From 90729ffd5b54204a724e08789597e3dab01e3199 Mon Sep 17 00:00:00 2001 From: Lekia Prosper Date: Sun, 16 Aug 2026 19:39:16 -0400 Subject: [PATCH 01/13] Add validation to prevent negative temperature and concentration float values --- src/pyked/validation.py | 67 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 66 insertions(+), 1 deletion(-) diff --git a/src/pyked/validation.py b/src/pyked/validation.py index 401e928..0f13426 100644 --- a/src/pyked/validation.py +++ b/src/pyked/validation.py @@ -397,7 +397,8 @@ def _validate_isvalid_speciation(self, isvalid_speciation, field, value): Each concentration profile row must carry one value per declared independent variable, followed by the measured amount, with an - optional trailing uncertainty. + optional trailing uncertainty. Amounts and auxiliary profile values are + also checked for physical possibility. The rule's arguments are validated against this schema: {'type': 'boolean'} @@ -419,6 +420,70 @@ def _validate_isvalid_speciation(self, isvalid_speciation, field, value): "independent-variable(s) + amount [+ uncertainty]); " f"got {len(row)}", ) + continue + + # Zero is meaningful here, since a species can be measured as + # absent, so only a negative amount is an error. This matches + # the view `isvalid_composition` and `isvalid_quantity` take of + # a composition amount. + amount = row[n_independent] + if isinstance(amount, (int, float)) and amount < 0: + self._error( + field, + f"concentration-profiles amount for {species} must not " + f"be negative; got {amount}", + ) + + self._check_auxiliary_profile_values(field, value) + + def _check_auxiliary_profile_values(self, field, value): + """Check that auxiliary profile values are physically possible. + + A profile records a measured history, so its units are declared once in + the profile's ``quantity`` block rather than on each point. That puts + the points out of reach of ``isvalid_quantity``, which is what lets a + value such as a negative absolute temperature pass otherwise. + + Args: + field (`str`): property the profiles belong to, used in the error + value (`dict`): the datapoint being validated + """ + for profile in value.get("auxiliary-profiles", []): + profile_type = profile.get("type") + expected_units = property_units.get(profile_type) + if expected_units is None: + # No dimension is configured for this type, so there is no sign + # convention to enforce against it. + continue + + unit_str = (profile.get("quantity") or {}).get("units") + if not unit_str: + continue + + for row in profile.get("values", []): + if len(row) < 2 or not isinstance(row[1], (int, float)): + continue + + quantity = self._parse_quantity(field, f"{row[1]} {unit_str}") + if quantity is None: + break + try: + magnitude = quantity.to(expected_units).magnitude + except pint.DimensionalityError: + self._error( + field, + f"auxiliary-profiles {profile_type} has incompatible " + f"units; should be consistent with {expected_units}", + ) + break + + if magnitude <= 0: + self._error( + field, + f"auxiliary-profiles {profile_type} value must be " + f"greater than 0.0 {expected_units}; got " + f"{row[1]} {unit_str}", + ) def _validate_isvalid_quantity(self, isvalid_quantity, field, value): """Checks for valid given value and appropriate units. From 3ce027b07913bdfa48a9f078aba6b03da3180889 Mon Sep 17 00:00:00 2001 From: Lekia Prosper Date: Sun, 16 Aug 2026 20:30:30 -0400 Subject: [PATCH 02/13] Validate temperature on the absolute scale, so Celsius and Fahrenheit values are accepted --- src/pyked/validation.py | 53 ++++++++++++---- tests/test_validation.py | 127 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 167 insertions(+), 13 deletions(-) diff --git a/src/pyked/validation.py b/src/pyked/validation.py index 0f13426..c6e7af5 100644 --- a/src/pyked/validation.py +++ b/src/pyked/validation.py @@ -422,7 +422,7 @@ def _validate_isvalid_speciation(self, isvalid_speciation, field, value): ) continue - # Zero is meaningful here, since a species can be measured as + # Zero is meaningful, since a species can be measured as # absent, so only a negative amount is an error. This matches # the view `isvalid_composition` and `isvalid_quantity` take of # a composition amount. @@ -464,11 +464,14 @@ def _check_auxiliary_profile_values(self, field, value): if len(row) < 2 or not isinstance(row[1], (int, float)): continue - quantity = self._parse_quantity(field, f"{row[1]} {unit_str}") - if quantity is None: - break + # Build the quantity from value and unit separately. The string + # form "-10 degC" reads as a multiplication, which Pint refuses + # for an offset unit, so it would reject an ordinary Celsius + # temperature as unparseable. Converting to the absolute scale + # first is also what makes the sign test meaningful: -10 degC is + # 263.15 K and perfectly physical, while -1111 K is not. try: - magnitude = quantity.to(expected_units).magnitude + magnitude = Q_(row[1], unit_str).to(expected_units).magnitude except pint.DimensionalityError: self._error( field, @@ -476,6 +479,13 @@ def _check_auxiliary_profile_values(self, field, value): f"units; should be consistent with {expected_units}", ) break + except Exception: # noqa: BLE001 - Pint raises several types for bad units + self._error( + field, + f"auxiliary-profiles {profile_type} has units " + f"{unit_str!r} that cannot be understood", + ) + break if magnitude <= 0: self._error( @@ -514,19 +524,24 @@ def _validate_isvalid_quantity(self, isvalid_quantity, field, value): self._error(field, "value must not be negative") return - low_lim = 0.0 * units(expected_units) - + # Convert before comparing, rather than comparing against a zero of the + # expected units. Celsius and Fahrenheit are interval scales, so the + # sign of the value as written says nothing: -10 degC is 263.15 K and + # perfectly physical. Only the value on the absolute scale can be tested. try: - if quantity <= low_lim: - self._error( - field, - f"value must be greater than 0.0 {expected_units}", - ) + converted = quantity.to(expected_units) except pint.DimensionalityError: self._error( field, f"incompatible units; should be consistent with {expected_units}", ) + return + + if converted.magnitude <= 0: + self._error( + field, + f"value must be greater than 0.0 {expected_units}", + ) def _parse_quantity(self, field, value): """Read a value into a Pint quantity, reporting an error if it cannot be read. @@ -538,8 +553,20 @@ def _parse_quantity(self, field, value): Returns: `~pint.Quantity`, or `None` if the value could not be read """ + normalized = _normalize_unit_str(value) + + try: + return Q_(normalized) + except Exception: # noqa: BLE001 - Pint raises several unrelated types for bad input + pass + + # Retry with the magnitude and the unit given separately. Pint reads a + # string such as "25 degC" as a multiplication and refuses that for an + # offset unit, so an ordinary Celsius or Fahrenheit temperature parses + # only in the two-argument form. + magnitude, _, unit_str = normalized.partition(" ") try: - return Q_(_normalize_unit_str(value)) + return Q_(float(magnitude), unit_str) except Exception: # noqa: BLE001 - Pint raises several unrelated types for bad input self._error(field, f"{value!r} is not a value with units that can be understood") return None diff --git a/tests/test_validation.py b/tests/test_validation.py index b616334..7317d85 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -1401,3 +1401,130 @@ def test_composition_thermo_bad(self, properties, mock_all_apis): thermo["T_ranges"] = [200.0, "1000 K", 5000.0] properties["datapoints"][0]["composition"]["species"][0]["thermo"] = thermo assert not v.validate(properties) + + +class TestSpeciationProfilePhysicality: + """Profile values are checked for physical possibility. + + A profile declares its units once, in the ``quantity`` block, rather than on + each point, so its values never reach ``isvalid_quantity``. Without a check + of their own they can hold anything a float can hold, including a negative + absolute temperature. + """ + + SPECIATION_FIXTURE = Path("tests") / "data" / "respecth" / "speciation" / "x60200017.yaml" + + @pytest.fixture(scope="function") + def properties(self): + with open(self.SPECIATION_FIXTURE, encoding="utf-8") as f: + properties = yaml.safe_load(f) + + # Borrow a reference and authorship the API mocks already know, so these + # tests exercise the profile rules rather than the DOI/ORCID lookups. + with open(Path("tests") / "testfile_st.yaml", encoding="utf-8") as f: + mocked = yaml.safe_load(f) + properties["reference"] = mocked["reference"] + properties["file-authors"] = mocked["file-authors"] + return properties + + def _errors(self, properties): + v.validate(properties) + return str(v.errors) + + def test_fixture_is_valid(self, properties, mock_all_apis): + """The unmodified fixture validates, so later failures are the edit's doing.""" + assert v.validate(properties), v.errors + + def test_negative_auxiliary_temperature_rejected(self, properties, mock_all_apis): + """A negative absolute temperature cannot be measured.""" + profile = properties["datapoints"][0]["auxiliary-profiles"][0] + assert profile["type"] == "temperature" + profile["values"][-1][1] = -1111.0 + + errors = self._errors(properties) + assert "auxiliary-profiles temperature value must be greater than 0.0 kelvin" in errors + + def test_zero_auxiliary_temperature_rejected(self, properties, mock_all_apis): + """Absolute zero is unreachable, so it marks missing data too.""" + properties["datapoints"][0]["auxiliary-profiles"][0]["values"][-1][1] = 0.0 + + errors = self._errors(properties) + assert "auxiliary-profiles temperature value must be greater than 0.0 kelvin" in errors + + @pytest.mark.parametrize("sentinel", [-1.0, -9.9999e94, -9.9999e99, -9.9999e-99]) + def test_negative_concentration_rejected(self, properties, sentinel, mock_all_apis): + """A concentration cannot be negative, whatever placeholder produced it.""" + properties["datapoints"][0]["concentration-profiles"][0]["values"][0][1] = sentinel + + errors = self._errors(properties) + assert "must not be negative" in errors + + def test_zero_concentration_allowed(self, properties, mock_all_apis): + """Zero is meaningful: a species can be measured as absent.""" + properties["datapoints"][0]["concentration-profiles"][0]["values"][0][1] = 0.0 + + assert v.validate(properties), v.errors + + @pytest.mark.parametrize( + "value, unit, physical", + [ + (-10.0, "degC", True), # 263.15 K, an ordinary cold temperature + (25.0, "degC", True), # 298.15 K, room temperature + (-10.0, "degF", True), # 249.82 K + (-273.15, "degC", False), # exactly 0 K, unattainable + (-300.0, "degC", False), # below absolute zero + (-1111.0, "K", False), # the sentinel seen in converted files + ], + ) + def test_temperature_is_judged_on_the_absolute_scale( + self, properties, value, unit, physical, mock_all_apis + ): + """Celsius and Fahrenheit are interval scales, so a negative number is fine. + + Only the temperature converted to kelvin has to be above zero, which is + what makes -10 degC acceptable while -1111 K is not. + """ + profile = properties["datapoints"][0]["auxiliary-profiles"][0] + profile["quantity"]["units"] = unit + for row in profile["values"]: + row[1] = value + + if physical: + assert v.validate(properties), v.errors + else: + assert "must be greater than 0.0 kelvin" in self._errors(properties) + + +class TestScalarTemperatureScale: + """A scalar temperature is judged after conversion to the absolute scale. + + Celsius and Fahrenheit are interval scales, so the sign of the value as + written carries no physical meaning on its own. + """ + + @pytest.mark.parametrize( + "temperature", + ["25 degC", "-10 degC", "-10 degF", "300 K", "1 K"], + ) + def test_physical_temperatures_accepted(self, temperature): + """-10 degC is 263.15 K, an ordinary temperature, and must not be refused.""" + assert v.validate({"datapoints": [{"temperature": [temperature]}]}, update=True), v.errors + + @pytest.mark.parametrize( + "temperature", + ["-273.15 degC", "-300 degC", "-1111 K", "0 K", "-460 degF"], + ) + def test_temperatures_at_or_below_absolute_zero_rejected(self, temperature): + """The third law puts a hard floor at 0 K, and 0 K itself is unattainable.""" + v.validate({"datapoints": [{"temperature": [temperature]}]}, update=True) + assert "value must be greater than 0.0 kelvin" in str(v.errors) + + def test_wrong_dimension_still_reported_as_such(self): + """A dimension error must not be reported as a sign error.""" + v.validate({"datapoints": [{"temperature": ["5 meter"]}]}, update=True) + assert "incompatible units" in str(v.errors) + + def test_unreadable_value_still_reported_as_such(self): + """The two-argument retry must not swallow genuinely bad input.""" + v.validate({"datapoints": [{"temperature": ["not a temperature"]}]}, update=True) + assert "is not a value with units that can be understood" in str(v.errors) From 51bddb1dd281de29a83f67239fa2d32b3acfb633 Mon Sep 17 00:00:00 2001 From: Lekia Prosper Date: Sun, 16 Aug 2026 21:47:32 -0400 Subject: [PATCH 03/13] Accept an absolute uncertainty of exactly zero --- CHANGELOG.md | 3 +++ src/pyked/validation.py | 27 +++++++++++++++++++++- tests/test_validation.py | 50 ++++++++++++++++++++++++++++++++++++++-- 3 files changed, 77 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ee88c29..e822e7b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,11 +16,13 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Round-trip tests asserting the converter reproduces each checked-in ReSpecTh/ChemKED fixture pair - `resolve_reference` maps an uncertainty that points at a column by its `label` or `id`, and one that references `initial composition`, onto the quantity it describes; both were silently dropped before - `0.5.0` added to the allowed `chemked-version` values, and a test asserting the current `__version__` is always among them, since `get_file_metadata` stamps it into every converted file +- Physicality checks on speciation profile values: a `concentration-profiles` amount may not be negative, and an `auxiliary-profiles` temperature, pressure or volume must be above zero on its absolute scale. Profile values declare their units once in the `quantity` block rather than per point, so they never reached `isvalid_quantity` and could hold any float, including the -1111 K and -9.9999e+94 missing-data placeholders that ReSpecTh conversions carry through ### Changed - The `tubular reactor` apparatus kind is renamed `flow reactor`, the name ReSpecTh, the ChemKED database, and the speciation literature all use. `tubular reactor` is still accepted as converter input and maps to `flow reactor` - The mole and mass fraction sum check uses a relative tolerance of 1e-3 (`composition_sum_tolerance`) rather than the NumPy default of 1e-5, so compositions reported to a few digits are not rejected for round-off - An auxiliary profile against a `residence-time` axis is recorded with the axis name `time`, which `auxiliary-profiles.independent.name` allows, since a residence time is a time coordinate +- An absolute uncertainty of exactly zero is accepted, meaning none was reported. The quantity it describes must still be above zero, but the uncertainty itself may be zero, the same view `isvalid_composition` takes of a composition amount of zero. Only a negative uncertainty is an error, reported as `uncertainty must not be negative` ### Fixed - A composition amount of exactly zero, meaning a species measured as absent, is accepted when it carries uncertainty metadata. It was accepted without metadata and rejected with it, and `isvalid_composition` already allowed it. Only a negative value is an error for a property with no configured units @@ -34,6 +36,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - `ignitionType` is only required for ignition delay files - `composition_schema.yaml` now references the shared `uncertainty-metadata` definition instead of a hand-copied duplicate that had drifted to `type: float`, so a species amount accepts the same uncertainty forms as every other quantity. The definition is hoisted to its own top-level anchor in `value_unit_schema.yaml` - Composition units accept concentrations (`mol/cm3`, `mol/m3`, `mol/dm3`, `mol/L`), the misspelling `mole faction` found in part of the ReSpecTh corpus, and a mixture of mole percent and mole fraction, which is reconciled onto mole fraction +- A temperature in an offset unit is parsed and validated correctly. `temperature: ['25 degC']` was rejected as unreadable, because Pint reads the string form `"25 degC"` as a multiplication and refuses that for an offset unit, and because the sign check compared the quantity against a zero in kelvin. Values are now built with Pint's two-argument form and converted to the absolute scale before the check, so -10 degC is accepted as 263.15 K while -1111 K and 0 K are still rejected ## [0.5.0] - 2026-07-02 ### Added diff --git a/src/pyked/validation.py b/src/pyked/validation.py index c6e7af5..02c0a1d 100644 --- a/src/pyked/validation.py +++ b/src/pyked/validation.py @@ -584,7 +584,32 @@ def _check_uncertainty_value(self, field, key, value, kind): kind (`str`): ``relative`` or ``absolute`` """ if kind != "relative": - self._validate_isvalid_quantity(True, field, [value]) + # Zero means no uncertainty was reported, not an impossible + # measurement, so it is accepted here even though the quantity it + # describes must itself be above zero. `isvalid_composition` takes + # the same view of a composition amount of exactly zero. Only a + # negative uncertainty is an error. + quantity = self._parse_quantity(field, value) + if quantity is None: + return + + expected_units = property_units.get(field) + if expected_units is None: + if quantity.magnitude < 0: + self._error(field, "uncertainty must not be negative") + return + + try: + converted = quantity.to(expected_units) + except pint.DimensionalityError: + self._error( + field, + f"incompatible units; should be consistent with {expected_units}", + ) + return + + if converted.magnitude < 0: + self._error(field, "uncertainty must not be negative") return quantity = self._parse_quantity(field, value) diff --git a/tests/test_validation.py b/tests/test_validation.py index 7317d85..d2f24c1 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -1172,7 +1172,7 @@ def test_incompatible_sym_uncertainty(self, quantity, unit): ] } ) - assert v.errors[quantity][0] == f"value must be greater than 0.0 {unit}" + assert v.errors[quantity][0] == "uncertainty must not be negative" @pytest.mark.parametrize("quantity, unit", property_units.items()) def test_dimensionality_error_sym_uncertainty(self, quantity, unit): @@ -1259,7 +1259,7 @@ def test_incompatible_asym_uncertainty(self, quantity, unit): ] } ) - assert v.errors[quantity][0] == f"value must be greater than 0.0 {unit}" + assert v.errors[quantity][0] == "uncertainty must not be negative" @pytest.mark.parametrize("quantity, unit", property_units.items()) def test_dimensionality_error_asym_uncertainty(self, quantity, unit): @@ -1528,3 +1528,49 @@ def test_unreadable_value_still_reported_as_such(self): """The two-argument retry must not swallow genuinely bad input.""" v.validate({"datapoints": [{"temperature": ["not a temperature"]}]}, update=True) assert "is not a value with units that can be understood" in str(v.errors) + + +class TestZeroUncertainty: + """An absolute uncertainty of exactly zero means none was reported. + + The quantity it describes must still be above zero, but the uncertainty + itself may be zero, the same view `isvalid_composition` takes of a + composition amount of exactly zero. + """ + + @pytest.mark.parametrize("quantity, unit", property_units.items()) + def test_zero_absolute_uncertainty_accepted(self, quantity, unit): + """A reported uncertainty of 0 must not invalidate the measurement.""" + quant_schema = {quantity: {"type": "list", "isvalid_uncertainty": True}} + validator = OurValidator(quant_schema) + assert validator.validate( + { + quantity: [ + f"999 {unit}", + {"uncertainty-type": "absolute", "uncertainty": f"0.0 {unit}"}, + ] + } + ), validator.errors + + @pytest.mark.parametrize("quantity, unit", property_units.items()) + def test_negative_absolute_uncertainty_still_rejected(self, quantity, unit): + """Relaxing zero must not let a negative uncertainty through.""" + quant_schema = {quantity: {"type": "list", "isvalid_uncertainty": True}} + validator = OurValidator(quant_schema) + validator.validate( + { + quantity: [ + f"999 {unit}", + {"uncertainty-type": "absolute", "uncertainty": f"-1 {unit}"}, + ] + } + ) + assert validator.errors[quantity][0] == "uncertainty must not be negative" + + @pytest.mark.parametrize("quantity, unit", property_units.items()) + def test_zero_value_still_rejected(self, quantity, unit): + """The measured quantity itself is unchanged: zero remains an error.""" + quant_schema = {quantity: {"type": "list", "isvalid_quantity": True}} + validator = OurValidator(quant_schema) + validator.validate({quantity: [f"0.0 {unit}"]}) + assert validator.errors[quantity][0] == f"value must be greater than 0.0 {unit}" From 67bc7f453211de13cde28e9b42b3b9f131f16804 Mon Sep 17 00:00:00 2001 From: Lekia Prosper Date: Sun, 16 Aug 2026 22:10:22 -0400 Subject: [PATCH 04/13] Normalize numeric values and page ranges when converting from ReSpecTh --- CHANGELOG.md | 1 + src/pyked/converters.py | 38 ++++++++++++++++++++++++++++++++++++-- tests/test_converters.py | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e822e7b..8b0abd0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - `composition_schema.yaml` now references the shared `uncertainty-metadata` definition instead of a hand-copied duplicate that had drifted to `type: float`, so a species amount accepts the same uncertainty forms as every other quantity. The definition is hoisted to its own top-level anchor in `value_unit_schema.yaml` - Composition units accept concentrations (`mol/cm3`, `mol/m3`, `mol/dm3`, `mol/L`), the misspelling `mole faction` found in part of the ReSpecTh corpus, and a mixture of mole percent and mole fraction, which is reconciled onto mole fraction - A temperature in an offset unit is parsed and validated correctly. `temperature: ['25 degC']` was rejected as unreadable, because Pint reads the string form `"25 degC"` as a multiplication and refuses that for an offset unit, and because the sign check compared the quantity against a zero in kelvin. Values are now built with Pint's two-argument form and converted to the absolute scale before the check, so -10 degC is accepted as 263.15 K while -1111 K and 0 K are still rejected +- Numeric values are normalized on conversion by the new `normalize_value`: leading zeros are stripped, since YAML reads them as octal, and a Fortran-style exponent written without the `e` is expanded so Pint can read it. Trailing zeros are deliberately left alone, being significant figures. A page range no longer keeps spaces around its dash, so it reads `446-457` rather than `446 - 457` ## [0.5.0] - 2026-07-02 ### Added diff --git a/src/pyked/converters.py b/src/pyked/converters.py index daa35a5..2fc54a1 100644 --- a/src/pyked/converters.py +++ b/src/pyked/converters.py @@ -247,6 +247,38 @@ def normalize_units(unit_str): return _normalize_unit_str(f"1.0 {unit_str.strip()}").split(" ", 1)[1] +def normalize_value(value): + """Normalize a numeric value as written in ReSpecTh for use in ChemKED. + + Expands Fortran-style exponents written without the ``e``, which Pint cannot + read, and strips leading zeros, which YAML would otherwise take for octal. + + The digits the source reported are otherwise left alone. A trailing zero is a + significant figure, so reformatting through a float would turn a reported + ``14.70`` into ``14.7`` and record three significant figures where the + authors stated four. + + Args: + value (`str`): Value as written in the ReSpecTh file + + Returns: + `str`: The same value, normalized + """ + text = str(value).strip() + + # Fortran-style exponent written without the 'e': '5.93+005' -> '5.93e+005' + text = re.sub(r"^([+-]?\d+\.?\d*)([+-]\d+)$", r"\1e\2", text) + + # Strip leading zeros from the integer part only, keeping the fraction and + # exponent exactly as written. Anything that is not a plain decimal, such as + # 'NaN' or '.5', is passed through untouched. + match = re.fullmatch(r"([+-]?)0*(\d+)(\.\d*)?([eE][+-]?\d+)?", text) + if match is None: + return text + sign, integer, fraction, exponent = match.groups() + return f"{sign}{integer}{fraction or ''}{exponent or ''}" + + def value_with_units(value, unit_str): """Build a ChemKED value-with-units string from ReSpecTh text. @@ -257,7 +289,7 @@ def value_with_units(value, unit_str): Returns: `str`: Value and units joined in a form the ChemKED schema accepts """ - return f"{value.strip()} {normalize_units(unit_str)}" + return f"{normalize_value(value)} {normalize_units(unit_str)}" def check_units(name, field, unit_str): @@ -387,7 +419,9 @@ def get_reference_details(elem): pages = details.findtext("pages") if pages is not None: # ReSpecTh writes page ranges with en dashes or doubled hyphens; ChemKED uses one hyphen - reference["pages"] = re.sub(r"[-–—]+", "-", pages.strip()) + # Collapse any spacing around the dash too, so a range reads "446-457" + # rather than "446 - 457". + reference["pages"] = re.sub(r"\s*[-–—]+\s*", "-", pages.strip()) return reference diff --git a/tests/test_converters.py b/tests/test_converters.py index 593927b..cbe0fca 100644 --- a/tests/test_converters.py +++ b/tests/test_converters.py @@ -17,6 +17,8 @@ # Local imports from pyked.converters import ( + normalize_value, + value_with_units, KeywordError, MissingAttributeError, MissingElementError, @@ -2474,3 +2476,35 @@ def test_conversion_invalid_file_type(self): with pytest.raises(KeywordError) as excinfo: main(["-i", str(file_path), "-o", "test.py"]) assert "Input/output args need to be .xml/.yaml" in str(excinfo.value) + + +class TestNormalizeValue: + """Numeric values are normalized without changing what the source stated.""" + + @pytest.mark.parametrize( + "text, expected", + [ + ("0626", "626"), # leading zero, which YAML would read as octal + ("09.45", "9.45"), + ("007", "7"), + ("-09.450", "-9.450"), + ("+07.5", "+7.5"), + ("0.5", "0.5"), # lone leading zero is kept + ("0", "0"), + ("5.93+005", "5.93e+005"), # Fortran exponent Pint cannot read + ], + ) + def test_normalized(self, text, expected): + assert normalize_value(text) == expected + + @pytest.mark.parametrize("text", ["14.70", "8.10", "1000", "0.000", "1.5e-3", "2.724"]) + def test_significant_figures_preserved(self, text): + """A trailing zero is a significant figure and must survive.""" + assert normalize_value(text) == text + + @pytest.mark.parametrize("text", ["NaN", ".5", "inf", "not a number"]) + def test_unparseable_passed_through(self, text): + assert normalize_value(text) == text + + def test_used_by_value_with_units(self): + assert value_with_units("0626", "us") == "626 us" From b0d42daa0922704661562c67bc690c9ce4304c2c Mon Sep 17 00:00:00 2001 From: Lekia Prosper Date: Sun, 16 Aug 2026 22:12:55 -0400 Subject: [PATCH 05/13] Unescape HTML entities in journal and author names from CrossRef --- CHANGELOG.md | 1 + src/pyked/converters.py | 7 +++++-- tests/_mock_data.py | 8 ++++++++ tests/test_converters.py | 13 +++++++++++++ 4 files changed, 27 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b0abd0..62e5de6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Composition units accept concentrations (`mol/cm3`, `mol/m3`, `mol/dm3`, `mol/L`), the misspelling `mole faction` found in part of the ReSpecTh corpus, and a mixture of mole percent and mole fraction, which is reconciled onto mole fraction - A temperature in an offset unit is parsed and validated correctly. `temperature: ['25 degC']` was rejected as unreadable, because Pint reads the string form `"25 degC"` as a multiplication and refuses that for an offset unit, and because the sign check compared the quantity against a zero in kelvin. Values are now built with Pint's two-argument form and converted to the absolute scale before the check, so -10 degC is accepted as 263.15 K while -1111 K and 0 K are still rejected - Numeric values are normalized on conversion by the new `normalize_value`: leading zeros are stripped, since YAML reads them as octal, and a Fortran-style exponent written without the `e` is expanded so Pint can read it. Trailing zeros are deliberately left alone, being significant figures. A page range no longer keeps spaces around its dash, so it reads `446-457` rather than `446 - 457` +- Text taken from a CrossRef DOI lookup is HTML-unescaped, so a journal reaches the file as `Energy & Fuels` rather than `Energy & Fuels`. Author names are unescaped the same way ## [0.5.0] - 2026-07-02 ### Added diff --git a/src/pyked/converters.py b/src/pyked/converters.py index 2fc54a1..afb9d4c 100644 --- a/src/pyked/converters.py +++ b/src/pyked/converters.py @@ -1,6 +1,7 @@ """Module with converters from other formats.""" # Standard libraries +import html import re import xml.etree.ElementTree as etree from argparse import ArgumentParser @@ -486,7 +487,9 @@ def get_reference(root): reference["doi"] = ref_doi # Now get elements of the reference data # Assume that the reference returned by the DOI lookup always has a container-title - reference["journal"] = ref.get("container-title")[0] + # CrossRef returns HTML-escaped text, so a journal such as + # "Energy & Fuels" arrives with the entity intact. + reference["journal"] = html.unescape(ref.get("container-title")[0]) ref_year = ref.get("published-print") or ref.get("published-online") reference["year"] = int(ref_year["date-parts"][0][0]) reference["volume"] = int(ref.get("volume")) @@ -494,7 +497,7 @@ def get_reference(root): reference["authors"] = [] for author in ref["author"]: auth = {} - auth["name"] = " ".join([author["given"], author["family"]]) + auth["name"] = html.unescape(" ".join([author["given"], author["family"]])) # Add ORCID if available orcid = author.get("ORCID") if orcid: diff --git a/tests/_mock_data.py b/tests/_mock_data.py index 9834b05..9d9069e 100644 --- a/tests/_mock_data.py +++ b/tests/_mock_data.py @@ -1,6 +1,14 @@ """Shared mock data for Crossref and ORCID APIs used by conftest.py and test_live_api.py.""" CROSSREF_RESPONSES = { + # Journal and author names as CrossRef actually returns them: HTML-escaped. + "10.1021/mock.escaped": { + "container-title": ["Energy & Fuels"], + "published-print": {"date-parts": [[2015]]}, + "volume": "29", + "page": "1-2", + "author": [{"given": "A&B", "family": "Author"}], + }, "10.1016/j.ijhydene.2007.04.008": { "container-title": ["International Journal of Hydrogen Energy"], "published-print": {"date-parts": [[2007]]}, diff --git a/tests/test_converters.py b/tests/test_converters.py index cbe0fca..71509d5 100644 --- a/tests/test_converters.py +++ b/tests/test_converters.py @@ -2508,3 +2508,16 @@ def test_unparseable_passed_through(self, text): def test_used_by_value_with_units(self): assert value_with_units("0626", "us") == "626 us" + + +class TestCrossrefTextIsUnescaped: + """CrossRef returns HTML-escaped text, which must not reach the ChemKED file.""" + + def test_journal_and_author_unescaped(self, mock_crossref_api): + """`Energy & Fuels` is not a journal name.""" + root = etree.fromstring( + '' + ) + reference = get_reference(root) + assert reference["journal"] == "Energy & Fuels" + assert reference["authors"][0]["name"] == "A&B Author" From e3029ddc7ba5b19f4c24ca643d8c43f9a7aa7145 Mon Sep 17 00:00:00 2001 From: Lekia Prosper Date: Sun, 16 Aug 2026 22:15:34 -0400 Subject: [PATCH 06/13] Compare CrossRef journal and author names unescaped during validation --- src/pyked/validation.py | 7 ++++++- tests/test_validation.py | 21 +++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/pyked/validation.py b/src/pyked/validation.py index 02c0a1d..d3c84d7 100644 --- a/src/pyked/validation.py +++ b/src/pyked/validation.py @@ -1,5 +1,6 @@ """Validation class for ChemKED schema.""" +import html import re from importlib import resources from warnings import warn @@ -717,7 +718,9 @@ def _validate_isvalid_reference(self, isvalid_reference, field, value): return # Assume that the reference returned by the DOI lookup always has a container-title - ref_container = ref.get("container-title")[0] + # CrossRef returns HTML-escaped text, and the converter unescapes it before + # writing, so unescape here too or the two never agree on "Energy & Fuels". + ref_container = html.unescape(ref.get("container-title")[0]) # TODO: Add other container types: value.get('journal') or value.get('report') or ... # note that there's a type field in the ref that is journal-article, proceedings-article container = value.get("journal") @@ -762,6 +765,8 @@ def _validate_isvalid_reference(self, isvalid_reference, field, value): authors = value["authors"][:] author_names = [a["name"] for a in authors] for author in ref["author"]: + author = {**author, "given": html.unescape(author.get("given", "")), + "family": html.unescape(author.get("family", ""))} # find using family name author_match = next( ( diff --git a/tests/test_validation.py b/tests/test_validation.py index d2f24c1..0e1f194 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -1574,3 +1574,24 @@ def test_zero_value_still_rejected(self, quantity, unit): validator = OurValidator(quant_schema) validator.validate({quantity: [f"0.0 {unit}"]}) assert validator.errors[quantity][0] == f"value must be greater than 0.0 {unit}" + + +class TestCrossrefComparisonUnescapes: + """The converter unescapes CrossRef text, so validation must compare likewise.""" + + def test_unescaped_journal_accepted(self, mock_crossref_api): + """`Energy & Fuels` is what the converter writes, and must validate.""" + v.validate( + { + "reference": { + "doi": "10.1021/mock.escaped", + "journal": "Energy & Fuels", + "year": 2015, + "volume": 29, + "pages": "1-2", + "authors": [{"name": "A&B Author"}], + } + }, + update=True, + ) + assert not [e for e in str(v.errors).split(",") if "journal should be" in e] From 787de82aa999c7453e07cf525dfbc885ee354401 Mon Sep 17 00:00:00 2001 From: Lekia Prosper Date: Mon, 17 Aug 2026 00:12:35 -0400 Subject: [PATCH 07/13] Strip a resolver prefix from a DOI written as a URL --- CHANGELOG.md | 1 + src/pyked/converters.py | 21 ++++++++++++++++++++- tests/test_converters.py | 20 ++++++++++++++++++++ 3 files changed, 41 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 62e5de6..80d5ee1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - A temperature in an offset unit is parsed and validated correctly. `temperature: ['25 degC']` was rejected as unreadable, because Pint reads the string form `"25 degC"` as a multiplication and refuses that for an offset unit, and because the sign check compared the quantity against a zero in kelvin. Values are now built with Pint's two-argument form and converted to the absolute scale before the check, so -10 degC is accepted as 263.15 K while -1111 K and 0 K are still rejected - Numeric values are normalized on conversion by the new `normalize_value`: leading zeros are stripped, since YAML reads them as octal, and a Fortran-style exponent written without the `e` is expanded so Pint can read it. Trailing zeros are deliberately left alone, being significant figures. A page range no longer keeps spaces around its dash, so it reads `446-457` rather than `446 - 457` - Text taken from a CrossRef DOI lookup is HTML-unescaped, so a journal reaches the file as `Energy & Fuels` rather than `Energy & Fuels`. Author names are unescaped the same way +- A DOI written as a resolvable URL, such as `doi.org/10.1016/j.proci.2016.05.048`, is reduced to the bare identifier on conversion. Some ReSpecTh files write it that way and no DOI lookup accepts it ## [0.5.0] - 2026-07-02 ### Added diff --git a/src/pyked/converters.py b/src/pyked/converters.py index afb9d4c..786d66d 100644 --- a/src/pyked/converters.py +++ b/src/pyked/converters.py @@ -427,6 +427,23 @@ def get_reference_details(elem): return reference +def normalize_doi(doi): + """Strip a resolver prefix from a DOI as ReSpecTh sometimes writes it. + + A DOI is the bare `10.xxxx/...` identifier. Some ReSpecTh files give a + resolvable URL instead, as in `doi.org/10.1016/j.proci.2016.05.048`, which + no lookup accepts. + + Args: + doi (`str`): DOI as written in the ReSpecTh file + + Returns: + `str`: The bare DOI + """ + doi = doi.strip() + return re.sub(r"^(?:doi:|(?:https?://)?(?:dx\.)?doi\.org/)", "", doi, flags=re.I) + + def get_reference(root): """Read reference info from root of ReSpecTh XML file. @@ -443,13 +460,15 @@ def get_reference(root): # Try to get reference info via DOI, fall back on preferredKey if necessary. ref_doi = elem.get("doi", None) + if ref_doi is not None: + ref_doi = normalize_doi(ref_doi) ref_key = elem.get("preferredKey", None) # ReSpecTh 2.x keeps the same information in child elements if ref_doi is None: ref_doi = getattr(elem.find("referenceDOI"), "text", None) if ref_doi is not None: - ref_doi = ref_doi.strip() or None + ref_doi = normalize_doi(ref_doi) or None if ref_key is None: ref_key = getattr(elem.find("description"), "text", None) if ref_key is not None: diff --git a/tests/test_converters.py b/tests/test_converters.py index 71509d5..523bbfb 100644 --- a/tests/test_converters.py +++ b/tests/test_converters.py @@ -17,6 +17,7 @@ # Local imports from pyked.converters import ( + normalize_doi, normalize_value, value_with_units, KeywordError, @@ -2521,3 +2522,22 @@ def test_journal_and_author_unescaped(self, mock_crossref_api): reference = get_reference(root) assert reference["journal"] == "Energy & Fuels" assert reference["authors"][0]["name"] == "A&B Author" + + +class TestNormalizeDoi: + """A DOI is the bare identifier; ReSpecTh sometimes writes a resolvable URL.""" + + @pytest.mark.parametrize( + "written, expected", + [ + ("doi.org/10.1016/j.proci.2016.05.048", "10.1016/j.proci.2016.05.048"), + ("https://doi.org/10.1021/x", "10.1021/x"), + ("http://dx.doi.org/10.1/y", "10.1/y"), + ("doi:10.1/z", "10.1/z"), + ("DOI.ORG/10.1/upper", "10.1/upper"), + (" 10.1/spaced ", "10.1/spaced"), + ("10.1016/already.bare", "10.1016/already.bare"), + ], + ) + def test_prefix_stripped(self, written, expected): + assert normalize_doi(written) == expected From 947613a373c1102105f928a05331f064db72dbe8 Mon Sep 17 00:00:00 2001 From: Lekia Prosper Date: Mon, 26 Oct 2026 06:52:17 -0400 Subject: [PATCH 08/13] Write speciation measurements to ReSpecTh convert_to_ReSpecTh now writes a ChemKED speciation measurement as the ReSpecTh speciation type its apparatus and swept axis call for: jet stirred reactor, burner stabilized flame speciation, concentration time profile (shock tube or flow reactor against time), or outlet concentration measurement. It is the inverse of get_speciation_datapoints: each datapoint becomes a dataGroup with the independent variables, one column per concentration profile, conditions of that datapoint alone, auxiliary profiles and per-row uncertainties as columns. Shared conditions, the initial composition and uncertainties that describe a whole profile or quantity become common properties; an uncertainty the datapoints do not share is a column with one repeated value. The reference is written as ReSpecTh 2 details, so reading it back needs no DOI look-up. All 576 speciation files of ChemKED-database round-trip through ReSpecTh to an equal dict. get_value_metadata now keeps the bound of a common uncertainty, which was read as symmetric so a lower bound overwrote the upper one. No file in the local ReSpecTh corpus has a one-sided common uncertainty. --- CHANGELOG.md | 2 + docs/ck-tutorial.rst | 8 +- src/pyked/chemked.py | 690 +++++++++++++++++++++++++++++++- src/pyked/converters.py | 1 + tests/test_chemked.py | 497 ++++++++++++++++++++++- tests/test_converters.py | 21 + tests/test_respecth_fixtures.py | 16 + 7 files changed, 1217 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 80d5ee1..65cae54 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - `apparatus_kind` argument to `ReSpecTh_to_ChemKED` and `-ak/--apparatus-kind` to `respth2ck`, for files whose apparatus ReSpecTh records only as the generic `flame` - `uncertainty` and `evaluated standard deviation` properties and dataGroup columns are converted and attached to the quantity they describe, whether that is a datapoint value, a common property, a species amount, or a concentration profile - ReSpecTh `comment` elements are converted to ChemKED `comments` +- `convert_to_ReSpecTh` writes speciation measurements, as whichever of ReSpecTh's four speciation types fits the apparatus and the swept axis. Each datapoint becomes a dataGroup, the inverse of `get_speciation_datapoints`, so `ReSpecTh_to_ChemKED` reads the file back as the same ChemKED file; all 576 speciation files of the ChemKED database do - `isvalid_experiment` validation rule cross-checking `experiment-type` against the datapoint contents and the apparatus kind, which the `anyof` datapoints schema cannot do on its own - Round-trip tests asserting the converter reproduces each checked-in ReSpecTh/ChemKED fixture pair - `resolve_reference` maps an uncertainty that points at a column by its `label` or `id`, and one that references `initial composition`, onto the quantity it describes; both were silently dropped before @@ -25,6 +26,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - An absolute uncertainty of exactly zero is accepted, meaning none was reported. The quantity it describes must still be above zero, but the uncertainty itself may be zero, the same view `isvalid_composition` takes of a composition amount of zero. Only a negative uncertainty is an error, reported as `uncertainty must not be negative` ### Fixed +- An `uncertainty` common property with `bound="upper"` or `bound="lower"` was read as a symmetric uncertainty, so the second bound overwrote the first. The bound is now kept, as it already was for a dataGroup column - A composition amount of exactly zero, meaning a species measured as absent, is accepted when it carries uncertainty metadata. It was accepted without metadata and rejected with it, and `isvalid_composition` already allowed it. Only a negative value is an error for a property with no configured units - The unsupported-composition-units error lists the units the converter actually accepts, built from `composition_units` rather than hand-written, so it cannot fall behind the table again - Every text file is now opened with an explicit UTF-8 encoding. Reading or writing a ChemKED or ReSpecTh file whose author names contain non-ASCII characters previously depended on the platform's preferred encoding, and failed on Windows. `convert_to_ReSpecTh` could also rewrite its pretty-printed XML in the platform encoding while declaring UTF-8 in the file. The ruff rule `PLW1514` now enforces this diff --git a/docs/ck-tutorial.rst b/docs/ck-tutorial.rst index d13f7af..813dda1 100644 --- a/docs/ck-tutorial.rst +++ b/docs/ck-tutorial.rst @@ -543,8 +543,12 @@ the kind from the article instead: ReSpecTh_to_ChemKED('file.xml', apparatus_kind='outwardly propagating spherical flame') PyKED also provides a converter to generate ReSpecTh files based on ChemKED records. -Writing ReSpecTh files is still limited to ignition delay data; a laminar burning -velocity or speciation record raises `NotImplementedError`. +Ignition delay and speciation measurement records can be written; a laminar burning +velocity record raises `NotImplementedError`. A speciation measurement is written as the +ReSpecTh speciation type its apparatus and swept axis call for: a jet stirred reactor +measurement, a burner stabilized flame speciation measurement, a concentration time profile +measurement for a shock tube or flow reactor against time, or otherwise an outlet +concentration measurement. Given a ChemKED file ``file.yaml``, a corresponding ReSpecTh file can be created from the command line via diff --git a/src/pyked/chemked.py b/src/pyked/chemked.py index 7189798..cd0916d 100644 --- a/src/pyked/chemked.py +++ b/src/pyked/chemked.py @@ -4,7 +4,7 @@ import xml.dom.minidom as minidom import xml.etree.ElementTree as etree from copy import deepcopy -from itertools import chain +from itertools import chain, count from pathlib import Path from typing import Any, ClassVar, NamedTuple from warnings import warn @@ -12,11 +12,588 @@ import numpy as np import pint -from .converters import ReSpecTh_to_ChemKED, datagroup_properties +from .converters import ( + ReSpecTh_to_ChemKED, + auxiliary_axes, + common_property_fields, + composition_units, + datagroup_properties, + independent_variables, +) # Local imports from .validation import Q_, OurValidator, _normalize_unit_str, schema, yaml +respecth_property_names = {field: name for name, field in common_property_fields.items()} +"""`dict`: ChemKED field name mapped to the ReSpecTh property name, the inverse of +`~pyked.converters.common_property_fields`""" + +respecth_axis_names = {axis: name for name, axis in independent_variables.items()} +"""`dict`: Speciation independent-variable name mapped to the ReSpecTh dataGroup property name, +the inverse of `~pyked.converters.independent_variables`""" + +respecth_speciation_apparatus = { + "jet stirred reactor": ("jet stirred reactor", []), + "flow reactor": ("flow reactor", []), + "shock tube": ("shock tube", []), + # ReSpecTh names a flame generically and the burner in a mode + "burner stabilized flame": ("flame", ["burner-stabilized"]), +} +"""`dict`: ChemKED ``apparatus.kind`` of a speciation measurement mapped to the ReSpecTh +``apparatus/kind`` and ``apparatus/mode`` elements""" + +respecth_labels = { + "temperature": "T", + "pressure": "P", + "time": "t", + "residence time": "tau", + "distance": "x", + "volume": "V", + "equivalence ratio": "phi", +} +"""`dict`: ReSpecTh property name mapped to the column label ReSpecTh files give it""" + +concentration_kinds = {kind for kind, _, _ in composition_units.values() if "/" in kind} +"""`set`: Composition kinds that are concentrations, which ReSpecTh names ``concentration`` +rather than ``composition``""" + +speciation_profile_keys = [ + "independent-variables", + "concentration-profiles", + "auxiliary-profiles", + "time-shift", +] +"""`list`: Speciation datapoint fields that are written as dataGroup columns or elements of their +own rather than as properties""" + + +def _respecth_units(units): + """Spell units as ReSpecTh does, which writes a dimensionless quantity as ``unitless``.""" + if units is None or units.strip() in ["", "dimensionless"]: + return "unitless" + return units.strip() + + +def _split_value(value): + """Split a ChemKED value into the value text and the units ReSpecTh states it in. + + The value text is kept as written, so its significant figures survive the conversion. + """ + number, _, units = str(value).strip().partition(" ") + return number, _respecth_units(units) + + +def _metadata_items(metadata): + """Turn ChemKED uncertainty metadata into ReSpecTh uncertainty descriptors. + + The inverse of `~pyked.converters.format_value_metadata`: an uncertainty, each bound of an + asymmetric one, and an evaluated standard deviation each become a property of their own. + + Args: + metadata (`dict`): The metadata mapping of a ChemKED quantity or profile + + Returns: + `list`: One `dict` per ReSpecTh uncertainty or evaluated standard deviation property + """ + items = [] + bounds = { + "uncertainty": "plusminus", + "upper-uncertainty": "upper", + "lower-uncertainty": "lower", + } + for key, bound in bounds.items(): + if key in metadata: + items.append( + { + "name": "uncertainty", + "kind": metadata.get("uncertainty-type"), + "bound": bound, + "sourcetype": metadata.get("uncertainty-sourcetype"), + "value": metadata[key], + } + ) + + if "evaluated-standard-deviation" in metadata: + items.append( + { + "name": "evaluated standard deviation", + "kind": metadata.get("evaluated-standard-deviation-type"), + "sourcetype": metadata.get("evaluated-standard-deviation-sourcetype"), + "method": metadata.get("evaluated-standard-deviation-method"), + "value": metadata["evaluated-standard-deviation"], + } + ) + + return items + + +row_uncertainty = {"name": "uncertainty", "kind": "absolute", "bound": "plusminus", "value": ""} +"""`dict`: Descriptor of the uncertainty a ChemKED profile row may end with, which is an +absolute uncertainty in the units of the profile. Its values are in the rows, so it has none of +its own.""" + + +def _metadata_value(item, units): + """The value text of an uncertainty descriptor and the units ReSpecTh states it in. + + Args: + item (`dict`): Descriptor from `_metadata_items` + units (`str`): Units of the quantity the uncertainty is about, which an absolute value + without units of its own is stated in + + Returns: + `tuple`: The value text and its units + """ + value, own_units = _split_value(item["value"]) + if item["kind"] == "relative": + # A relative value is a fraction of the quantity + return value, "unitless" + if own_units == "unitless": + return value, _respecth_units(units) + return value, own_units + + +def _set_metadata_attributes(prop, item, reference, units, column_id=None): + """Describe a ReSpecTh uncertainty property and return its value text. + + Args: + prop (`~xml.etree.ElementTree.Element`): The ReSpecTh property to describe + item (`dict`): Descriptor from `_metadata_items` + reference (`str`): ReSpecTh name of the quantity the uncertainty is about + units (`str`): Units of that quantity + column_id (`str`, optional): The id of the property, when it is a dataGroup column + + Returns: + `str`: The value text + """ + value, units = _metadata_value(item, units) + prop.set("name", item["name"]) + if column_id is not None: + prop.set("id", column_id) + prop.set("units", units) + prop.set("reference", reference) + for attribute in ["kind", "bound", "sourcetype", "method"]: + if item.get(attribute) is not None: + prop.set(attribute, item[attribute]) + + return value + + +def _add_species_link(parent, species): + """Add a ReSpecTh speciesLink for a ChemKED species, profile, or swept inlet species.""" + link = etree.SubElement(parent, "speciesLink") + link.set("preferredKey", species["species-name"]) + for key in ["InChI", "SMILES"]: + if species.get(key) is not None: + link.set(key, species[key]) + + +def _add_metadata_property(parent, item, reference, units, species=None): + """Add an uncertainty that applies to every value of a quantity as a common property.""" + prop = etree.SubElement(parent, "property") + value = _set_metadata_attributes(prop, item, reference, units) + if species is not None: + _add_species_link(prop, species) + etree.SubElement(prop, "value").text = value + + +def _shared_value(values): + """The value every entry has, or `None` when they differ or the value is missing.""" + if not values or values[0] is None: + return None + if all(value == values[0] for value in values): + return values[0] + return None + + +def _speciation_experiment_type(apparatus_kind, datapoints): + """Pick the ReSpecTh experiment type for a ChemKED speciation measurement. + + ReSpecTh keeps four speciation types where ChemKED has one. The apparatus says which, and for a + shock tube or flow reactor so does the swept axis: profiles against time are concentration + time profiles, while sweeps of temperature or residence time sample the outlet. + + Args: + apparatus_kind (`str`): The ChemKED ``apparatus.kind`` + datapoints (`list`): The ChemKED datapoints + + Returns: + `str`: The ReSpecTh ``experimentType`` + + Raises: + `NotImplementedError`: If the apparatus has no ReSpecTh speciation type, or the datapoints + would need more than one + """ + if apparatus_kind == "jet stirred reactor": + return "jet stirred reactor measurement" + if apparatus_kind == "burner stabilized flame": + return "burner stabilized flame speciation measurement" + if apparatus_kind not in ["shock tube", "flow reactor"]: + raise NotImplementedError( + f"ReSpecTh has no speciation measurement type for a {apparatus_kind}." + ) + + against_time = {dp["independent-variables"][0]["name"] == "time" for dp in datapoints} + if len(against_time) > 1: + raise NotImplementedError( + "ReSpecTh gives one experiment type per file, but some datapoints are profiles " + "against time and others are outlet concentrations." + ) + if against_time.pop(): + return "concentration time profile measurement" + return "outlet concentration measurement" + + +def _respecth_bibliography(reference): + """Write a ChemKED reference as a ReSpecTh 2 ``bibliographyLink``. + + The reference is stated in full in ``details``, which `~pyked.converters.get_reference_details` + reads back without a DOI look-up. Author names are written as ChemKED has them, given name + first, which BibTeX accepts as well as the family-name-first form. + + Args: + reference (`Reference`): The ChemKED reference + + Returns: + `~xml.etree.ElementTree.Element`: The ``bibliographyLink`` element + """ + names = [author["name"] for author in reference.authors] + citation = ", ".join(names) + for part in [reference.journal, reference.volume, reference.pages, reference.year]: + if part is not None: + citation += f", {part}" + citation += "." + if reference.detail: + citation += f" {reference.detail}" + + link = etree.Element("bibliographyLink") + etree.SubElement(link, "description").text = citation + if reference.doi is not None: + etree.SubElement(link, "referenceDOI").text = reference.doi + + details = etree.SubElement(link, "details") + etree.SubElement(details, "author").text = " and ".join(names) + for field in ["journal", "pages", "volume", "year"]: + value = getattr(reference, field) + if value is not None: + etree.SubElement(details, field).text = str(value) + + return link + + +def _respecth_property_name(field): + """The ReSpecTh property name of a ChemKED condition. + + Raises: + `NotImplementedError`: If ReSpecTh has no property for the condition + """ + if field not in respecth_property_names: + raise NotImplementedError(f"ReSpecTh has no property for {field}.") + return respecth_property_names[field] + + +def _speciation_common_properties(properties): + """The conditions of a speciation measurement that ReSpecTh can state once for the file. + + ReSpecTh applies a common property to every dataGroup, so only a condition every datapoint + states with the same value can be common. The candidates are the file's own + common-properties, so that the file reads back the same, or what the first datapoint states + when the file has none. + + Args: + properties (`dict`): The ChemKED file + + Returns: + `dict`: ChemKED field mapped to the value every datapoint shares + + Raises: + `NotImplementedError`: If the datapoints have different initial compositions + """ + datapoints = properties["datapoints"] + candidates = properties.get("common-properties") + if candidates is None: + candidates = { + field: value + for field, value in datapoints[0].items() + if field not in speciation_profile_keys + } + + common = { + field: value + for field, value in candidates.items() + if all(field in dp and dp[field] == value for dp in datapoints) + } + if "composition" not in common: + raise NotImplementedError( + "ReSpecTh states one initial composition for the whole file, but the datapoints " + "have different compositions." + ) + return common + + +def _datapoint_conditions(datapoint, common): + """The conditions a datapoint states with a value of its own rather than a common one.""" + return [ + field for field in datapoint if field not in common and field not in speciation_profile_keys + ] + + +def _shared_uncertainties(datapoints, common): + """Find the uncertainties that ReSpecTh can state as common properties. + + The converter attaches a common uncertainty about a species to every profile of that species, + and one about a condition to every datapoint that states the condition. Such an uncertainty + can therefore be common when every profile of the species, or every datapoint stating the + condition, carries the same one. + + Args: + datapoints (`list`): The ChemKED datapoints + common (`dict`): The common conditions, from `_speciation_common_properties` + + Returns: + `tuple`: Species name mapped to a profile of it and the uncertainty mapping they share, + and ChemKED field mapped to the uncertainty mapping the datapoints share + """ + profiles: dict[str, list] = {} + conditions: dict[str, list] = {} + for dp in datapoints: + for profile in dp["concentration-profiles"]: + profiles.setdefault(profile["species-name"], []).append(profile) + for field in _datapoint_conditions(dp, common): + conditions.setdefault(field, []).append(dp[field][1] if len(dp[field]) > 1 else None) + + shared_profiles = {} + for species, found in profiles.items(): + # The units are shared too, as an absolute uncertainty is stated in them + shared = _shared_value([(p["quantity"]["units"], p.get("uncertainty")) for p in found]) + if shared is not None and shared[1] is not None: + shared_profiles[species] = (found[0], shared[1][0]) + + shared_conditions = {} + for field, found in conditions.items(): + shared = _shared_value(found) + if shared is not None: + shared_conditions[field] = shared + + return shared_profiles, shared_conditions + + +def _add_speciation_common_properties(root, datapoints, common, shared_profiles, shared_conditions): + """Write the common properties of a speciation measurement. + + The uncertainties follow the values they describe, as in ReSpecTh files, and each names the + quantity it is about: an amount in the inlet mixture is referred to as the ``initial + composition`` and a measured profile as the ``composition``, with the species linked. + + Args: + root (`~xml.etree.ElementTree.Element`): The ReSpecTh ``experiment`` element + datapoints (`list`): The ChemKED datapoints + common (`dict`): The common conditions, from `_speciation_common_properties` + shared_profiles (`dict`): Profile uncertainties to state once, from `_shared_uncertainties` + shared_conditions (`dict`): Condition uncertainties to state once, likewise + """ + common_properties = etree.SubElement(root, "commonProperties") + + # (reference, units of the quantity, species, descriptor) of each uncertainty + metadata = [] + for field, value in common.items(): + prop = etree.SubElement(common_properties, "property") + if field == "composition": + prop.set("name", "initial composition") + for species in value["species"]: + component = etree.SubElement(prop, "component") + _add_species_link(component, species) + amount = etree.SubElement(component, "amount") + amount.set("units", value["kind"]) + amount.text = str(species["amount"][0]) + if len(species["amount"]) > 1: + metadata.extend( + ("initial composition", value["kind"], species, item) + for item in _metadata_items(species["amount"][1]) + ) + continue + + name = _respecth_property_name(field) + number, units = _split_value(value[0]) + prop.set("name", name) + if name in respecth_labels: + prop.set("label", respecth_labels[name]) + prop.set("units", units) + etree.SubElement(prop, "value").text = number + if len(value) > 1: + metadata.extend((name, units, None, item) for item in _metadata_items(value[1])) + + for profile, uncertainty in shared_profiles.values(): + metadata.extend( + ("composition", profile["quantity"]["units"], profile, item) + for item in _metadata_items(uncertainty) + ) + + for field, uncertainty in shared_conditions.items(): + value = next(dp[field] for dp in datapoints if field in dp) + metadata.extend( + (_respecth_property_name(field), _split_value(value[0])[1], None, item) + for item in _metadata_items(uncertainty) + ) + + for reference, units, species, item in metadata: + _add_metadata_property(common_properties, item, reference, units, species) + + +def _add_speciation_datagroup( + root, datapoint, datagroup_id, column_ids, common, shared_profiles, shared_conditions +): + """Write a speciation datapoint as a ReSpecTh dataGroup. + + The columns are, in order, the independent variables with the swept axis first, one column + per concentration profile, any condition the datapoint states with a value of its own, the + auxiliary profiles, and then the uncertainties. That is the order in which + `~pyked.converters.get_speciation_datapoints` tells the columns apart. An uncertainty that + could not be common is written as a column with one repeated value, which describes the whole + profile. + + Args: + root (`~xml.etree.ElementTree.Element`): The ReSpecTh ``experiment`` element + datapoint (`dict`): The ChemKED datapoint + datagroup_id (`str`): The id of the dataGroup + column_ids (`~collections.abc.Iterator`): Column numbers, which ReSpecTh counts across the + whole file + common (`dict`): The common conditions, from `_speciation_common_properties` + shared_profiles (`dict`): Profile uncertainties stated once, from `_shared_uncertainties` + shared_conditions (`dict`): Condition uncertainties stated once, likewise + + Raises: + `NotImplementedError`: If the concentration and auxiliary profiles are not all sampled at + the same points + """ + axes = datapoint["independent-variables"] + n_axes = len(axes) + profiles = datapoint["concentration-profiles"] + auxiliary = datapoint.get("auxiliary-profiles", []) + + grid = [row[:n_axes] for row in profiles[0]["values"]] + for profile in profiles[1:]: + if [row[:n_axes] for row in profile["values"]] != grid: + raise NotImplementedError( + f"The profile of {profile['species-name']} is sampled at other points than that " + f"of {profiles[0]['species-name']}, but a ReSpecTh dataGroup holds every profile " + "on one set of rows." + ) + for aux in auxiliary: + if ( + aux["independent"]["name"] != auxiliary_axes.get(axes[0]["name"]) + or aux["independent"]["units"] != axes[0]["units"] + or [row[0] for row in aux["values"]] != [point[0] for point in grid] + ): + raise NotImplementedError( + f"The auxiliary {aux['type']} profile is not sampled at the points of the " + "concentration profiles, but a ReSpecTh dataGroup holds both on one set of rows." + ) + + datagroup = etree.SubElement(root, "dataGroup") + datagroup.set("id", datagroup_id) + columns = [] + + def add_column(values, name, units, species=None, metadata=None): + """Declare a column whose text in each row is in ``values``, `None` where it is blank. + + An uncertainty column is described by ``metadata``, its descriptor and the name of the + quantity it is about, instead of by ``name``. + """ + prop = etree.SubElement(datagroup, "property") + column_id = f"x{next(column_ids)}" + if metadata is not None: + item, reference = metadata + _set_metadata_attributes(prop, item, reference, units, column_id) + else: + prop.set("name", name) + prop.set("id", column_id) + if species is not None: + prop.set("label", f"[{species['species-name']}]") + elif name in respecth_labels: + prop.set("label", respecth_labels[name]) + prop.set("units", _respecth_units(units)) + if species is not None: + _add_species_link(prop, species) + columns.append((column_id, values)) + + for idx, axis in enumerate(axes): + add_column( + [str(point[idx]) for point in grid], + respecth_axis_names[axis["name"]], + axis["units"], + species=axis if "species-name" in axis else None, + ) + + for profile in profiles: + units = profile["quantity"]["units"] + add_column( + [str(row[n_axes]) for row in profile["values"]], + "concentration" if units in concentration_kinds else "composition", + units, + species=profile, + ) + + conditions = _datapoint_conditions(datapoint, common) + for field in conditions: + number, units = _split_value(datapoint[field][0]) + add_column([number] * len(grid), _respecth_property_name(field), units) + + for aux in auxiliary: + add_column([str(row[1]) for row in aux["values"]], aux["type"], aux["quantity"]["units"]) + + # A row may end with the uncertainty of its value + for profile in profiles: + if any(len(row) > n_axes + 1 for row in profile["values"]): + add_column( + [ + str(row[n_axes + 1]) if len(row) > n_axes + 1 else None + for row in profile["values"] + ], + None, + profile["quantity"]["units"], + species=profile, + metadata=(row_uncertainty, "composition"), + ) + for aux in auxiliary: + if any(len(row) > 2 for row in aux["values"]): + add_column( + [str(row[2]) if len(row) > 2 else None for row in aux["values"]], + None, + aux["quantity"]["units"], + metadata=(row_uncertainty, aux["type"]), + ) + + for profile in profiles: + if profile["species-name"] in shared_profiles or "uncertainty" not in profile: + continue + units = profile["quantity"]["units"] + for item in _metadata_items(profile["uncertainty"][0]): + add_column( + [_metadata_value(item, units)[0]] * len(grid), + None, + units, + species=profile, + metadata=(item, "composition"), + ) + for field in conditions: + if field in shared_conditions or len(datapoint[field]) < 2: + continue + units = _split_value(datapoint[field][0])[1] + for item in _metadata_items(datapoint[field][1]): + add_column( + [_metadata_value(item, units)[0]] * len(grid), + None, + units, + metadata=(item, _respecth_property_name(field)), + ) + + for row in range(len(grid)): + point = etree.SubElement(datagroup, "dataPoint") + for column_id, values in columns: + if values[row] is not None: + etree.SubElement(point, column_id).text = values[row] + class VolumeHistory(NamedTuple): """Time history of the volume in an RCM experiment. Deprecated, to be removed after PyKED 0.4""" @@ -422,6 +999,10 @@ def convert_to_ReSpecTh(self, filename): ReSpecTh XML file. Note that some information may be lost, as ChemKED stores some additional attributes. + Ignition delay and speciation measurement files can be converted. A speciation + measurement is written as whichever of the four ReSpecTh speciation types fits its + apparatus and swept axis; see `_speciation_to_ReSpecTh`. + Arguments: filename (`str`): Filename for output ReSpecTh XML file. @@ -429,6 +1010,19 @@ def convert_to_ReSpecTh(self, filename): >>> dataset = ChemKED(yaml_file) >>> dataset.convert_to_ReSpecTh(xml_file) """ + if self.experiment_type == "speciation measurement": + root = self._speciation_to_ReSpecTh() + # Indent for reading, but keep each dataPoint on one line as ReSpecTh files do, since + # a profile can run to hundreds of rows + etree.indent(root, space=" ") + for point in root.iter("dataPoint"): + point.text = None + for value in point: + value.tail = None + etree.ElementTree(root).write(filename, encoding="utf-8", xml_declaration=True) + print("Converted to " + str(filename)) + return + root = etree.Element("experiment") file_author = etree.SubElement(root, "fileAuthor") @@ -447,12 +1041,14 @@ def convert_to_ReSpecTh(self, filename): minor_version = etree.SubElement(respecth_version, "minor") minor_version.text = "0" - # Only ignition delay currently supported + # Speciation measurements were handled above exp = etree.SubElement(root, "experimentType") if self.experiment_type == "ignition delay": exp.text = "Ignition delay measurement" else: - raise NotImplementedError("Only ignition delay type supported for conversion.") + raise NotImplementedError( + "Only ignition delay and speciation measurement types supported for conversion." + ) reference = etree.SubElement(root, "bibliographyLink") citation = ( @@ -680,6 +1276,92 @@ def convert_to_ReSpecTh(self, filename): print("Converted to " + str(filename)) + def _speciation_to_ReSpecTh(self): + """Build the ReSpecTh experiment for a speciation measurement. + + The inverse of `~pyked.converters.get_speciation_datapoints`: each datapoint becomes a + dataGroup, with the independent variables, the concentration and auxiliary profiles, and + the per-row uncertainties as its columns. A per-row uncertainty is written as an absolute + uncertainty in the units of its profile, which is how a ChemKED row states it. Conditions + every datapoint shares, the initial composition, and the uncertainties that describe a + whole profile or quantity become common properties. + + `DataPoint` does not model profiles, so they are read from the mapping the instance was + built from. + + Note: + ReSpecTh has no place for the ORCID of an author, for more than one file author + (their names are joined into one), for the apparatus institution and facility, or for + the atomic composition and thermo of a species. + + Returns: + `~xml.etree.ElementTree.Element`: The ReSpecTh ``experiment`` element + + Raises: + `NotImplementedError`: If the measurement cannot be stated in one ReSpecTh file, as + for datapoints with different initial compositions or time shifts, or profiles + of one datapoint that are sampled at different points + """ + datapoints = self._properties["datapoints"] + experiment_type = _speciation_experiment_type(self.apparatus.kind, datapoints) + common = _speciation_common_properties(self._properties) + shared_profiles, shared_conditions = _shared_uncertainties(datapoints, common) + + root = etree.Element("experiment") + etree.SubElement(root, "fileAuthor").text = "; ".join( + author["name"] for author in self.file_authors + ) + + # right now ChemKED just uses an integer file version + file_version = etree.SubElement(root, "fileVersion") + etree.SubElement(file_version, "major").text = str(self.file_version) + etree.SubElement(file_version, "minor").text = "0" + + # The speciation types and the bibliographic details are ReSpecTh 2 elements + respecth_version = etree.SubElement(root, "ReSpecThVersion") + etree.SubElement(respecth_version, "major").text = "2" + etree.SubElement(respecth_version, "minor").text = "3" + + root.append(_respecth_bibliography(self.reference)) + etree.SubElement(root, "experimentType").text = experiment_type + + apparatus = etree.SubElement(root, "apparatus") + kind, modes = respecth_speciation_apparatus[self.apparatus.kind] + etree.SubElement(apparatus, "kind").text = kind + for mode in modes: + etree.SubElement(apparatus, "mode").text = mode + + _add_speciation_common_properties( + root, datapoints, common, shared_profiles, shared_conditions + ) + + # ReSpecTh numbers columns across the whole file + column_ids = count(1) + for index, dp in enumerate(datapoints): + _add_speciation_datagroup( + root, dp, f"dg{index + 1}", column_ids, common, shared_profiles, shared_conditions + ) + + # ReSpecTh states the zero of a time axis once for the whole file + shifts = [dp.get("time-shift") for dp in datapoints] + if any(shift is not None for shift in shifts): + shift = _shared_value(shifts) + if shift is None: + raise NotImplementedError( + "ReSpecTh states one time shift for the whole file, but the datapoints " + "have different ones." + ) + timeshift = etree.SubElement(root, "timeshift") + timeshift.set("target", shift["target"]) + timeshift.set("type", shift["type"]) + if shift.get("amount"): + timeshift.set("amount", _split_value(shift["amount"][0])[0]) + + for comment in self._properties.get("comments", []): + etree.SubElement(root, "comment").text = comment + + return root + class DataPoint: """Class for a single datapoint. diff --git a/src/pyked/converters.py b/src/pyked/converters.py index 786d66d..2da2dcf 100644 --- a/src/pyked/converters.py +++ b/src/pyked/converters.py @@ -806,6 +806,7 @@ def get_value_metadata(root): "reference": reference, "kind": elem.attrib["kind"], "units": elem.attrib.get("units"), + "bound": elem.attrib.get("bound"), "sourcetype": elem.attrib.get("sourcetype"), "method": elem.attrib.get("method"), "value": elem.find("value").text, diff --git a/tests/test_chemked.py b/tests/test_chemked.py index 40321b5..8051c29 100644 --- a/tests/test_chemked.py +++ b/tests/test_chemked.py @@ -13,7 +13,7 @@ import pytest from pyked.chemked import ChemKED, Composition, DataPoint -from pyked.converters import get_common_properties, get_datapoints +from pyked.converters import ReSpecTh_to_ChemKED, get_common_properties, get_datapoints # Local imports from pyked.validation import Q_, OurValidator, schema, yaml @@ -346,23 +346,19 @@ def test_time_history_conversion_to_respecth_unsupported(self, history_type, uni assert len(c.datapoints) == len(c_true.datapoints) assert getattr(c.datapoints[0], "{}_history".format(history_type.replace(" ", "_"))) is None - @pytest.mark.parametrize( - "experiment_type", - [ - "laminar burning velocity measurement", - "speciation measurement", - ], - ) - def test_conversion_to_respecth_error(self, experiment_type): - """Only ignition delay can be written back out to ReSpecTh.""" + def test_conversion_to_respecth_error(self): + """Laminar burning velocity cannot be written back out to ReSpecTh yet.""" filename = Path("tests") / "testfile_st.yaml" c = ChemKED(filename) - c.experiment_type = experiment_type + c.experiment_type = "laminar burning velocity measurement" with pytest.raises(NotImplementedError) as excinfo: c.convert_to_ReSpecTh("test.xml") - assert "Only ignition delay type supported for conversion." in str(excinfo.value) + assert ( + "Only ignition delay and speciation measurement types supported for conversion." + in str(excinfo.value) + ) def test_conversion_datapoints_composition_missing_inchi(self): """Test for appropriate handling of composition with missing InChI.""" @@ -570,6 +566,483 @@ def test_conversion_multiple_ignition_targets(self): ) +def speciation_document( + apparatus="jet stirred reactor", axis=("temperature", "K"), points=(800.0, 900.0) +): + """A small speciation measurement whose datapoint shares its common values, as in a file.""" + pressure = ["1.0 atm"] + volume = ["39 cm3"] + composition = { + "kind": "mole fraction", + "species": [ + {"species-name": "H2", "InChI": "1S/H2/h1H", "amount": [0.01]}, + {"species-name": "O2", "InChI": "1S/O2/c1-2", "amount": [0.01]}, + {"species-name": "N2", "InChI": "1S/N2/c1-2", "amount": [0.98]}, + ], + } + common = {"pressure": pressure, "reactor-volume": volume, "composition": composition} + datapoint = { + "independent-variables": [{"name": axis[0], "units": axis[1], "primary": True}], + "concentration-profiles": [ + { + "species-name": "H2", + "InChI": "1S/H2/h1H", + "quantity": {"units": "mole fraction"}, + "values": [[points[0], 0.0095], [points[1], 0.0071]], + "uncertainty": [ + { + "evaluated-standard-deviation-type": "relative", + "evaluated-standard-deviation": 0.05, + "evaluated-standard-deviation-sourcetype": "estimated", + "evaluated-standard-deviation-method": "generic uncertainty", + } + ], + }, + { + "species-name": "H2O", + "InChI": "1S/H2O/h1H2", + "quantity": {"units": "mole fraction"}, + "values": [[points[0], 0.0005, 0.0001], [points[1], 0.0029, 0.0002]], + }, + ], + **common, + } + return { + "file-authors": [{"name": "Kyle Niemeyer"}], + "file-version": 0, + "chemked-version": "0.5.0", + "reference": { + "authors": [{"name": "Ann Author"}, {"name": "Ben Author"}], + "journal": "Combustion and Flame", + "year": 2001, + "volume": 125, + "pages": "1-10", + # What the converter writes, so the file reads back the same + "detail": "Converted from ReSpecTh XML file x1.xml", + }, + "experiment-type": "speciation measurement", + "apparatus": {"kind": apparatus, "institution": "", "facility": ""}, + "common-properties": common, + "datapoints": [datapoint], + "comments": ["Measured by gas chromatography."], + } + + +@pytest.mark.usefixtures("mock_all_apis") +class TestSpeciationToReSpecTh: + """Speciation measurements are written as one of the four ReSpecTh speciation types.""" + + def convert(self, document, tmp_path, *, skip_validation=False): + """Write ``document`` as ReSpecTh, and return the XML root and the file.""" + filename = tmp_path / "x1.xml" + c = ChemKED(dict_input=deepcopy(document), skip_validation=skip_validation) + c.convert_to_ReSpecTh(filename) + return etree.parse(filename).getroot(), filename + + def round_trip(self, document, tmp_path): + """Write ``document`` as ReSpecTh and convert it back to ChemKED.""" + root, filename = self.convert(document, tmp_path) + return root, ReSpecTh_to_ChemKED(filename) + + def test_round_trip(self, tmp_path): + """Converting the ReSpecTh file back gives the same ChemKED file.""" + document = speciation_document() + + _, converted = self.round_trip(document, tmp_path) + + assert converted == document + ChemKED(dict_input=converted) + + def test_layout(self, tmp_path): + """The file is laid out as ReSpecTh writes a speciation measurement.""" + root, _ = self.round_trip(speciation_document(), tmp_path) + + assert root.findtext("ReSpecThVersion/major") == "2" + assert root.findtext("bibliographyLink/details/author") == "Ann Author and Ben Author" + assert root.findtext("bibliographyLink/details/year") == "2001" + assert root.find("bibliographyLink/referenceDOI") is None + + common = root.find("commonProperties") + assert [prop.get("name") for prop in common] == [ + "pressure", + "volume", + "initial composition", + "evaluated standard deviation", + ] + assert common[1].get("units") == "cm3" + assert common[1].findtext("value") == "39" + assert [ + component.find("speciesLink").get("preferredKey") + for component in common[2].iter("component") + ] == ["H2", "O2", "N2"] + + # An uncertainty about a whole profile is a common property linked to its species + esd = common[3] + assert esd.attrib == { + "name": "evaluated standard deviation", + "units": "unitless", + "reference": "composition", + "kind": "relative", + "sourcetype": "estimated", + "method": "generic uncertainty", + } + assert esd.find("speciesLink").attrib == {"preferredKey": "H2", "InChI": "1S/H2/h1H"} + assert esd.findtext("value") == "0.05" + + datagroup = root.find("dataGroup") + columns = [ + (prop.get("id"), prop.get("name"), prop.get("units"), prop.find("speciesLink")) + for prop in datagroup.findall("property") + ] + assert [column[:3] for column in columns] == [ + ("x1", "temperature", "K"), + ("x2", "composition", "mole fraction"), + ("x3", "composition", "mole fraction"), + ("x4", "uncertainty", "mole fraction"), + ] + assert [getattr(column[3], "attrib", {}).get("preferredKey") for column in columns] == [ + None, + "H2", + "H2O", + "H2O", + ] + + # The last value of a profile row is an absolute uncertainty in the units of the profile + uncertainty = datagroup.find("property[@id='x4']") + assert uncertainty.get("reference") == "composition" + assert uncertainty.get("kind") == "absolute" + assert uncertainty.get("bound") == "plusminus" + + rows = [{value.tag: value.text for value in point} for point in datagroup.iter("dataPoint")] + assert rows == [ + {"x1": "800.0", "x2": "0.0095", "x3": "0.0005", "x4": "0.0001"}, + {"x1": "900.0", "x2": "0.0071", "x3": "0.0029", "x4": "0.0002"}, + ] + assert root.findtext("comment") == "Measured by gas chromatography." + + @pytest.mark.parametrize( + ("apparatus", "axis", "experiment_type", "kind", "modes"), + [ + ( + "jet stirred reactor", + ("temperature", "K"), + "jet stirred reactor measurement", + "jet stirred reactor", + [], + ), + ( + "flow reactor", + ("time", "ms"), + "concentration time profile measurement", + "flow reactor", + [], + ), + ( + "flow reactor", + ("temperature", "K"), + "outlet concentration measurement", + "flow reactor", + [], + ), + ( + "flow reactor", + ("residence-time", "s"), + "outlet concentration measurement", + "flow reactor", + [], + ), + ( + "shock tube", + ("time", "us"), + "concentration time profile measurement", + "shock tube", + [], + ), + ( + "shock tube", + ("temperature", "K"), + "outlet concentration measurement", + "shock tube", + [], + ), + ( + "burner stabilized flame", + ("distance", "mm"), + "burner stabilized flame speciation measurement", + "flame", + ["burner-stabilized"], + ), + ], + ) + def test_experiment_type(self, tmp_path, apparatus, axis, experiment_type, kind, modes): + """The apparatus, and for a reactor the swept axis, picks the ReSpecTh type.""" + document = speciation_document(apparatus, axis) + + root, converted = self.round_trip(document, tmp_path) + + assert root.findtext("experimentType") == experiment_type + assert root.findtext("apparatus/kind") == kind + assert [mode.text for mode in root.iterfind("apparatus/mode")] == modes + assert converted == document + + def test_reference_doi_and_concentration(self, tmp_path): + """A DOI is written with the details, and a concentration profile is a concentration.""" + document = speciation_document("shock tube", ("time", "us")) + document["reference"]["doi"] = "10.1016/S0010-2180(00)00200-7" + profile = document["datapoints"][0]["concentration-profiles"][1] + profile["quantity"]["units"] = "mol/cm3" + + root, _ = self.convert(document, tmp_path, skip_validation=True) + + assert root.findtext("bibliographyLink/referenceDOI") == "10.1016/S0010-2180(00)00200-7" + column = root.find("dataGroup/property[@id='x3']") + assert column.get("name") == "concentration" + assert column.get("units") == "mol/cm3" + + def test_uncertainty_that_differs_between_datapoints(self, tmp_path): + """An uncertainty only some profiles of a species share is a column of each dataGroup.""" + document = speciation_document() + second = deepcopy(document["datapoints"][0]) + second["concentration-profiles"][0]["uncertainty"][0]["evaluated-standard-deviation"] = 0.1 + document["datapoints"].append(second) + + root, converted = self.round_trip(document, tmp_path) + + assert converted == document + assert root.find("commonProperties/property[@reference='composition']") is None + for datagroup, expected in zip(root.iterfind("dataGroup"), ["0.05", "0.1"]): + column = datagroup.find("property[@name='evaluated standard deviation']") + assert column.find("speciesLink").get("preferredKey") == "H2" + assert {point.findtext(column.get("id")) for point in datagroup.iter("dataPoint")} == { + expected + } + + # ReSpecTh numbers the columns across the whole file + ids = [prop.get("id") for prop in root.iterfind("dataGroup/property")] + assert len(ids) == len(set(ids)) + + def test_condition_of_one_datapoint(self, tmp_path): + """A condition that datapoints state differently is a column with one value.""" + document = speciation_document("flow reactor", ("time", "ms")) + document["datapoints"].append(deepcopy(document["datapoints"][0])) + for datapoint, temperature in zip(document["datapoints"], ["1000 K", "1100 K"]): + datapoint["temperature"] = [ + temperature, + {"uncertainty-type": "absolute", "uncertainty": "10 K"}, + ] + + root, converted = self.round_trip(document, tmp_path) + + assert converted == document + assert "temperature" not in converted["common-properties"] + for datagroup, expected in zip(root.iterfind("dataGroup"), ["1000", "1100"]): + column = datagroup.find("property[@name='temperature']") + assert column.get("units") == "K" + assert {point.findtext(column.get("id")) for point in datagroup.iter("dataPoint")} == { + expected + } + + # Every datapoint states the same uncertainty, so it is stated once + uncertainty = root.find("commonProperties/property[@reference='temperature']") + assert uncertainty.get("units") == "K" + assert uncertainty.findtext("value") == "10" + + def test_condition_uncertainty_of_one_datapoint(self, tmp_path): + """The uncertainty of a condition of one datapoint alone is a column too.""" + document = speciation_document("flow reactor", ("time", "ms")) + document["datapoints"].append(deepcopy(document["datapoints"][0])) + for datapoint, uncertainty in zip(document["datapoints"], ["10 K", "20 K"]): + datapoint["temperature"] = [ + "1000 K", + {"uncertainty-type": "absolute", "uncertainty": uncertainty}, + ] + + root, _ = self.convert(document, tmp_path) + + assert root.find("commonProperties/property[@reference='temperature']") is None + for datagroup, expected in zip(root.iterfind("dataGroup"), ["10", "20"]): + column = datagroup.find("property[@reference='temperature']") + assert column.get("name") == "uncertainty" + assert column.get("units") == "K" + assert {point.findtext(column.get("id")) for point in datagroup.iter("dataPoint")} == { + expected + } + + def test_auxiliary_profile(self, tmp_path): + """An auxiliary profile and its per-row uncertainty are columns on the same rows.""" + document = speciation_document("burner stabilized flame", ("distance", "mm"), (0.5, 1.5)) + document["datapoints"][0]["auxiliary-profiles"] = [ + { + "type": "temperature", + "independent": {"name": "distance", "units": "mm"}, + "quantity": {"units": "K"}, + "values": [[0.5, 1500.0, 50.0], [1.5, 1600.0, 60.0]], + } + ] + + root, converted = self.round_trip(document, tmp_path) + + assert converted == document + datagroup = root.find("dataGroup") + assert datagroup.find("property[@id='x4']").attrib == { + "name": "temperature", + "id": "x4", + "label": "T", + "units": "K", + } + uncertainty = datagroup.find("property[@reference='temperature']") + assert uncertainty.get("units") == "K" + assert [point.findtext(uncertainty.get("id")) for point in datagroup.iter("dataPoint")] == [ + "50.0", + "60.0", + ] + + def test_swept_inlet_species(self, tmp_path): + """The species of an inlet composition sweep is linked to its column.""" + document = speciation_document(points=(0.01, 0.02)) + document["datapoints"][0]["independent-variables"] = [ + { + "name": "initial-composition", + "units": "dimensionless", + "primary": True, + "species-name": "H2", + "InChI": "1S/H2/h1H", + } + ] + + root, converted = self.round_trip(document, tmp_path) + + assert converted == document + column = root.find("dataGroup/property[@id='x1']") + assert column.get("name") == "initial composition" + assert column.get("units") == "unitless" + assert column.find("speciesLink").get("preferredKey") == "H2" + + def test_bounds_and_inlet_amount_uncertainty(self, tmp_path): + """Asymmetric bounds and the uncertainty of an inlet amount are common properties.""" + document = speciation_document() + document["common-properties"]["pressure"].append( + { + "uncertainty-type": "relative", + "upper-uncertainty": "0.1", + "lower-uncertainty": "0.05", + "uncertainty-sourcetype": "reported", + } + ) + document["common-properties"]["composition"]["species"][0]["amount"].append( + {"uncertainty-type": "absolute", "uncertainty": 0.0005} + ) + + with pytest.warns(UserWarning, match="Asymmetric uncertainties"): + root, converted = self.round_trip(document, tmp_path) + + assert converted == document + bounds = root.findall("commonProperties/property[@reference='pressure']") + assert [(prop.get("bound"), prop.findtext("value")) for prop in bounds] == [ + ("upper", "0.1"), + ("lower", "0.05"), + ] + inlet = root.find("commonProperties/property[@reference='initial composition']") + assert inlet.get("units") == "mole fraction" + assert inlet.find("speciesLink").get("preferredKey") == "H2" + assert inlet.findtext("value") == "0.0005" + + def test_time_shift(self, tmp_path): + """A time shift is a ReSpecTh timeshift element.""" + document = speciation_document("shock tube", ("time", "us")) + document["datapoints"][0]["time-shift"] = { + "target": "H2", + "type": "relative decrease", + "amount": ["0.21"], + } + + root, _ = self.convert(document, tmp_path) + + assert root.find("timeshift").attrib == { + "target": "H2", + "type": "relative decrease", + "amount": "0.21", + } + + def test_without_common_properties(self, tmp_path): + """Without common-properties, what every datapoint shares is stated once.""" + document = speciation_document() + del document["common-properties"] + + root, converted = self.round_trip(document, tmp_path) + + assert [prop.get("name") for prop in root.iterfind("commonProperties/property")] == [ + "pressure", + "volume", + "initial composition", + "evaluated standard deviation", + ] + assert converted["datapoints"] == document["datapoints"] + assert set(converted["common-properties"]) == {"pressure", "reactor-volume", "composition"} + + def test_different_compositions(self, tmp_path): + """ReSpecTh states one initial composition for a file.""" + document = speciation_document() + second = deepcopy(document["datapoints"][0]) + second["composition"]["species"][0]["amount"] = [0.02] + second["composition"]["species"][2]["amount"] = [0.97] + document["datapoints"].append(second) + + with pytest.raises(NotImplementedError, match="one initial composition"): + self.convert(document, tmp_path) + + def test_profiles_on_different_points(self, tmp_path): + """The profiles of a datapoint share the rows of its dataGroup.""" + document = speciation_document() + document["datapoints"][0]["concentration-profiles"][1]["values"][1][0] = 950.0 + + with pytest.raises(NotImplementedError, match="sampled at other points"): + self.convert(document, tmp_path) + + def test_auxiliary_profile_on_other_points(self, tmp_path): + """An auxiliary profile shares the rows of the concentration profiles.""" + document = speciation_document("burner stabilized flame", ("distance", "mm"), (0.5, 1.5)) + document["datapoints"][0]["auxiliary-profiles"] = [ + { + "type": "temperature", + "independent": {"name": "distance", "units": "mm"}, + "quantity": {"units": "K"}, + "values": [[0.5, 1500.0], [2.0, 1600.0]], + } + ] + + with pytest.raises(NotImplementedError, match="not sampled at the points"): + self.convert(document, tmp_path) + + def test_time_profiles_and_outlet_concentrations(self, tmp_path): + """A file holds one ReSpecTh experiment type.""" + document = speciation_document("flow reactor", ("time", "ms")) + second = deepcopy(document["datapoints"][0]) + second["independent-variables"][0].update(name="temperature", units="K") + document["datapoints"].append(second) + + with pytest.raises(NotImplementedError, match="one experiment type per file"): + self.convert(document, tmp_path) + + def test_different_time_shifts(self, tmp_path): + """ReSpecTh states one time shift for a file.""" + document = speciation_document("shock tube", ("time", "us")) + second = deepcopy(document["datapoints"][0]) + document["datapoints"][0]["time-shift"] = {"target": "H2", "type": "half decrease"} + second["time-shift"] = {"target": "O2", "type": "half decrease"} + document["datapoints"].append(second) + + with pytest.raises(NotImplementedError, match="one time shift"): + self.convert(document, tmp_path) + + def test_apparatus_without_speciation_type(self, tmp_path): + """Only the apparatus ReSpecTh has a speciation type for can be converted.""" + document = speciation_document("counterflow twin flame", ("distance", "mm")) + + with pytest.raises(NotImplementedError, match="no speciation measurement type"): + self.convert(document, tmp_path, skip_validation=True) + + @pytest.mark.usefixtures("mock_all_apis") class TestDataPoint: """ """ diff --git a/tests/test_converters.py b/tests/test_converters.py index 523bbfb..82c8666 100644 --- a/tests/test_converters.py +++ b/tests/test_converters.py @@ -1844,6 +1844,27 @@ def test_uncertainty_and_esd_on_one_value(self): assert metadata["evaluated-standard-deviation"] == "2.0 cm/s" assert metadata["evaluated-standard-deviation-method"] == "generic uncertainty" + def test_bounds_of_a_common_uncertainty(self): + """A one-sided uncertainty stated once for the file keeps its bound.""" + root = etree.Element("experiment") + properties_elem = etree.SubElement(root, "commonProperties") + for bound, value in [("upper", "0.1"), ("lower", "0.05")]: + prop = etree.SubElement(properties_elem, "property") + prop.set("name", "uncertainty") + prop.set("reference", "pressure") + prop.set("kind", "relative") + prop.set("bound", bound) + etree.SubElement(prop, "value").text = value + properties = {"common-properties": {"pressure": ["1.0 atm"]}, "datapoints": [{}]} + + attach_value_metadata(properties, get_value_metadata(root)) + + assert properties["common-properties"]["pressure"][1] == { + "uncertainty-type": "relative", + "upper-uncertainty": "0.1", + "lower-uncertainty": "0.05", + } + def test_metadata_attaches_to_common_property(self): """A deviation about a shared value is stored with that shared value.""" root = self.build_metadata("uncertainty", "temperature", "absolute", "5", units="K") diff --git a/tests/test_respecth_fixtures.py b/tests/test_respecth_fixtures.py index 79b5c8c..fca2ff6 100644 --- a/tests/test_respecth_fixtures.py +++ b/tests/test_respecth_fixtures.py @@ -202,3 +202,19 @@ def test_auxiliary_profile_scenario(): auxiliary = flame_profile["datapoints"][0]["auxiliary-profiles"] assert auxiliary[0]["type"] == "temperature" assert auxiliary[0]["independent"]["name"] == "distance" + + +@pytest.mark.parametrize( + ("stem", "source_type"), + [(stem, source_type) for group, stem, source_type, _, _ in CASES if group == "speciation"], +) +def test_speciation_round_trip(stem, source_type, tmp_path): + """Writing a converted speciation file back out as ReSpecTh loses nothing.""" + converted = ReSpecTh_to_ChemKED(str(DATA_DIR / "speciation" / f"{stem}.xml")) + + # Keep the source name, which the converter records in the reference detail + filename = tmp_path / f"{stem}.xml" + ChemKED(dict_input=deepcopy(converted), skip_validation=True).convert_to_ReSpecTh(filename) + + assert etree.parse(filename).getroot().findtext("experimentType") == source_type + assert ReSpecTh_to_ChemKED(str(filename)) == converted From 2ed9b2e0335079f5f8aa98fb7583d10b2ae87dad Mon Sep 17 00:00:00 2001 From: Lekia Prosper Date: Mon, 26 Oct 2026 12:57:54 -0400 Subject: [PATCH 09/13] Read ReSpecTh time shifts and per-row uncertainty meaning for speciation The speciation reader dropped the timeshift element, and of a varying uncertainty column it kept only the values: their name, kind, sourcetype and method were lost, and the values were scaled by the profile's unit factor rather than their own, so an evaluated standard deviation in mole fraction on a ppm profile came out 1e6 too small. - timeshift is read into the time-shift of every speciation datapoint, and "half increase" is an allowed time-shift type, as ReSpecTh uses it. - A profile's uncertainty mapping says what the last value of each row is with the fields of one kind given without a value, such as evaluated-standard-deviation-type, -sourcetype and -method. A plain absolute uncertainty needs none, and stays the default meaning. The validator accepts such fields only when the rows end with a value, and requires the -type. - An absolute uncertainty about a profile is converted from its own units to the profile's kind; a relative one is not rescaled. - convert_to_ReSpecTh writes the row column as the profile describes it, so it stays the inverse of the reader. --- CHANGELOG.md | 3 + docs/schema-docs.rst | 27 ++- src/pyked/chemked.py | 47 +++- src/pyked/converters.py | 175 +++++++++++++- .../speciation_measurement_schema.yaml | 1 + src/pyked/validation.py | 103 ++++++++- tests/test_chemked.py | 98 +++++++- tests/test_converters.py | 215 ++++++++++++++++++ tests/test_validation.py | 97 ++++++++ 9 files changed, 742 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 65cae54..748d6d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - `resolve_reference` maps an uncertainty that points at a column by its `label` or `id`, and one that references `initial composition`, onto the quantity it describes; both were silently dropped before - `0.5.0` added to the allowed `chemked-version` values, and a test asserting the current `__version__` is always among them, since `get_file_metadata` stamps it into every converted file - Physicality checks on speciation profile values: a `concentration-profiles` amount may not be negative, and an `auxiliary-profiles` temperature, pressure or volume must be above zero on its absolute scale. Profile values declare their units once in the `quantity` block rather than per point, so they never reached `isvalid_quantity` and could hold any float, including the -1111 K and -9.9999e+94 missing-data placeholders that ReSpecTh conversions carry through +- A ReSpecTh `timeshift` element is read into the `time-shift` of every speciation datapoint; it was dropped before. `half increase` is added to the allowed `time-shift.type` values, as ReSpecTh uses it +- A concentration profile can say what the uncertainty at the end of each row is: the fields of one kind in its `uncertainty` mapping given without a value, such as `evaluated-standard-deviation-type`, `-sourcetype` and `-method`, describe the row values. `get_speciation_datapoints` records the name, kind, sourcetype and method of a varying uncertainty column this way, and `convert_to_ReSpecTh` writes the column back as described. A plain absolute uncertainty with no sourcetype needs no fields, and remains what a row's last value means by default ### Changed - The `tubular reactor` apparatus kind is renamed `flow reactor`, the name ReSpecTh, the ChemKED database, and the speciation literature all use. `tubular reactor` is still accepted as converter input and maps to `flow reactor` @@ -27,6 +29,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed - An `uncertainty` common property with `bound="upper"` or `bound="lower"` was read as a symmetric uncertainty, so the second bound overwrote the first. The bound is now kept, as it already was for a dataGroup column +- An uncertainty column about a concentration profile was scaled by the unit factor of the profile instead of its own: an evaluated standard deviation in mole fraction on a ppm profile came out 10⁶ too small, and one on a percent profile 100 too small. An absolute uncertainty is now converted from its own units to those of the profile, and a relative one is not rescaled - A composition amount of exactly zero, meaning a species measured as absent, is accepted when it carries uncertainty metadata. It was accepted without metadata and rejected with it, and `isvalid_composition` already allowed it. Only a negative value is an error for a property with no configured units - The unsupported-composition-units error lists the units the converter actually accepts, built from `composition_units` rather than hand-written, so it cannot fall behind the table again - Every text file is now opened with an explicit UTF-8 encoding. Reading or writing a ChemKED or ReSpecTh file whose author names contain non-ASCII characters previously depended on the platform's preferred encoding, and failed on Windows. `convert_to_ReSpecTh` could also rewrite its pretty-printed XML in the platform encoding while declaring UTF-8 in the file. The ruff rule `PLW1514` now enforces this diff --git a/docs/schema-docs.rst b/docs/schema-docs.rst index 52585ab..69bbabe 100644 --- a/docs/schema-docs.rst +++ b/docs/schema-docs.rst @@ -607,7 +607,8 @@ This section details the schema for a speciation measurement datapoint, selected - ``values``: sequence, required A sequence of at least two rows. Each row contains one value for each ``independent-variables`` entry, followed by the measured amount, and optionally an - uncertainty value. + uncertainty value. Unless ``uncertainty`` says otherwise, that last value is an + absolute uncertainty in the units of the profile. - ``uncertainty``: sequence, optional Profile-level uncertainty or evaluated-standard-deviation information. The measured @@ -615,11 +616,32 @@ This section details the schema for a speciation measurement datapoint, selected with the uncertainty and/or evaluated-standard-deviation fields described under :ref:`value-with-uncertainty `. + The fields of one kind given without its value, such as + ``evaluated-standard-deviation-type``, ``-sourcetype`` and ``-method`` without + ``evaluated-standard-deviation``, say what the uncertainty value at the end of each row + is. The ``-type`` field is then required, and the rows must end with an uncertainty. The + other kind may still give a value for the whole profile: + + .. code-block:: yaml + + values: + - [798.0, 9.8e-4, 4.9e-5] + uncertainty: + - uncertainty-type: relative # the whole profile + uncertainty: 0.1 + evaluated-standard-deviation-type: absolute # the last value of each row + evaluated-standard-deviation-sourcetype: estimated + * ``auxiliary-profiles``: sequence, optional A sequence of auxiliary measured profiles, such as temperature, pressure, volume, or velocity. Each profile includes an ``independent`` mapping, a ``quantity`` mapping, and ``values`` rows. +* ``time-shift``: mapping, optional + How the zero of a time axis was placed. ``target`` is the species, and ``type`` is one of + ``half decrease``, ``half increase``, or ``relative decrease``; a relative decrease gives + its ``amount`` as a :ref:`value-unit-optional ` fraction. + .. _schema-only-keys: Schema-Only Keys @@ -657,7 +679,8 @@ should not be used in actual ChemKED files. These keys are documented in this se ``evaluated-standard-deviation-sourcetype``, and ``evaluated-standard-deviation-method`` must be accompanied by an actual ``uncertainty``, ``upper-uncertainty``/``lower-uncertainty``, or - ``evaluated-standard-deviation`` value. + ``evaluated-standard-deviation`` value. Only in a concentration profile may they describe + the uncertainty at the end of each row instead. - Uncertainty fields: diff --git a/src/pyked/chemked.py b/src/pyked/chemked.py index cd0916d..5044309 100644 --- a/src/pyked/chemked.py +++ b/src/pyked/chemked.py @@ -22,7 +22,7 @@ ) # Local imports -from .validation import Q_, OurValidator, _normalize_unit_str, schema, yaml +from .validation import Q_, OurValidator, _normalize_unit_str, row_uncertainty_kinds, schema, yaml respecth_property_names = {field: name for name, field in common_property_fields.items()} """`dict`: ChemKED field name mapped to the ReSpecTh property name, the inverse of @@ -128,9 +128,41 @@ def _metadata_items(metadata): row_uncertainty = {"name": "uncertainty", "kind": "absolute", "bound": "plusminus", "value": ""} -"""`dict`: Descriptor of the uncertainty a ChemKED profile row may end with, which is an -absolute uncertainty in the units of the profile. Its values are in the rows, so it has none of -its own.""" +"""`dict`: Descriptor of the uncertainty a ChemKED profile row ends with when nothing says +otherwise, which is an absolute uncertainty in the units of the profile. Its values are in the +rows, so it has none of its own.""" + + +def _row_uncertainty(metadata): + """Describe the uncertainty at the end of each row of a profile for ReSpecTh. + + The inverse of `~pyked.converters.format_row_uncertainty`: the profile's uncertainty metadata + says what the last value of a row is with the keys of one kind of uncertainty given without + a value (see `~pyked.validation.row_uncertainty_kinds`). Without such keys it is + `row_uncertainty`. + + Args: + metadata (`dict`): The uncertainty metadata mapping of the profile, empty if it has none + + Returns: + `dict`: Descriptor of the ReSpecTh uncertainty or evaluated standard deviation column + """ + kinds = row_uncertainty_kinds(metadata) + if not kinds: + return row_uncertainty + if kinds[0] == "uncertainty": + return dict( + row_uncertainty, + kind=metadata.get("uncertainty-type"), + sourcetype=metadata.get("uncertainty-sourcetype"), + ) + return { + "name": "evaluated standard deviation", + "kind": metadata.get("evaluated-standard-deviation-type"), + "sourcetype": metadata.get("evaluated-standard-deviation-sourcetype"), + "method": metadata.get("evaluated-standard-deviation-method"), + "value": "", + } def _metadata_value(item, units): @@ -553,7 +585,7 @@ def add_column(values, name, units, species=None, metadata=None): None, profile["quantity"]["units"], species=profile, - metadata=(row_uncertainty, "composition"), + metadata=(_row_uncertainty((profile.get("uncertainty") or [{}])[0]), "composition"), ) for aux in auxiliary: if any(len(row) > 2 for row in aux["values"]): @@ -1281,8 +1313,9 @@ def _speciation_to_ReSpecTh(self): The inverse of `~pyked.converters.get_speciation_datapoints`: each datapoint becomes a dataGroup, with the independent variables, the concentration and auxiliary profiles, and - the per-row uncertainties as its columns. A per-row uncertainty is written as an absolute - uncertainty in the units of its profile, which is how a ChemKED row states it. Conditions + the per-row uncertainties as its columns. A per-row uncertainty is written as whatever its + profile's uncertainty metadata describes without a value, and otherwise as an absolute + uncertainty in the units of the profile, which is what a ChemKED row means by it. Conditions every datapoint shares, the initial composition, and the uncertainties that describe a whole profile or quantity become common properties. diff --git a/src/pyked/converters.py b/src/pyked/converters.py index 2da2dcf..0109c3f 100644 --- a/src/pyked/converters.py +++ b/src/pyked/converters.py @@ -18,7 +18,14 @@ from ._version import __version__ # Local imports -from .validation import _normalize_unit_str, crossref_api, property_units, yaml +from .validation import ( + _normalize_unit_str, + crossref_api, + property_units, + row_uncertainty_kinds, + uncertainty_metadata_groups, + yaml, +) from .validation import units as unit_registry # Valid properties for ReSpecTh dataGroup @@ -217,6 +224,10 @@ } """`dict`: ReSpecTh composition units mapped to (ChemKED kind, scale factor, warning)""" +fraction_kinds = {"mole fraction": 1.0, "mole percent": 0.01} +"""`dict`: Composition kinds that state one quantity on different scales, mapped to the mole +fraction that one unit of the kind is""" + composition_unit_typos = ["mole faction"] """`list`: Misspelled composition units in the ReSpecTh corpus, accepted with a warning @@ -907,6 +918,108 @@ def format_value_metadata(item, factor=None, numeric=False): return metadata +def format_row_uncertainty(item): + """Say what the uncertainty at the end of each profile row is, as ChemKED metadata keys. + + These are the keys of `format_value_metadata` without the value, which is in the rows. An + absolute, symmetric uncertainty with nothing else stated is what the last value of a row + means when no key says otherwise, so it needs none. + + Args: + item (`dict`): Descriptor of the uncertainty column, from `get_datagroup_columns` + + Returns: + `dict`: Uncertainty metadata keys without a value, empty for an absolute uncertainty with + no sourcetype + + Raises: + `KeywordError`: If the ``kind`` attribute is neither absolute nor relative + `NotImplementedError`: If the column is one bound of an asymmetric uncertainty + """ + if item["name"] == "uncertainty" and (item.get("bound") or "plusminus") != "plusminus": + raise NotImplementedError( + f"The {item['bound']} bound of the uncertainty of {item['reference']} varies across " + "the dataGroup, but a ChemKED profile row ends with a symmetric uncertainty" + ) + + metadata = format_value_metadata(dict(item, value="0"), numeric=True) + for value_keys, _ in uncertainty_metadata_groups.values(): + for key in value_keys: + metadata.pop(key, None) + + if metadata == {"uncertainty-type": "absolute"}: + return {} + return metadata + + +def uncertainty_factor(item, profile_units): + """Scale factor that states an uncertainty about a profile in the units of the profile. + + ReSpecTh gives an uncertainty units of its own, which need not be those of the composition it + describes: a profile in ppm often has an evaluated standard deviation in mole fraction. The + profile is converted to its ChemKED kind, so an absolute uncertainty is converted to the same + kind. A relative uncertainty is a fraction of the amount, so it is not rescaled. + + Args: + item (`dict`): Descriptor of the uncertainty, with its ``kind`` and ``units`` + profile_units (`str`): ReSpecTh units of the profile + + Returns: + `float`: The factor to multiply the uncertainty by + + Raises: + `KeywordError`: If an absolute uncertainty cannot be stated in the units of the profile + """ + if item["kind"] == "relative": + return 1.0 + + kind, factor, _ = composition_units[profile_units] + units = item.get("units") + if units is None or units.strip().lower() in dimensionless_units: + # Without units of its own, an absolute uncertainty is in those of the profile + return factor + + own_kind, own_factor, _ = composition_units.get(units, (None, None, None)) + if own_kind == kind: + return own_factor + if own_kind in fraction_kinds and kind in fraction_kinds: + return own_factor * fraction_kinds[own_kind] / fraction_kinds[kind] + raise KeywordError( + f"{item['name']} in {units} cannot be stated in the {kind} of the profile it describes" + ) + + +def merge_profile_metadata(profile, metadata): + """Add uncertainty metadata to a concentration profile, in place. + + One mapping holds both the uncertainty of the whole profile and what the last value of each + row is, which is described by keys given without a value (see + `~pyked.validation.row_uncertainty_kinds`). So each kind of uncertainty can describe either + the rows or the whole profile. + + Args: + profile (`dict`): ChemKED concentration profile + metadata (`dict`): Metadata keys from `format_value_metadata` or `format_row_uncertainty` + + Raises: + `NotImplementedError`: If one kind of uncertainty would describe both the rows and the + whole profile + """ + block = profile.setdefault("uncertainty", [{}])[0] + for kind, (value_keys, label_keys) in uncertainty_metadata_groups.items(): + keys = value_keys + label_keys + if not any(key in metadata for key in keys): + continue + if kind in row_uncertainty_kinds(block) or ( + kind in row_uncertainty_kinds(metadata) and any(key in block for key in keys) + ): + raise NotImplementedError( + f"The profile of {profile['species-name']} has a {kind} for each row and one for " + "the whole profile, but ChemKED states both with the same keys" + ) + block.update(metadata) + + def merge_value_metadata(value, metadata): """Add uncertainty metadata to a ChemKED value list, in place. @@ -944,9 +1057,8 @@ def attach_value_metadata(properties, metadata): for datapoint in datapoints: for profile in datapoint.get("concentration-profiles", []): if item["species"] in (None, profile["species-name"]): - profile.setdefault("uncertainty", [{}]) - profile["uncertainty"][0].update( - format_value_metadata(item, factor=factor, numeric=True) + merge_profile_metadata( + profile, format_value_metadata(item, factor=factor, numeric=True) ) attached = True @@ -1153,12 +1265,40 @@ def get_lbv_datapoints(root): return datapoints +def get_time_shift(elem): + """Read a ReSpecTh ``timeshift`` element as a ChemKED time shift. + + ReSpecTh states once for the file how the zero of its time axis was placed: where the amount + of the ``target`` species has fallen to half, for example, or by a relative ``amount``. + + Args: + elem (`~xml.etree.ElementTree.Element`): The ``timeshift`` element + + Returns: + `dict`: ChemKED ``time-shift`` + + Raises: + `MissingAttributeError`: If the element has no ``target`` or ``type`` + """ + shift = {} + for attribute in ["target", "type"]: + if attribute not in elem.attrib: + raise MissingAttributeError(attribute, "timeshift") + shift[attribute] = " ".join(elem.attrib[attribute].split()) + + if "amount" in elem.attrib: + # A relative amount is a fraction, so it carries no units + shift["amount"] = [normalize_value(elem.attrib["amount"])] + + return shift + + def get_speciation_datapoints(root): """Parse speciation datapoints from a ReSpecTh file. Each dataGroup becomes one ChemKED datapoint: the first column that is not a species is the swept axis, the species columns become concentration profiles, and any remaining measured - quantity becomes an auxiliary profile. + quantity becomes an auxiliary profile. The file's time shift is given to every datapoint. Args: root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file @@ -1174,6 +1314,14 @@ def get_speciation_datapoints(root): if not dataGroups: raise MissingElementError("dataGroup") + time_shifts = root.findall("timeshift") + if len(time_shifts) > 1: + raise NotImplementedError( + f"The file has {len(time_shifts)} timeshift elements, but a ChemKED datapoint has " + "one time shift" + ) + time_shift = time_shifts[0] if time_shifts else None + datapoints = [] for dataGroup in dataGroups: columns = get_datagroup_columns(dataGroup, root) @@ -1279,13 +1427,15 @@ def split_metadata(key): uncertainty_column, constant_columns = split_metadata( ("composition", column["species"]) ) + if uncertainty_column is not None: + row_factor = uncertainty_factor(uncertainty_column, column["units"]) values = [] for row in rows: point = [float(row[axis["id"]]) for axis in independent] point.append(float(row[column["id"]]) * factor) if uncertainty_column is not None and uncertainty_column["id"] in row: - point.append(float(row[uncertainty_column["id"]]) * factor) + point.append(float(row[uncertainty_column["id"]]) * row_factor) values.append(point) profile = {"species-name": column["species"]} @@ -1296,10 +1446,16 @@ def split_metadata(key): for constant_column in constant_columns: metadata = format_value_metadata( dict(constant_column, value=rows[0][constant_column["id"]]), - factor=factor, + factor=uncertainty_factor(constant_column, column["units"]), numeric=True, ) - profile.setdefault("uncertainty", [{}])[0].update(metadata) + merge_profile_metadata(profile, metadata) + if uncertainty_column is not None: + # What the last value of each row is, unless it is the plain absolute uncertainty + # a row ends with when nothing says otherwise + row_metadata = format_row_uncertainty(uncertainty_column) + if row_metadata: + merge_profile_metadata(profile, row_metadata) profiles.append(profile) datapoint["concentration-profiles"] = profiles @@ -1340,6 +1496,9 @@ def split_metadata(key): + ", which has no profile in this dataGroup" ) + if time_shift is not None: + datapoint["time-shift"] = get_time_shift(time_shift) + datapoints.append(datapoint) return datapoints diff --git a/src/pyked/schemas/speciation_measurement_schema.yaml b/src/pyked/schemas/speciation_measurement_schema.yaml index bfe9416..8538318 100644 --- a/src/pyked/schemas/speciation_measurement_schema.yaml +++ b/src/pyked/schemas/speciation_measurement_schema.yaml @@ -13,6 +13,7 @@ time-shift: &time-shift type: string allowed: - half decrease + - half increase - relative decrease amount: *value-unit-optional diff --git a/src/pyked/validation.py b/src/pyked/validation.py index d3c84d7..5caf8c8 100644 --- a/src/pyked/validation.py +++ b/src/pyked/validation.py @@ -169,6 +169,47 @@ def _normalize_unit_str(val_str): "temperature-in-reference-state": "kelvin", } +# The uncertainty metadata keys of each kind of uncertainty: those that give a value, and those that +# describe it +uncertainty_metadata_groups = { + "uncertainty": ( + ["uncertainty", "upper-uncertainty", "lower-uncertainty"], + ["uncertainty-type", "uncertainty-sourcetype"], + ), + "evaluated-standard-deviation": ( + ["evaluated-standard-deviation"], + [ + "evaluated-standard-deviation-type", + "evaluated-standard-deviation-sourcetype", + "evaluated-standard-deviation-method", + ], + ), +} + + +def row_uncertainty_kinds(metadata): + """The kinds of uncertainty that a profile's metadata describes without giving a value. + + A concentration profile row may end with an uncertainty of its own. The profile's uncertainty + metadata says what that last value is with the descriptive keys of one kind, such as + ``evaluated-standard-deviation-type``, given without the value of that kind, which is in the + rows instead. Without such keys the last value of a row is an absolute uncertainty in the + units of the profile. + + Args: + metadata (`dict`): The uncertainty metadata mapping of a concentration profile + + Returns: + `list`: ``uncertainty`` and/or ``evaluated-standard-deviation``, each kind whose + descriptive keys are given without a value + """ + return [ + kind + for kind, (value_keys, label_keys) in uncertainty_metadata_groups.items() + if any(key in metadata for key in label_keys) + and not any(metadata.get(key) is not None for key in value_keys) + ] + def compare_name(given_name, family_name, question_name): """Compares a name in question to a specified name separated into given and family. @@ -398,8 +439,10 @@ def _validate_isvalid_speciation(self, isvalid_speciation, field, value): Each concentration profile row must carry one value per declared independent variable, followed by the measured amount, with an - optional trailing uncertainty. Amounts and auxiliary profile values are - also checked for physical possibility. + optional trailing uncertainty. Uncertainty metadata that describes + that trailing value (see `row_uncertainty_kinds`) must describe one + kind, give its type, and belong to rows that have one. Amounts and + auxiliary profile values are also checked for physical possibility. The rule's arguments are validated against this schema: {'type': 'boolean'} @@ -435,8 +478,45 @@ def _validate_isvalid_speciation(self, isvalid_speciation, field, value): f"be negative; got {amount}", ) + self._check_row_uncertainty(field, profile, n_independent) + self._check_auxiliary_profile_values(field, value) + def _check_row_uncertainty(self, field, profile, n_independent): + """Check uncertainty metadata that describes the last value of each profile row. + + Args: + field (`str`): property the profile belongs to, used in the error + profile (`dict`): the concentration profile + n_independent (`int`): number of independent variables of its datapoint + """ + metadata = (profile.get("uncertainty") or [None])[0] + if not isinstance(metadata, dict): + return + + species = profile.get("species-name", "?") + described = row_uncertainty_kinds(metadata) + if len(described) > 1: + self._error( + field, + f"the uncertainty of {species} describes both an uncertainty and an " + "evaluated-standard-deviation without a value, but a row ends with only one", + ) + elif described: + kind = described[0] + if f"{kind}-type" not in metadata: + self._error( + field, + f"the uncertainty of {species} describes the {kind} at the end of each " + f"row, so it must give {kind}-type", + ) + if not any(len(row) == n_independent + 2 for row in profile.get("values", [])): + self._error( + field, + f"the uncertainty of {species} describes the {kind} at the end of each " + "row without a value, but no row ends with one", + ) + def _check_auxiliary_profile_values(self, field, value): """Check that auxiliary profile values are physically possible. @@ -647,9 +727,15 @@ def _check_uncertainty_metadata(self, field, metadata): ) return False - def _check_uncertainty_metadata_values(self, field, uncertainty_dict): - """Validate the values contained in an uncertainty metadata mapping.""" - if not self._check_uncertainty_metadata(field, uncertainty_dict): + def _check_uncertainty_metadata_values(self, field, uncertainty_dict, require_value=True): + """Validate the values contained in an uncertainty metadata mapping. + + Args: + field (`str`): property the uncertainty describes + uncertainty_dict (`dict`): the uncertainty metadata + require_value (`bool`, optional): whether the mapping must give a value at all + """ + if require_value and not self._check_uncertainty_metadata(field, uncertainty_dict): return uncertainty_type = uncertainty_dict.get("uncertainty-type") @@ -672,11 +758,16 @@ def _validate_isvalid_profile_uncertainty( ): """Validate uncertainty metadata associated with a concentration profile. + Metadata that only describes the uncertainty at the end of each row needs no value of its + own; `_check_row_uncertainty` checks that the rows have one. + The rule's arguments are validated against this schema: {'type': 'boolean'} """ if value and isinstance(value[0], dict): - self._check_uncertainty_metadata_values(field, value[0]) + self._check_uncertainty_metadata_values( + field, value[0], require_value=not row_uncertainty_kinds(value[0]) + ) def _validate_isvalid_uncertainty(self, isvalid_uncertainty, field, value): """Checks for valid given value and appropriate units with uncertainty. diff --git a/tests/test_chemked.py b/tests/test_chemked.py index 8051c29..c72a8bc 100644 --- a/tests/test_chemked.py +++ b/tests/test_chemked.py @@ -956,13 +956,109 @@ def test_time_shift(self, tmp_path): "amount": ["0.21"], } - root, _ = self.convert(document, tmp_path) + root, converted = self.round_trip(document, tmp_path) assert root.find("timeshift").attrib == { "target": "H2", "type": "relative decrease", "amount": "0.21", } + assert converted == document + ChemKED(dict_input=converted) + + def test_time_shift_of_every_datapoint(self, tmp_path): + """The time shift that every datapoint shares is one timeshift element.""" + document = speciation_document("shock tube", ("time", "us")) + document["datapoints"][0]["time-shift"] = {"target": "H2O", "type": "half increase"} + document["datapoints"].append(deepcopy(document["datapoints"][0])) + + root, converted = self.round_trip(document, tmp_path) + + assert [elem.attrib for elem in root.iterfind("timeshift")] == [ + {"target": "H2O", "type": "half increase"} + ] + assert converted == document + ChemKED(dict_input=converted) + + def row_uncertainty_column(self, root, species): + """The per-row uncertainty column of the profile of ``species``, and its values.""" + datagroup = root.find("dataGroup") + for prop in datagroup.iterfind("property[@reference='composition']"): + if prop.find("speciesLink").get("preferredKey") == species: + values = [point.findtext(prop.get("id")) for point in datagroup.iter("dataPoint")] + return prop, values + raise AssertionError(f"no uncertainty column for {species}") + + def test_row_evaluated_standard_deviation(self, tmp_path): + """Rows that end with an evaluated standard deviation are written with one.""" + document = speciation_document() + profile = document["datapoints"][0]["concentration-profiles"][1] + profile["uncertainty"] = [ + { + "evaluated-standard-deviation-type": "absolute", + "evaluated-standard-deviation-sourcetype": "estimated", + "evaluated-standard-deviation-method": "combined from scatter and reported " + "uncertainty", + } + ] + + root, converted = self.round_trip(document, tmp_path) + + assert converted == document + ChemKED(dict_input=converted) + column, values = self.row_uncertainty_column(root, "H2O") + assert {key: value for key, value in column.attrib.items() if key != "id"} == { + "name": "evaluated standard deviation", + "units": "mole fraction", + "reference": "composition", + "kind": "absolute", + "sourcetype": "estimated", + "method": "combined from scatter and reported uncertainty", + } + assert values == ["0.0001", "0.0002"] + # Keys without a value describe the rows, so they are not a common property + common = root.findall("commonProperties/property[@reference='composition']") + assert [prop.find("speciesLink").get("preferredKey") for prop in common] == ["H2"] + + def test_row_and_profile_uncertainty(self, tmp_path): + """A relative uncertainty per row is written beside one about the whole profile.""" + document = speciation_document() + profile = document["datapoints"][0]["concentration-profiles"][0] + profile["values"] = [[800.0, 0.0095, 0.05], [900.0, 0.0071, 0.08]] + profile["uncertainty"][0].update( + {"uncertainty-type": "relative", "uncertainty-sourcetype": "calculated"} + ) + + root, converted = self.round_trip(document, tmp_path) + + assert converted == document + ChemKED(dict_input=converted) + column, values = self.row_uncertainty_column(root, "H2") + assert column.get("name") == "uncertainty" + assert column.get("units") == "unitless" + assert column.get("kind") == "relative" + assert column.get("bound") == "plusminus" + assert column.get("sourcetype") == "calculated" + assert values == ["0.05", "0.08"] + common = root.find("commonProperties/property[@reference='composition']") + assert common.get("name") == "evaluated standard deviation" + assert common.findtext("value") == "0.05" + + def test_row_uncertainty_in_mole_percent(self, tmp_path): + """An absolute uncertainty per row is in the units of its profile.""" + document = speciation_document() + profile = document["datapoints"][0]["concentration-profiles"][1] + profile["quantity"]["units"] = "mole percent" + profile["values"] = [[800.0, 0.05, 0.01], [900.0, 0.29, 0.02]] + profile["uncertainty"] = [{"evaluated-standard-deviation-type": "absolute"}] + + root, converted = self.round_trip(document, tmp_path) + + assert converted == document + column, values = self.row_uncertainty_column(root, "H2O") + assert column.get("name") == "evaluated standard deviation" + assert column.get("units") == "mole percent" + assert values == ["0.01", "0.02"] def test_without_common_properties(self, tmp_path): """Without common-properties, what every datapoint shares is stated once.""" diff --git a/tests/test_converters.py b/tests/test_converters.py index 82c8666..a324ac0 100644 --- a/tests/test_converters.py +++ b/tests/test_converters.py @@ -2268,6 +2268,221 @@ def test_datagroup_without_species(self): get_speciation_datapoints(root) assert "without composition columns cannot be a speciation datapoint" in str(excinfo.value) + def uncertainty_column(self, name="evaluated standard deviation", **attributes): + """An uncertainty column x3 about the H2 profile, absolute and in mole fraction.""" + return { + "name": name, + "id": "x3", + "units": "mole fraction", + "reference": "composition", + "kind": "absolute", + "species": "H2", + **attributes, + } + + def read_profile(self, column, profile_units="mole fraction", values=("0.01", "0.02")): + """Read the H2 profile of a dataGroup whose uncertainty column x3 holds ``values``.""" + root = self.build_root( + [ + {"name": "temperature", "id": "x1", "units": "K"}, + {"name": "composition", "id": "x2", "units": profile_units, "species": "H2"}, + column, + ], + [ + {"x1": "849", "x2": "0.1", "x3": values[0]}, + {"x1": "899", "x2": "0.2", "x3": values[1]}, + ], + ) + return get_speciation_datapoints(root)[0]["concentration-profiles"][0] + + def test_row_evaluated_standard_deviation(self): + """The profile says that its rows end with an evaluated standard deviation.""" + profile = self.read_profile( + self.uncertainty_column( + sourcetype="estimated", method="combined from scatter and reported uncertainty" + ) + ) + + assert [row[2] for row in profile["values"]] == [0.01, 0.02] + # Given without a value, the keys describe the last value of each row + assert profile["uncertainty"] == [ + { + "evaluated-standard-deviation-type": "absolute", + "evaluated-standard-deviation-sourcetype": "estimated", + "evaluated-standard-deviation-method": "combined from scatter and reported " + "uncertainty", + } + ] + + def test_row_uncertainty_with_sourcetype(self): + """The sourcetype of a row uncertainty is kept.""" + profile = self.read_profile( + self.uncertainty_column("uncertainty", bound="plusminus", sourcetype="calculated") + ) + + assert profile["uncertainty"] == [ + {"uncertainty-type": "absolute", "uncertainty-sourcetype": "calculated"} + ] + + def test_plain_row_uncertainty(self): + """An absolute uncertainty with nothing more stated is what a row ends with by default.""" + profile = self.read_profile(self.uncertainty_column("uncertainty", bound="plusminus")) + + assert [row[2] for row in profile["values"]] == [0.01, 0.02] + assert "uncertainty" not in profile + + @pytest.mark.filterwarnings("ignore:Assuming") + @pytest.mark.parametrize( + ("units", "profile_units", "expected"), + [ + # A ppm profile is converted to mole fraction, and so is its uncertainty + ("ppm", "ppm", [1.0e-8, 2.0e-8]), + # An uncertainty may be in other units than its profile + ("mole fraction", "ppm", [0.01, 0.02]), + ("ppm", "mole fraction", [1.0e-8, 2.0e-8]), + ("mole fraction", "percent", [1.0, 2.0]), + ("percent", "mole fraction", [1.0e-4, 2.0e-4]), + # Without units of its own, it is in those of the profile + ("unitless", "ppm", [1.0e-8, 2.0e-8]), + ], + ) + def test_row_uncertainty_in_other_units(self, units, profile_units, expected): + """An absolute uncertainty is converted to the units the profile is stated in.""" + profile = self.read_profile(self.uncertainty_column(units=units), profile_units) + + assert [row[2] for row in profile["values"]] == pytest.approx(expected) + + @pytest.mark.filterwarnings("ignore:Assuming") + def test_relative_row_uncertainty(self): + """A relative uncertainty is a fraction of the amount, so it is not rescaled.""" + column = self.uncertainty_column( + "uncertainty", units="unitless", kind="relative", bound="plusminus" + ) + + profile = self.read_profile(column, "ppm") + + assert [row[2] for row in profile["values"]] == [0.01, 0.02] + assert profile["uncertainty"] == [{"uncertainty-type": "relative"}] + + def test_constant_uncertainty_in_other_units(self): + """An uncertainty that describes the whole profile is converted to its units too.""" + column = self.uncertainty_column("uncertainty", units="ppm", bound="plusminus") + + profile = self.read_profile(column, values=("2", "2")) + + assert len(profile["values"][0]) == 2 + assert profile["uncertainty"][0]["uncertainty-type"] == "absolute" + assert profile["uncertainty"][0]["uncertainty"] == pytest.approx(2.0e-6) + + def test_row_uncertainty_in_incompatible_units(self): + """A mole fraction cannot be stated as a concentration without the density.""" + with pytest.raises(KeywordError, match="cannot be stated in the mol/cm3"): + self.read_profile(self.uncertainty_column(), "mol/cm3") + + def test_varying_bound(self): + """A row ends with a symmetric uncertainty, so one bound cannot vary on its own.""" + with pytest.raises(NotImplementedError, match="ends with a symmetric uncertainty"): + self.read_profile(self.uncertainty_column("uncertainty", bound="upper")) + + def test_row_and_profile_uncertainty_of_one_kind(self): + """One kind of uncertainty cannot describe both the rows and the whole profile.""" + root = self.build_root( + [ + {"name": "temperature", "id": "x1", "units": "K"}, + {"name": "composition", "id": "x2", "units": "mole fraction", "species": "H2"}, + self.uncertainty_column(sourcetype="estimated"), + dict(self.uncertainty_column(), id="x4"), + ], + [ + {"x1": "849", "x2": "0.1", "x3": "0.01", "x4": "0.05"}, + {"x1": "899", "x2": "0.2", "x3": "0.02", "x4": "0.05"}, + ], + ) + + with pytest.raises(NotImplementedError, match="for each row and one for the whole"): + get_speciation_datapoints(root) + + def test_common_uncertainty_of_the_row_kind(self): + """Nor can a common property give a value to the kind that describes the rows.""" + root = self.build_root( + [ + {"name": "temperature", "id": "x1", "units": "K"}, + {"name": "composition", "id": "x2", "units": "mole fraction", "species": "H2"}, + self.uncertainty_column(), + ], + [{"x1": "849", "x2": "0.1", "x3": "0.01"}, {"x1": "899", "x2": "0.2", "x3": "0.02"}], + ) + common = etree.SubElement(root, "commonProperties") + prop = etree.SubElement( + common, + "property", + attrib={ + "name": "evaluated standard deviation", + "units": "mole fraction", + "reference": "composition", + "kind": "absolute", + }, + ) + etree.SubElement(prop, "value").text = "0.05" + properties = {"datapoints": get_speciation_datapoints(root), "common-properties": {}} + + with pytest.raises(NotImplementedError, match="for each row and one for the whole"): + attach_value_metadata(properties, get_value_metadata(root)) + + def time_profile_root(self, datagroups=1): + """A file with ``datagroups`` time profiles of H2.""" + columns = [ + {"name": "time", "id": "x1", "units": "us"}, + {"name": "composition", "id": "x2", "units": "mole fraction", "species": "H2"}, + ] + rows = [{"x1": "0", "x2": "0.01"}, {"x1": "100", "x2": "0.005"}] + root = self.build_root(columns, rows) + for _ in range(datagroups - 1): + root.append(self.build_root(columns, rows).find("dataGroup")) + return root + + def test_time_shift(self): + """The time shift of the file is given to every datapoint.""" + root = self.time_profile_root(datagroups=2) + etree.SubElement( + root, + "timeshift", + attrib={"target": "H2", "type": "relative decrease", "amount": "0.21"}, + ) + + datapoints = get_speciation_datapoints(root) + + assert [datapoint["time-shift"] for datapoint in datapoints] == [ + {"target": "H2", "type": "relative decrease", "amount": ["0.21"]}, + {"target": "H2", "type": "relative decrease", "amount": ["0.21"]}, + ] + + def test_time_shift_without_amount(self): + """A half decrease or increase needs no amount.""" + root = self.time_profile_root() + etree.SubElement(root, "timeshift", attrib={"target": "CO2", "type": "half increase"}) + + datapoint = get_speciation_datapoints(root)[0] + + assert datapoint["time-shift"] == {"target": "CO2", "type": "half increase"} + + def test_time_shift_without_type(self): + """A time shift names how the zero was placed.""" + root = self.time_profile_root() + etree.SubElement(root, "timeshift", attrib={"target": "H2"}) + + with pytest.raises(MissingAttributeError, match="type of timeshift"): + get_speciation_datapoints(root) + + def test_two_time_shifts(self): + """A datapoint has one time shift.""" + root = self.time_profile_root() + for target in ["H2", "CO"]: + etree.SubElement(root, "timeshift", attrib={"target": target, "type": "half decrease"}) + + with pytest.raises(NotImplementedError, match="2 timeshift elements"): + get_speciation_datapoints(root) + @pytest.mark.usefixtures("mock_crossref_api") class TestConvertReSpecTh: diff --git a/tests/test_validation.py b/tests/test_validation.py index 0e1f194..df791cc 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -12,6 +12,9 @@ v = OurValidator(schema) +# The speciation measurement datapoints schema on its own, without the other datapoint schemas +speciation = OurValidator({"datapoints": schema["datapoints"]["anyof"][2]}) + def test_current_version_is_allowed(): """The version the converters stamp into new files has to be an allowed one. @@ -1000,6 +1003,100 @@ def test_profile_uncertainty_does_not_require_inline_measured_value(self): } assert v.validate({"datapoints": [datapoint]}, update=True) + def speciation_datapoint(self, values, metadata): + """A speciation datapoint whose H2 profile has ``values`` and uncertainty ``metadata``. + + It is validated with `speciation`, since in update mode the other datapoint schemas of the + ``anyof`` accept it whatever its profiles hold. + """ + return { + "pressure": ["1 atm"], + "composition": { + "kind": "mole fraction", + "species": [{"species-name": "H2", "InChI": "1S/H2/h1H", "amount": [1.0]}], + }, + "independent-variables": [{"name": "time", "units": "s"}], + "concentration-profiles": [ + { + "species-name": "H2", + "InChI": "1S/H2/h1H", + "quantity": {"units": "mole fraction"}, + "values": values, + "uncertainty": [metadata], + } + ], + } + + @pytest.mark.parametrize( + "metadata", + [ + { + "evaluated-standard-deviation-type": "absolute", + "evaluated-standard-deviation-sourcetype": "estimated", + "evaluated-standard-deviation-method": "statistical scatter", + }, + {"uncertainty-type": "relative"}, + # The kind with a value describes the profile, the other the rows + { + "uncertainty-type": "relative", + "uncertainty": 0.05, + "evaluated-standard-deviation-type": "absolute", + }, + ], + ) + def test_profile_uncertainty_that_describes_the_rows(self, metadata): + """Uncertainty keys given without a value describe the last value of each row.""" + datapoint = self.speciation_datapoint([[0.0, 0.1, 0.01], [1.0, 0.2, 0.02]], metadata) + assert speciation.validate({"datapoints": [datapoint]}), speciation.errors + + @pytest.mark.parametrize( + ("values", "metadata", "message"), + [ + # The rows have no uncertainty for the keys to describe + ( + [[0.0, 0.1], [1.0, 0.2]], + {"evaluated-standard-deviation-type": "absolute"}, + "no row ends with one", + ), + # A row ends with only one uncertainty + ( + [[0.0, 0.1, 0.01], [1.0, 0.2, 0.02]], + {"uncertainty-type": "absolute", "evaluated-standard-deviation-type": "absolute"}, + "describes both", + ), + # Whether the value in the rows is absolute or relative must be stated + ( + [[0.0, 0.1, 0.01], [1.0, 0.2, 0.02]], + {"uncertainty-sourcetype": "calculated"}, + "must give uncertainty-type", + ), + # Metadata that describes nothing is still an error + ([[0.0, 0.1], [1.0, 0.2]], {}, "must contain at least one"), + ], + ) + def test_profile_uncertainty_that_cannot_describe_the_rows(self, values, metadata, message): + """Keys without a value need rows with an uncertainty, and must say what it is.""" + datapoint = self.speciation_datapoint(values, metadata) + assert not speciation.validate({"datapoints": [datapoint]}) + assert message in str(speciation.errors) + + @pytest.mark.parametrize( + ("time_shift", "valid"), + [ + ({"target": "H2", "type": "half decrease"}, True), + ({"target": "CO2", "type": "half increase"}, True), + ({"target": "H2", "type": "relative decrease", "amount": ["0.21"]}, True), + ({"target": "H2", "type": "quarter decrease"}, False), + ], + ) + def test_time_shift_type(self, time_shift, valid): + """A time shift is placed at a half decrease or increase, or a relative decrease.""" + datapoint = self.speciation_datapoint( + [[0.0, 0.1], [1.0, 0.2]], {"uncertainty-type": "relative", "uncertainty": 0.05} + ) + datapoint["time-shift"] = time_shift + assert speciation.validate({"datapoints": [datapoint]}) is valid + def test_evaluated_standard_deviation_requires_type(self): """Ensure an ESD value without evaluated-standard-deviation-type is rejected.""" metadata = {"evaluated-standard-deviation": 0.1} From 557f1223465f97ba14383d6ae4a6afa9be3c3498 Mon Sep 17 00:00:00 2001 From: Lekia Prosper Date: Mon, 26 Oct 2026 13:03:41 -0400 Subject: [PATCH 10/13] Convert common profile uncertainties to the profile's units A common uncertainty about a concentration profile was scaled to its own kind, not the profile's, so an evaluated standard deviation in mole fraction stayed a mole fraction on a mole percent profile, and on a mol/cm3 profile. It is now converted with uncertainty_factor, like a dataGroup column. An uncertainty that cannot be stated in the profile's units, such as a mole fraction about a concentration, which would need the density of the mixture, is dropped with a warning, in a column as well as common. It is not given to the inlet amount of the species instead. --- CHANGELOG.md | 2 +- src/pyked/converters.py | 50 +++++++++++++++------- tests/test_converters.py | 91 +++++++++++++++++++++++++++++++++------- 3 files changed, 112 insertions(+), 31 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 748d6d4..f079e12 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,7 +29,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed - An `uncertainty` common property with `bound="upper"` or `bound="lower"` was read as a symmetric uncertainty, so the second bound overwrote the first. The bound is now kept, as it already was for a dataGroup column -- An uncertainty column about a concentration profile was scaled by the unit factor of the profile instead of its own: an evaluated standard deviation in mole fraction on a ppm profile came out 10⁶ too small, and one on a percent profile 100 too small. An absolute uncertainty is now converted from its own units to those of the profile, and a relative one is not rescaled +- An uncertainty column about a concentration profile was scaled by the unit factor of the profile instead of its own: an evaluated standard deviation in mole fraction on a ppm profile came out 10⁶ too small, and one on a percent profile 100 too small. A common uncertainty about a profile was scaled to its own kind, so one in mole fraction stayed a mole fraction on a mole percent or mol/cm3 profile. An absolute uncertainty, in a column or common, is now converted from its own units to those of the profile, and a relative one is not rescaled. One that cannot be converted, such as a mole fraction about a concentration profile, which would need the density of the mixture, is dropped with a warning - A composition amount of exactly zero, meaning a species measured as absent, is accepted when it carries uncertainty metadata. It was accepted without metadata and rejected with it, and `isvalid_composition` already allowed it. Only a negative value is an error for a property with no configured units - The unsupported-composition-units error lists the units the converter actually accepts, built from `composition_units` rather than hand-written, so it cannot fall behind the table again - Every text file is now opened with an explicit UTF-8 encoding. Reading or writing a ChemKED or ReSpecTh file whose author names contain non-ASCII characters previously depended on the platform's preferred encoding, and failed on Windows. `convert_to_ReSpecTh` could also rewrite its pretty-printed XML in the platform encoding while declaring UTF-8 in the file. The ruff rule `PLW1514` now enforces this diff --git a/src/pyked/converters.py b/src/pyked/converters.py index 0109c3f..c82bd98 100644 --- a/src/pyked/converters.py +++ b/src/pyked/converters.py @@ -952,7 +952,7 @@ def format_row_uncertainty(item): return metadata -def uncertainty_factor(item, profile_units): +def uncertainty_factor(item, profile_units, species): """Scale factor that states an uncertainty about a profile in the units of the profile. ReSpecTh gives an uncertainty units of its own, which need not be those of the composition it @@ -960,15 +960,18 @@ def uncertainty_factor(item, profile_units): profile is converted to its ChemKED kind, so an absolute uncertainty is converted to the same kind. A relative uncertainty is a fraction of the amount, so it is not rescaled. + Some cannot be converted. A mole fraction is stated as a concentration only with the density + of the mixture at each point, which the file does not give, so such an uncertainty is dropped + with a warning rather than attached in the wrong units. + Args: - item (`dict`): Descriptor of the uncertainty, with its ``kind`` and ``units`` - profile_units (`str`): ReSpecTh units of the profile + item (`dict`): Descriptor of the uncertainty, with its ``name``, ``kind`` and ``units`` + profile_units (`str`): ReSpecTh units of the profile, or its ChemKED kind + species (`str`): The species of the profile, named in the warning Returns: - `float`: The factor to multiply the uncertainty by - - Raises: - `KeywordError`: If an absolute uncertainty cannot be stated in the units of the profile + `float`: The factor to multiply the uncertainty by, or `None` if it cannot be stated in + the units of the profile """ if item["kind"] == "relative": return 1.0 @@ -984,9 +987,12 @@ def uncertainty_factor(item, profile_units): return own_factor if own_kind in fraction_kinds and kind in fraction_kinds: return own_factor * fraction_kinds[own_kind] / fraction_kinds[kind] - raise KeywordError( - f"{item['name']} in {units} cannot be stated in the {kind} of the profile it describes" + + warn( + f"Dropping {item['name']} in {units} of the {species} profile, which cannot be stated in " + f"the {kind} of the profile" ) + return None def merge_profile_metadata(profile, metadata): @@ -1056,11 +1062,18 @@ def attach_value_metadata(properties, metadata): # A speciation datapoint keeps its measured species in profiles for datapoint in datapoints: for profile in datapoint.get("concentration-profiles", []): - if item["species"] in (None, profile["species-name"]): + if item["species"] not in (None, profile["species-name"]): + continue + # The profile is what it describes, even if it cannot be converted + attached = True + profile_factor = uncertainty_factor( + item, profile["quantity"]["units"], profile["species-name"] + ) + if profile_factor is not None: merge_profile_metadata( - profile, format_value_metadata(item, factor=factor, numeric=True) + profile, + format_value_metadata(item, factor=profile_factor, numeric=True), ) - attached = True if not attached: # Otherwise it describes the amount of that species in the mixture, which may be @@ -1428,7 +1441,11 @@ def split_metadata(key): ("composition", column["species"]) ) if uncertainty_column is not None: - row_factor = uncertainty_factor(uncertainty_column, column["units"]) + row_factor = uncertainty_factor( + uncertainty_column, column["units"], column["species"] + ) + if row_factor is None: + uncertainty_column = None values = [] for row in rows: @@ -1444,9 +1461,14 @@ def split_metadata(key): profile["quantity"] = {"units": kind} profile["values"] = values for constant_column in constant_columns: + constant_factor = uncertainty_factor( + constant_column, column["units"], column["species"] + ) + if constant_factor is None: + continue metadata = format_value_metadata( dict(constant_column, value=rows[0][constant_column["id"]]), - factor=uncertainty_factor(constant_column, column["units"]), + factor=constant_factor, numeric=True, ) merge_profile_metadata(profile, metadata) diff --git a/tests/test_converters.py b/tests/test_converters.py index a324ac0..2bcf0b8 100644 --- a/tests/test_converters.py +++ b/tests/test_converters.py @@ -2374,10 +2374,15 @@ def test_constant_uncertainty_in_other_units(self): assert profile["uncertainty"][0]["uncertainty-type"] == "absolute" assert profile["uncertainty"][0]["uncertainty"] == pytest.approx(2.0e-6) - def test_row_uncertainty_in_incompatible_units(self): - """A mole fraction cannot be stated as a concentration without the density.""" - with pytest.raises(KeywordError, match="cannot be stated in the mol/cm3"): - self.read_profile(self.uncertainty_column(), "mol/cm3") + @pytest.mark.parametrize("values", [("0.01", "0.02"), ("0.01", "0.01")]) + def test_uncertainty_column_in_incompatible_units(self, values): + """A mole fraction cannot be stated as a concentration without the density, so a row or + whole-profile uncertainty in one is dropped.""" + with pytest.warns(UserWarning, match="cannot be stated in the mol/cm3 of the profile"): + profile = self.read_profile(self.uncertainty_column(), "mol/cm3", values) + + assert [len(row) for row in profile["values"]] == [2, 2] + assert "uncertainty" not in profile def test_varying_bound(self): """A row ends with a symmetric uncertainty, so one bound cannot vary on its own.""" @@ -2402,33 +2407,87 @@ def test_row_and_profile_uncertainty_of_one_kind(self): with pytest.raises(NotImplementedError, match="for each row and one for the whole"): get_speciation_datapoints(root) - def test_common_uncertainty_of_the_row_kind(self): - """Nor can a common property give a value to the kind that describes the rows.""" - root = self.build_root( - [ - {"name": "temperature", "id": "x1", "units": "K"}, - {"name": "composition", "id": "x2", "units": "mole fraction", "species": "H2"}, - self.uncertainty_column(), - ], - [{"x1": "849", "x2": "0.1", "x3": "0.01"}, {"x1": "899", "x2": "0.2", "x3": "0.02"}], - ) + def add_common_deviation(self, root, units="mole fraction"): + """State an absolute evaluated standard deviation of 0.0005 about every profile.""" common = etree.SubElement(root, "commonProperties") prop = etree.SubElement( common, "property", attrib={ "name": "evaluated standard deviation", - "units": "mole fraction", + "units": units, "reference": "composition", "kind": "absolute", }, ) - etree.SubElement(prop, "value").text = "0.05" + etree.SubElement(prop, "value").text = "0.0005" + + def test_common_uncertainty_of_the_row_kind(self): + """Nor can a common property give a value to the kind that describes the rows.""" + root = self.build_root( + [ + {"name": "temperature", "id": "x1", "units": "K"}, + {"name": "composition", "id": "x2", "units": "mole fraction", "species": "H2"}, + self.uncertainty_column(), + ], + [{"x1": "849", "x2": "0.1", "x3": "0.01"}, {"x1": "899", "x2": "0.2", "x3": "0.02"}], + ) + self.add_common_deviation(root) properties = {"datapoints": get_speciation_datapoints(root), "common-properties": {}} with pytest.raises(NotImplementedError, match="for each row and one for the whole"): attach_value_metadata(properties, get_value_metadata(root)) + def read_with_common_deviation(self, units, profile_units): + """Read a file whose H2 profile is in ``profile_units`` and whose inlet holds H2, with a + common evaluated standard deviation in ``units``.""" + root = self.build_root( + [ + {"name": "temperature", "id": "x1", "units": "K"}, + {"name": "composition", "id": "x2", "units": profile_units, "species": "H2"}, + ], + [{"x1": "849", "x2": "0.1"}, {"x1": "899", "x2": "0.2"}], + ) + self.add_common_deviation(root, units) + properties = { + "datapoints": get_speciation_datapoints(root), + "common-properties": { + "composition": { + "kind": "mole fraction", + "species": [{"species-name": "H2", "amount": [0.01]}], + } + }, + } + attach_value_metadata(properties, get_value_metadata(root)) + return properties + + @pytest.mark.filterwarnings("ignore:Assuming") + @pytest.mark.parametrize( + ("units", "profile_units", "expected"), + [ + # A percent profile stays in mole percent, so a mole fraction uncertainty is converted + ("mole fraction", "percent", 0.05), + # A ppm profile is converted to mole fraction, which the uncertainty is already in + ("mole fraction", "ppm", 0.0005), + ("ppm", "mole fraction", 5.0e-10), + ], + ) + def test_common_uncertainty_in_other_units(self, units, profile_units, expected): + """A common uncertainty about a profile is converted to the units of the profile.""" + properties = self.read_with_common_deviation(units, profile_units) + + profile = properties["datapoints"][0]["concentration-profiles"][0] + assert profile["uncertainty"][0]["evaluated-standard-deviation"] == pytest.approx(expected) + + def test_common_uncertainty_in_incompatible_units(self): + """A common mole fraction uncertainty about a concentration profile is dropped.""" + with pytest.warns(UserWarning, match="mole fraction of the H2 profile, which cannot be"): + properties = self.read_with_common_deviation("mole fraction", "mol/cm3") + + assert "uncertainty" not in properties["datapoints"][0]["concentration-profiles"][0] + # It describes the profile, so it is not given to the inlet amount of H2 instead + assert properties["common-properties"]["composition"]["species"][0]["amount"] == [0.01] + def time_profile_root(self, datagroups=1): """A file with ``datagroups`` time profiles of H2.""" columns = [ From 5b3be3ecbe1572946574cc63947bec5b940d5b1b Mon Sep 17 00:00:00 2001 From: Kyle Niemeyer Date: Fri, 13 Nov 2026 10:47:54 -0800 Subject: [PATCH 11/13] Format the files this pull request changes with ruff The ruff-format pre-commit hook rejects any commit touching these files as they stand. Layout only, with no change in behavior. Co-Authored-By: Claude Opus 5.5 --- src/pyked/chemked.py | 4 +--- src/pyked/validation.py | 19 ++++++++----------- tests/test_validation.py | 17 ++++------------- 3 files changed, 13 insertions(+), 27 deletions(-) diff --git a/src/pyked/chemked.py b/src/pyked/chemked.py index 5044309..4049b23 100644 --- a/src/pyked/chemked.py +++ b/src/pyked/chemked.py @@ -1509,9 +1509,7 @@ def __init__(self, properties): self._store_evaluated_standard_deviation( "equivalence-ratio", properties["equivalence-ratio"] ) - self.equivalence_ratio = self.process_equivalence_ratio( - properties.get("equivalence-ratio") - ) + self.equivalence_ratio = self.process_equivalence_ratio(properties.get("equivalence-ratio")) self.ignition_type = deepcopy(properties.get("ignition-type")) if "time-histories" in properties and "volume-history" in properties: diff --git a/src/pyked/validation.py b/src/pyked/validation.py index 5caf8c8..b130036 100644 --- a/src/pyked/validation.py +++ b/src/pyked/validation.py @@ -711,9 +711,7 @@ def _check_uncertainty_metadata(self, field, metadata): "upper-uncertainty", "lower-uncertainty", } - has_uncertainty_value = any( - metadata.get(key) is not None for key in uncertainty_value_keys - ) + has_uncertainty_value = any(metadata.get(key) is not None for key in uncertainty_value_keys) has_evaluated_sd_value = metadata.get("evaluated-standard-deviation") is not None if has_uncertainty_value or has_evaluated_sd_value: @@ -741,9 +739,7 @@ def _check_uncertainty_metadata_values(self, field, uncertainty_dict, require_va uncertainty_type = uncertainty_dict.get("uncertainty-type") for key in ["uncertainty", "upper-uncertainty", "lower-uncertainty"]: if uncertainty_dict.get(key) is not None: - self._check_uncertainty_value( - field, key, uncertainty_dict[key], uncertainty_type - ) + self._check_uncertainty_value(field, key, uncertainty_dict[key], uncertainty_type) if uncertainty_dict.get("evaluated-standard-deviation") is not None: self._check_uncertainty_value( @@ -753,9 +749,7 @@ def _check_uncertainty_metadata_values(self, field, uncertainty_dict, require_va uncertainty_dict.get("evaluated-standard-deviation-type"), ) - def _validate_isvalid_profile_uncertainty( - self, isvalid_profile_uncertainty, field, value - ): + def _validate_isvalid_profile_uncertainty(self, isvalid_profile_uncertainty, field, value): """Validate uncertainty metadata associated with a concentration profile. Metadata that only describes the uncertainty at the end of each row needs no value of its @@ -856,8 +850,11 @@ def _validate_isvalid_reference(self, isvalid_reference, field, value): authors = value["authors"][:] author_names = [a["name"] for a in authors] for author in ref["author"]: - author = {**author, "given": html.unescape(author.get("given", "")), - "family": html.unescape(author.get("family", ""))} + author = { + **author, + "given": html.unescape(author.get("given", "")), + "family": html.unescape(author.get("family", "")), + } # find using family name author_match = next( ( diff --git a/tests/test_validation.py b/tests/test_validation.py index df791cc..a27a8fb 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -632,10 +632,7 @@ def test_invalid_apparatus_kind(self): """Ensure that an apparatus kind outside the schema is an error""" # update=True means to ignore required keys that are left out for testing v.validate({"apparatus": {"kind": "internal combustion engine"}}, update=True) - assert ( - v.errors["apparatus"][0]["kind"][0] - == "unallowed value internal combustion engine" - ) + assert v.errors["apparatus"][0]["kind"][0] == "unallowed value internal combustion engine" @pytest.mark.parametrize( "valid_kind", @@ -966,9 +963,7 @@ def test_evaluated_standard_deviation_metadata_value(self): def test_common_property_uncertainty_requires_property_value(self): """Common-property uncertainty metadata cannot appear without its property value.""" metadata = {"uncertainty-type": "relative", "uncertainty": 0.1} - assert not v.validate( - {"common-properties": {"temperature": [metadata]}}, update=True - ) + assert not v.validate({"common-properties": {"temperature": [metadata]}}, update=True) assert v.validate( {"common-properties": {"temperature": ["1000 kelvin", metadata]}}, update=True, @@ -995,9 +990,7 @@ def test_profile_uncertainty_does_not_require_inline_measured_value(self): "InChI": "1S/H2/h1H", "quantity": {"units": "mole fraction"}, "values": [[0.0, 0.1], [1.0, 0.2]], - "uncertainty": [ - {"uncertainty-type": "relative", "uncertainty": 0.05} - ], + "uncertainty": [{"uncertainty-type": "relative", "uncertainty": 0.05}], } ], } @@ -1113,9 +1106,7 @@ def test_evaluated_standard_deviation_requires_type(self): } ], } - assert not v.validate( - {"common-properties": {"composition": composition}}, update=True - ) + assert not v.validate({"common-properties": {"composition": composition}}, update=True) @pytest.mark.parametrize("quantity, unit", property_units.items()) def test_absolute_evaluated_standard_deviation_validation(self, quantity, unit): From 014d4facad9cf99359d7ef5c54316dc2da9655c4 Mon Sep 17 00:00:00 2001 From: Kyle Niemeyer Date: Fri, 13 Nov 2026 10:48:15 -0800 Subject: [PATCH 12/13] Treat absolute uncertainties in degC and degF as temperature differences An uncertainty is a span, but Pint converts a quantity in an offset unit as a point on the scale. So an uncertainty of 10 degC about a temperature in kelvin was loaded as 283.15 K, a temperature in degC with an uncertainty of 10 K failed to load because the uncertainty became -263.15 degC, and a negative uncertainty such as -5 degC passed the sign check in validation as 268.15 K. The larger of two asymmetric bounds was also chosen by comparing them as temperatures. The new _as_difference restates a quantity in an offset unit in Pint's delta unit, which converts as a span. Validation checks the sign of an absolute uncertainty or evaluated standard deviation as a span, and DataPoint converts absolute uncertainties, the bounds it compares, and absolute evaluated standard deviations the same way. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + src/pyked/chemked.py | 27 +++++++++++++----- src/pyked/validation.py | 23 +++++++++++++++ tests/test_chemked.py | 61 ++++++++++++++++++++++++++++++++++++++++ tests/test_validation.py | 57 +++++++++++++++++++++++++++++++++++++ 5 files changed, 162 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f079e12..11c1a54 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,6 +45,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Numeric values are normalized on conversion by the new `normalize_value`: leading zeros are stripped, since YAML reads them as octal, and a Fortran-style exponent written without the `e` is expanded so Pint can read it. Trailing zeros are deliberately left alone, being significant figures. A page range no longer keeps spaces around its dash, so it reads `446-457` rather than `446 - 457` - Text taken from a CrossRef DOI lookup is HTML-unescaped, so a journal reaches the file as `Energy & Fuels` rather than `Energy & Fuels`. Author names are unescaped the same way - A DOI written as a resolvable URL, such as `doi.org/10.1016/j.proci.2016.05.048`, is reduced to the bare identifier on conversion. Some ReSpecTh files write it that way and no DOI lookup accepts it +- An absolute uncertainty or evaluated standard deviation in `degC` or `degF` is treated as a temperature difference rather than a temperature, in validation and when a file is loaded. An uncertainty of `10 degC` was loaded as ±283.15 K instead of ±10 K; a temperature in `degC` with an uncertainty in kelvin failed to load, since 10 K became -263.15 degC; and a negative uncertainty such as `-5 degC` passed validation as 268.15 K ## [0.5.0] - 2026-07-02 ### Added diff --git a/src/pyked/chemked.py b/src/pyked/chemked.py index 4049b23..b02b996 100644 --- a/src/pyked/chemked.py +++ b/src/pyked/chemked.py @@ -22,7 +22,15 @@ ) # Local imports -from .validation import Q_, OurValidator, _normalize_unit_str, row_uncertainty_kinds, schema, yaml +from .validation import ( + Q_, + OurValidator, + _as_difference, + _normalize_unit_str, + row_uncertainty_kinds, + schema, + yaml, +) respecth_property_names = {field: name for name, field in common_property_fields.items()} """`dict`: ChemKED field name mapped to the ReSpecTh property name, the inverse of @@ -1598,7 +1606,8 @@ def process_evaluated_standard_deviation(self, properties): esd_type = metadata.get("evaluated-standard-deviation-type") if esd_type == "absolute": - value = Q_(_normalize_unit_str(esd)) + # A standard deviation is a span, so one in degC is kept in delta_degC + value = _as_difference(Q_(_normalize_unit_str(esd))) else: value = float(Q_(_normalize_unit_str(esd)).magnitude) @@ -1664,9 +1673,13 @@ def process_quantity(self, properties): '"lower-uncertainty" need to be specified.' ) elif uncertainty_type == "absolute": + # An uncertainty is a span, not a point on the scale of the quantity, so it is + # converted as a difference: 10 degC of uncertainty about a temperature in kelvin + # is 10 K, not 283.15 K, and 10 K about one in degC is 10 delta_degC. + span_units = _as_difference(quant).units if uncertainty is not None: - uncertainty = Q_(_normalize_unit_str(uncertainty)) - quant = quant.plus_minus(uncertainty.to(quant.units).magnitude) + uncertainty = _as_difference(Q_(_normalize_unit_str(uncertainty))) + quant = quant.plus_minus(uncertainty.to(span_units).magnitude) elif upper_uncertainty is not None and lower_uncertainty is not None: warn( "Asymmetric uncertainties are not supported. The " @@ -1674,10 +1687,10 @@ def process_quantity(self, properties): "has been used as the symmetric uncertainty." ) uncertainty = max( - Q_(_normalize_unit_str(upper_uncertainty)), - Q_(_normalize_unit_str(lower_uncertainty)), + _as_difference(Q_(_normalize_unit_str(upper_uncertainty))), + _as_difference(Q_(_normalize_unit_str(lower_uncertainty))), ) - quant = quant.plus_minus(uncertainty.to(quant.units).magnitude) + quant = quant.plus_minus(uncertainty.to(span_units).magnitude) else: raise ValueError( 'Either "uncertainty" or "upper-uncertainty" and ' diff --git a/src/pyked/validation.py b/src/pyked/validation.py index b130036..e5d2d76 100644 --- a/src/pyked/validation.py +++ b/src/pyked/validation.py @@ -43,6 +43,27 @@ def _normalize_unit_str(val_str): Q_ = units.Quantity + +def _as_difference(quantity): + """Read a quantity as a difference between two values rather than as a point on a scale. + + An uncertainty is a span. Celsius and Fahrenheit are offset scales, on which 10 degC as a + temperature is 283.15 K but an uncertainty of 10 degC spans 10 K. Pint converts a quantity in + an offset unit as a point, so it is restated in Pint's delta unit, which converts as a span. + Every other unit converts the same either way and is returned unchanged. + + Args: + quantity (`~pint.Quantity`): The quantity, such as an uncertainty + + Returns: + `~pint.Quantity`: The same quantity, in a delta unit if it was in an offset unit + """ + delta_units = f"delta_{quantity.units}" + if delta_units in units: + return Q_(quantity.magnitude, delta_units) + return quantity + + crossref_api = habanero.Crossref(mailto="prometheus@pr.omethe.us") # Load the ChemKED schema definition file @@ -673,6 +694,8 @@ def _check_uncertainty_value(self, field, key, value, kind): quantity = self._parse_quantity(field, value) if quantity is None: return + # An uncertainty is a span, so -5 degC of it is -5 K, not 268.15 K + quantity = _as_difference(quantity) expected_units = property_units.get(field) if expected_units is None: diff --git a/tests/test_chemked.py b/tests/test_chemked.py index c72a8bc..541ceed 100644 --- a/tests/test_chemked.py +++ b/tests/test_chemked.py @@ -1630,6 +1630,67 @@ def test_unit_normalization_asymmetric_uncertainty(self): assert np.isclose(datapoint.pressure.value.to("pascal").magnitude, 220000) assert np.isclose(datapoint.pressure.error.to("pascal").magnitude, 2000) + @staticmethod + def load_with_temperature(temperature): + """Load testfile_st.yaml with the temperature of its first datapoint replaced.""" + filename = Path("tests") / "testfile_st.yaml" + with open(filename, encoding="utf-8") as f: + properties = yaml.safe_load(f) + properties["datapoints"][0]["temperature"] = temperature + return ChemKED(dict_input=properties).datapoints[0] + + @pytest.mark.parametrize( + "temperature, uncertainty", + [ + ("1164.48 kelvin", "10 degC"), + ("1164.48 kelvin", "18 degF"), + ("891.33 degC", "10 kelvin"), + ("891.33 degC", "10 degC"), + ("1636.394 degF", "10 kelvin"), + ], + ) + def test_offset_unit_uncertainty_is_a_span(self, temperature, uncertainty): + """An uncertainty in degC or degF spans that many degrees; it is not a temperature. + + 10 degC of uncertainty is 10 K, not 283.15 K, and 10 K about a temperature in degC is + 10 degC, not -263.15 degC, which `uncertainties` refuses as a negative error. + """ + datapoint = self.load_with_temperature( + [temperature, {"uncertainty-type": "absolute", "uncertainty": uncertainty}] + ) + in_kelvin = datapoint.temperature.to("kelvin") + assert np.isclose(in_kelvin.value.magnitude, 1164.48) + assert np.isclose(in_kelvin.error.magnitude, 10.0) + + def test_offset_unit_asymmetric_uncertainty_is_a_span(self): + """The larger bound is chosen as a span: 20 K is larger than 5 degC, which spans 5 K.""" + with pytest.warns(UserWarning, match="Asymmetric uncertainties"): + datapoint = self.load_with_temperature( + [ + "1164.48 kelvin", + { + "uncertainty-type": "absolute", + "upper-uncertainty": "5 degC", + "lower-uncertainty": "20 kelvin", + }, + ] + ) + assert np.isclose(datapoint.temperature.error.to("kelvin").magnitude, 20.0) + + def test_offset_unit_evaluated_standard_deviation_is_a_span(self): + """An evaluated standard deviation of 10 degC is stored as a span of 10 K.""" + datapoint = self.load_with_temperature( + [ + "1164.48 kelvin", + { + "evaluated-standard-deviation": "10 degC", + "evaluated-standard-deviation-type": "absolute", + }, + ] + ) + esd = datapoint.evaluated_standard_deviation["temperature"] + assert np.isclose(esd.value.to("kelvin").magnitude, 10.0) + def test_volume_history(self): """Test that volume history works properly. diff --git a/tests/test_validation.py b/tests/test_validation.py index a27a8fb..1f1083f 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -1664,6 +1664,63 @@ def test_zero_value_still_rejected(self, quantity, unit): assert validator.errors[quantity][0] == f"value must be greater than 0.0 {unit}" +class TestOffsetUnitUncertainty: + """An absolute uncertainty in an offset unit is a span, not a point on the scale. + + 10 degC as a temperature is 283.15 K, but an uncertainty of 10 degC spans 10 K. Converted as a + point, -5 degC would pass the sign check as 268.15 K. + """ + + @staticmethod + def validate_temperature(metadata): + validator = OurValidator({"temperature": {"type": "list", "isvalid_uncertainty": True}}) + validator.validate({"temperature": ["1000 K", metadata]}) + return validator + + @pytest.mark.parametrize( + "metadata", + [ + {"uncertainty-type": "absolute", "uncertainty": "10 degC"}, + {"uncertainty-type": "absolute", "uncertainty": "18 degF"}, + {"uncertainty-type": "absolute", "uncertainty": "0 degC"}, + { + "uncertainty-type": "absolute", + "upper-uncertainty": "10 degC", + "lower-uncertainty": "5 degC", + }, + { + "evaluated-standard-deviation": "10 degC", + "evaluated-standard-deviation-type": "absolute", + }, + ], + ) + def test_offset_unit_uncertainty_accepted(self, metadata): + """A positive or zero span in degC or degF is an ordinary uncertainty.""" + validator = self.validate_temperature(metadata) + assert not validator.errors, validator.errors + + @pytest.mark.parametrize( + "metadata", + [ + {"uncertainty-type": "absolute", "uncertainty": "-5 degC"}, + {"uncertainty-type": "absolute", "uncertainty": "-5 degF"}, + { + "uncertainty-type": "absolute", + "upper-uncertainty": "10 degC", + "lower-uncertainty": "-5 degC", + }, + { + "evaluated-standard-deviation": "-5 degC", + "evaluated-standard-deviation-type": "absolute", + }, + ], + ) + def test_negative_offset_unit_uncertainty_rejected(self, metadata): + """-5 degC of uncertainty is -5 K, so it is negative, not 268.15 K.""" + validator = self.validate_temperature(metadata) + assert "uncertainty must not be negative" in str(validator.errors) + + class TestCrossrefComparisonUnescapes: """The converter unescapes CrossRef text, so validation must compare likewise.""" From 833fa78ecb6cc2aa56a6be8d035cd8d00e611732 Mon Sep 17 00:00:00 2001 From: Kyle Niemeyer Date: Fri, 13 Nov 2026 11:02:43 -0800 Subject: [PATCH 13/13] Require Python 3.12 and Pint 0.26 Pint 0.26 is the first release that reads a value written as a string in an offset unit, such as "25 degC"; earlier releases take it for 25 multiplied by degC and raise OffsetUnitCalculusError. The loader parses values in that string form, so with Pint 0.24 (the last release for Python 3.10) or 0.25 (the last for Python 3.11) a file with a temperature in degC or degF failed to load, and the new tests of uncertainties in those units failed on the Python 3.10 and 3.11 CI jobs. Pint 0.26 itself requires Python 3.12, so Python 3.10 and 3.11 are dropped: requires-python, the classifiers, the CI matrix and the ruff target move to 3.12, and pint is required at >=0.26 so an older Pint already installed on Python 3.12 or later is upgraded rather than kept. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 2 +- CHANGELOG.md | 1 + pyproject.toml | 8 +++----- 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 42f88ad..eb8910e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,7 +13,7 @@ jobs: fail-fast: false matrix: os: [ubuntu-latest] - python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"] + python-version: ["3.12", "3.13", "3.14"] include: - os: macos-latest python-version: "3.14" diff --git a/CHANGELOG.md b/CHANGELOG.md index 11c1a54..b0fe304 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - A concentration profile can say what the uncertainty at the end of each row is: the fields of one kind in its `uncertainty` mapping given without a value, such as `evaluated-standard-deviation-type`, `-sourcetype` and `-method`, describe the row values. `get_speciation_datapoints` records the name, kind, sourcetype and method of a varying uncertainty column this way, and `convert_to_ReSpecTh` writes the column back as described. A plain absolute uncertainty with no sourcetype needs no fields, and remains what a row's last value means by default ### Changed +- Python 3.12 or later and Pint 0.26 or later are required; Python 3.10 and 3.11 are no longer supported. Pint 0.26 itself requires Python 3.12, and earlier Pint releases cannot read a value written as a string in an offset unit, such as `"25 degC"`, so a file with a temperature in `degC` or `degF` failed to load with them - The `tubular reactor` apparatus kind is renamed `flow reactor`, the name ReSpecTh, the ChemKED database, and the speciation literature all use. `tubular reactor` is still accepted as converter input and maps to `flow reactor` - The mole and mass fraction sum check uses a relative tolerance of 1e-3 (`composition_sum_tolerance`) rather than the NumPy default of 1e-5, so compositions reported to a few digits are not rejected for round-off - An auxiliary profile against a `residence-time` axis is recorded with the axis name `time`, which `auxiliary-profiles.independent.name` allows, since a residence time is a time coordinate diff --git a/pyproject.toml b/pyproject.toml index 7b82876..2a8985e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -23,19 +23,17 @@ classifiers = [ 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.10', - 'Programming Language :: Python :: 3.11', 'Programming Language :: Python :: 3.12', 'Programming Language :: Python :: 3.13', 'Programming Language :: Python :: 3.14', 'Topic :: Scientific/Engineering :: Chemistry', ] -requires-python = ">=3.10" +requires-python = ">=3.12" dependencies = [ "numpy>=2.0.0", "pyyaml", "cerberus", - "pint>0.24.0", + "pint>=0.26", "uncertainties>=3.2", "habanero>=2.9.1", "httpx2>=2.0", @@ -84,7 +82,7 @@ filterwarnings = [ # https://github.com/charliermarsh/ruff [tool.ruff] line-length = 100 -target-version = "py310" +target-version = "py312" [tool.ruff.lint] # PLW1514 requires an explicit encoding on every text file that is opened. Without it, Python