diff --git a/molecular_qm_models/__init__.py b/molecular_qm_models/__init__.py index ecf5513..2c38a3c 100644 --- a/molecular_qm_models/__init__.py +++ b/molecular_qm_models/__init__.py @@ -1,4 +1,5 @@ from .molecule import Atom, Molecule, MoleculeList +from .annotated_molecule import AnnotatedMolecule, BondAnnotation, SphereAnnotation from .molecule_snapshot import MoleculeSnapshot, geometry_hash_from_molecule from .qm_input import QMInput, QMMethod, SCFAccuracy, OptimizationAccuracy, GridType from .qm_result import QMResult, QMThermoResult @@ -20,6 +21,9 @@ "Atom", "Molecule", "MoleculeList", + "AnnotatedMolecule", + "SphereAnnotation", + "BondAnnotation", "MoleculeSnapshot", "geometry_hash_from_molecule", "QMInput", diff --git a/molecular_qm_models/annotated_molecule.py b/molecular_qm_models/annotated_molecule.py new file mode 100644 index 0000000..7e8b527 --- /dev/null +++ b/molecular_qm_models/annotated_molecule.py @@ -0,0 +1,81 @@ +import math +from typing import List + +from odmantic import EmbeddedModel, Field, Model, Reference +from pydantic import model_validator + +from molecular_qm_models.molecule import Molecule +from simstack.models import simstack_model +from simstack.util.generate_ui_schema import generate_ui_schema + + +@simstack_model +class SphereAnnotation(EmbeddedModel): + """A colored sphere drawn at one coordinate on an annotated molecule.""" + + field_name: str = "SphereAnnotation" + coordinate: List[float] + radius: float + color: str + transparency: float + + @model_validator(mode="after") + def validate_sphere(self): + if len(self.coordinate) != 3 or any(not math.isfinite(value) for value in self.coordinate): + raise ValueError("coordinate must be three finite numbers") + if not math.isfinite(self.radius) or self.radius <= 0: + raise ValueError("radius must be a positive finite number") + if not self.color.strip(): + raise ValueError("color is required") + if not math.isfinite(self.transparency) or self.transparency < 0 or self.transparency > 1: + raise ValueError("transparency must be a finite number between 0 and 1") + return self + + +@simstack_model +class BondAnnotation(EmbeddedModel): + """A colored line drawn between two coordinates on an annotated molecule.""" + + field_name: str = "BondAnnotation" + points: List[List[float]] + color: str + thickness: float + transparency: float + + @model_validator(mode="after") + def validate_bond(self): + if len(self.points) != 2: + raise ValueError("points must contain exactly two coordinates") + for point in self.points: + if len(point) != 3 or any(not math.isfinite(value) for value in point): + raise ValueError("each point must be three finite numbers") + if not self.color.strip(): + raise ValueError("color is required") + if not math.isfinite(self.thickness) or self.thickness <= 0: + raise ValueError("thickness must be a positive finite number") + if not math.isfinite(self.transparency) or self.transparency < 0 or self.transparency > 1: + raise ValueError("transparency must be a finite number between 0 and 1") + return self + + +@simstack_model +class AnnotatedMolecule(Model): + """A molecule reference plus the spheres and bonds drawn on top of it.""" + + field_name: str = "AnnotatedMolecule" + molecule: Molecule = Reference() + sphere_annotations: List[SphereAnnotation] = Field(default_factory=list) + bond_annotations: List[BondAnnotation] = Field(default_factory=list) + + @model_validator(mode="before") + @classmethod + def ensure_fieldname(cls, data): + if isinstance(data, dict) and "field_name" not in data: + data["field_name"] = cls.__name__ + return data + + @classmethod + def ui_schema(cls): + ui_schema = generate_ui_schema(cls) + ui_schema["ui:field"] = "AnnotatedMoleculeField" + return ui_schema diff --git a/tests/molecule/test_annotated_molecule.py b/tests/molecule/test_annotated_molecule.py new file mode 100644 index 0000000..1255a6e --- /dev/null +++ b/tests/molecule/test_annotated_molecule.py @@ -0,0 +1,101 @@ +"""Tests for AnnotatedMolecule sphere and bond annotations.""" + +import pytest + +from molecular_qm_models import AnnotatedMolecule, BondAnnotation, Molecule, SphereAnnotation + + +def test_annotated_molecule_stores_sphere_and_bond_annotations(water): + annotated = AnnotatedMolecule( + molecule=water, + sphere_annotations=[ + SphereAnnotation(coordinate=[1.0, 0.0, 0.0], radius=0.4, color="#ff0000", transparency=0.25) + ], + bond_annotations=[ + BondAnnotation( + points=[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]], + color="blue", + thickness=0.15, + transparency=0.0, + ) + ], + ) + + assert annotated.molecule is water + assert annotated.sphere_annotations[0].coordinate == [1.0, 0.0, 0.0] + assert annotated.bond_annotations[0].points[1] == [1.0, 0.0, 0.0] + assert annotated.ui_schema()["ui:field"] == "AnnotatedMoleculeField" + + +def test_annotation_lists_default_to_empty(water): + annotated = AnnotatedMolecule(molecule=water) + assert annotated.sphere_annotations == [] + assert annotated.bond_annotations == [] + + +def test_molecule_reference_is_required(): + with pytest.raises(ValueError): + AnnotatedMolecule() + + +def test_null_annotation_lists_are_rejected(water): + with pytest.raises(ValueError): + AnnotatedMolecule(molecule=water, sphere_annotations=None) + with pytest.raises(ValueError): + AnnotatedMolecule(molecule=water, bond_annotations=None) + + +@pytest.mark.parametrize( + "kwargs", + [ + {"coordinate": [1.0, 2.0], "radius": 1.0, "color": "red", "transparency": 0.0}, + {"coordinate": [1.0, 2.0, float("nan")], "radius": 1.0, "color": "red", "transparency": 0.0}, + {"coordinate": [0.0, 0.0, 0.0], "radius": 0.0, "color": "red", "transparency": 0.0}, + {"coordinate": [0.0, 0.0, 0.0], "radius": 1.0, "color": " ", "transparency": 0.0}, + {"coordinate": [0.0, 0.0, 0.0], "radius": 1.0, "color": "red", "transparency": 1.5}, + ], +) +def test_sphere_annotation_rejects_uncontrolled_values(kwargs): + with pytest.raises(ValueError): + SphereAnnotation(**kwargs) + + +@pytest.mark.parametrize( + "kwargs", + [ + {"points": [[0.0, 0.0, 0.0]], "color": "red", "thickness": 0.1, "transparency": 0.0}, + { + "points": [[0.0, 0.0, 0.0], [1.0, 0.0]], + "color": "red", + "thickness": 0.1, + "transparency": 0.0, + }, + { + "points": [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]], + "color": "red", + "thickness": -0.2, + "transparency": 0.0, + }, + { + "points": [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]], + "color": "", + "thickness": 0.2, + "transparency": 0.5, + }, + ], +) +def test_bond_annotation_rejects_uncontrolled_values(kwargs): + with pytest.raises(ValueError): + BondAnnotation(**kwargs) + + +def test_annotated_molecule_accepts_a_molecule_built_from_sites(): + molecule = Molecule.from_sites(["C"], [[0.0, 0.0, 0.0]]) + annotated = AnnotatedMolecule( + molecule=molecule, + sphere_annotations=[ + SphereAnnotation(coordinate=[0.0, 0.0, 1.0], radius=0.8, color="green", transparency=1.0) + ], + ) + assert len(annotated.molecule.atoms) == 1 + assert annotated.sphere_annotations[0].transparency == 1.0