Repository: Materials-Consortia/optimade-python-tools (python)

Issue:
Hill notation wrong (still)
Actual definition:
- If carbon is present, place it first, then hydrogen if present.
- Following hydrogen, sort elements alphabetically.
- If carbon is _not_ present, sort elements alphabetically, also if hydrogen is present.

Example of valid Hill notation formulas:
- C H<sub>4</sub> Cl O
- Cl H<sub>4</sub> O
- C Cl O

Incorrect Hill notation:
- H<sub>4</sub> Cl O

(See, e.g., the [wikipedia entry](https://en.wikipedia.org/wiki/Chemical_formula#Hill_system) for Hill notation.)

Pull request description:
Check for carbon in elements for Hill
Fixes #585.

If carbon is not present, the elements should be sorted alphabetically (including hydrogen).

This changes a test to the corrected definition of Hill notation.

Patch:
diff --git a/optimade/models/structures.py b/optimade/models/structures.py
index e1aebb19..82ad7f1c 100644
--- a/optimade/models/structures.py
+++ b/optimade/models/structures.py
@@ -774,11 +774,12 @@ The properties of the species are found in the property `species`.
         expected_elements = sorted(elements)
 
         if field.name == "chemical_formula_hill":
-            # Make sure C is first and H is second.
-            for elem in ("H", "C"):
-                if elem in expected_elements:
-                    expected_elements.pop(expected_elements.index(elem))
-                    expected_elements.insert(0, elem)
+            # Make sure C is first (and H is second, if present along with C).
+            if "C" in expected_elements:
+                expected_elements = sorted(
+                    expected_elements,
+                    key=lambda elem: {"C": "0", "H": "1"}.get(elem, elem),
+                )
 
         if any(elem not in CHEMICAL_SYMBOLS for elem in elements):
             raise ValueError(


Test patch:
diff --git a/tests/models/test_structures.py b/tests/models/test_structures.py
index 1a6b8b56..2828c608 100644
--- a/tests/models/test_structures.py
+++ b/tests/models/test_structures.py
@@ -80,8 +80,8 @@ deformities = (
         "Elements in 'chemical_formula_hill' must appear in Hill order: ['Ge', 'Si'] not ['Si', 'Ge']",
     ),
     (
-        {"chemical_formula_hill": "GeHSi"},
-        "Elements in 'chemical_formula_hill' must appear in Hill order: ['H', 'Ge', 'Si'] not ['Ge', 'H', 'Si']",
+        {"chemical_formula_hill": "HGeSi"},
+        "Elements in 'chemical_formula_hill' must appear in Hill order: ['Ge', 'H', 'Si'] not ['H', 'Ge', 'Si']",
     ),
     (
         {"chemical_formula_hill": "CGeHSi"},