diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 19ee807..71e95ba 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "0.19.0" + ".": "0.20.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 7122f93..06fd357 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## 0.20.0 (2026-12-01) + + +### Features + +* **models:** sample structure ensembles with gibbs + ## 0.19.0 (2026-12-01) diff --git a/openprotein/models/__init__.py b/openprotein/models/__init__.py index c149885..873b98a 100644 --- a/openprotein/models/__init__.py +++ b/openprotein/models/__init__.py @@ -13,6 +13,8 @@ BioEmuInput, ESMFlow, ESMFlowInput, + Gibbs, + GibbsInput, StructureEnsemblePredictionModel, ) from .estimators import GP, SVD, UMAP @@ -96,6 +98,8 @@ "ESMFold", "ESMFold2", "GPModel", + "Gibbs", + "GibbsInput", "LinearKernel", "Matern12Kernel", "Matern32Kernel", diff --git a/openprotein/models/ensemble/__init__.py b/openprotein/models/ensemble/__init__.py index 92bca34..90a5ee9 100644 --- a/openprotein/models/ensemble/__init__.py +++ b/openprotein/models/ensemble/__init__.py @@ -4,6 +4,7 @@ from .base import StructureEnsemblePredictionModel from .bioemu import BioEmu, BioEmuInput from .esmflow import ESMFlow, ESMFlowInput +from .gibbs import Gibbs, GibbsInput __all__ = [ "AlphaFlow", @@ -12,5 +13,7 @@ "BioEmuInput", "ESMFlow", "ESMFlowInput", + "Gibbs", + "GibbsInput", "StructureEnsemblePredictionModel", ] diff --git a/openprotein/models/ensemble/_inputs.py b/openprotein/models/ensemble/_inputs.py index e22c2a9..b54835a 100644 --- a/openprotein/models/ensemble/_inputs.py +++ b/openprotein/models/ensemble/_inputs.py @@ -4,7 +4,12 @@ from typing import Any, TypeVar from openprotein.fold.common import _msa_id_of +from openprotein.fold.future import FoldResultFuture +from openprotein.jobs.futures import StructurePredictionFuture from openprotein.molecules import Complex, Protein, Structure +from openprotein.utils.uuid import _as_id + +from .. import _inputs _T = TypeVar("_T") @@ -161,3 +166,30 @@ def flow_references( } for index, (reference, sequence) in enumerate(zip(references, sequences)) ] + + +def gibbs_structure(value: Any, field: str) -> str: + if _as_id(value) is not None: + raise ValueError(f"{field} takes structure text, not a job id") + if isinstance(value, (str, bytes)): + return _text(value, field) + complex = _reference_complex(value, field, single_chain=False) + return complex.to_string(format="cif") + + +def gibbs_reference(value: Any, field: str) -> dict[str, str]: + """``value`` as a ``job_id`` when it names a prediction, else ``structure_file``.""" + if isinstance(value, (StructurePredictionFuture, FoldResultFuture)): + return {"job_id": value.id} + if (job_id := _as_id(value)) is not None: + return {"job_id": job_id} + return {"structure_file": gibbs_structure(value, field)} + + +def prompt_id(value: Any, field: str) -> str: + if value is None: + raise ValueError(f"{field} is required") + _inputs._check_prompt(value, field) + resolved = _inputs.prompt_id(value) + assert resolved is not None + return resolved diff --git a/openprotein/models/ensemble/gibbs.py b/openprotein/models/ensemble/gibbs.py new file mode 100644 index 0000000..3a0285d --- /dev/null +++ b/openprotein/models/ensemble/gibbs.py @@ -0,0 +1,133 @@ +"""Gibbs.""" + +from collections.abc import Sequence +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any + +from openprotein.jobs import futures + +from . import _inputs +from .base import StructureEnsemblePredictionModel + +if TYPE_CHECKING: + from openprotein.data.prompts.prompts import Prompt as StoredPrompt + from openprotein.fold.future import FoldResultFuture + from openprotein.molecules import Complex, Protein, Structure + from openprotein.prompt import Prompt + +__all__ = ["Gibbs", "GibbsInput"] + + +@dataclass(frozen=True) +class GibbsInput: + """One Gibbs ensemble: a reference structure and the prompt it samples with. + + Attributes + ---------- + reference_structure : str, bytes, Protein, Complex, Structure, StructurePredictionFuture or FoldResultFuture + PDB or mmCIF text, a protein-only molecule, or a structure prediction + of one structure, given as its future or job id. A reference may hold + several protein chains. + prompt : str, Prompt or StoredPrompt + The PoET-2 prompt the ensemble is conditioned on, or its id. + constraint : str, bytes, Protein, Complex, Structure or None + Part of the reference held fixed while the rest is sampled. + temperature : int or None + Temperature in Kelvin for this ensemble. ``None`` uses the call's. + """ + + reference_structure: "str | bytes | Protein | Complex | Structure | futures.StructurePredictionFuture | FoldResultFuture" + prompt: "str | Prompt | StoredPrompt" + constraint: "str | bytes | Protein | Complex | Structure | None" = None + temperature: int | None = None + + +class Gibbs(StructureEnsemblePredictionModel): + """Gibbs samples protein ensembles around reference structures. + + Each ensemble starts from a reference and a PoET-2 prompt. A constraint + holds part of the reference fixed, and a temperature overrides the call's + for one ensemble. A reference may hold several protein chains. Its + checkpoint is ``gibbs``. + """ + + Input = GibbsInput + _default_id = "gibbs" + + def sample( + self, + inputs: Sequence[GibbsInput], + num_samples: int = 1, + temperature: int = 300, + random_seed: int | None = None, + ) -> futures.StructurePredictionFuture: + """Sample one ensemble per input. + + Parameters + ---------- + inputs : sequence of GibbsInput + One entry per ensemble. + num_samples : int + Conformations to sample per input. + temperature : int + Sampling temperature in Kelvin, for inputs that set none. + random_seed : int or None + Random seed. Gibbs samples are not reproducible from it. + + Returns + ------- + StructurePredictionFuture + One ensemble per input, in input order. + + Examples + -------- + A reference straight off a structure prediction, and a second one + sampled hotter: + + >>> prompt = msa.sample_prompt(num_sequences=16) + >>> predicted = session.models.esmfold.fold(sequence) + >>> gibbs = session.models.gibbs + >>> future = gibbs.sample( + ... [ + ... gibbs.Input(reference_structure=predicted, prompt=prompt), + ... gibbs.Input( + ... reference_structure=reference, prompt=prompt, temperature=350 + ... ), + ... ], + ... num_samples=10, + ... temperature=300, + ... ) + >>> ensembles = future.get() + + Part of the reference held fixed while the rest is sampled: + + >>> future = gibbs.sample( + ... [ + ... gibbs.Input( + ... reference_structure=reference, prompt=prompt, constraint=pocket + ... ) + ... ] + ... ) + """ + references = [] + for i, entry in enumerate(_inputs.input_list(inputs, GibbsInput)): + field = f"inputs[{i}]" + record: dict[str, Any] = { + **_inputs.gibbs_reference( + entry.reference_structure, f"{field}.reference_structure" + ), + "prompt_id": _inputs.prompt_id(entry.prompt, f"{field}.prompt"), + } + if entry.constraint is not None: + record["constraint"] = _inputs.gibbs_structure( + entry.constraint, f"{field}.constraint" + ) + if entry.temperature is not None: + record["temperature"] = entry.temperature + references.append(record) + return self._sample( + reference_structures=references, + num_samples=num_samples, + temperature=temperature, + random_seed=random_seed, + ) diff --git a/openprotein/models/models.py b/openprotein/models/models.py index b540d97..17576e7 100644 --- a/openprotein/models/models.py +++ b/openprotein/models/models.py @@ -8,7 +8,7 @@ from openprotein.errors import HTTPError from . import _api, estimators, gp, svd, umap -from .ensemble import AlphaFlow, BioEmu, ESMFlow +from .ensemble import AlphaFlow, BioEmu, ESMFlow, Gibbs from .fold import ( AlphaFold2, Boltz1, @@ -395,6 +395,11 @@ def esmflow_md_distilled_v1(self) -> ESMFlow: """``esmflow-md-distilled-v1``.""" return self._handle("esmflow-md-distilled-v1", ESMFlow) + @property + def gibbs(self) -> Gibbs: + """``gibbs``.""" + return self._handle("gibbs", Gibbs) + def list_models( self, verbose: bool = False, diff --git a/tests/data/ensemble_cards.json b/tests/data/ensemble_cards.json index d650a59..3258184 100644 --- a/tests/data/ensemble_cards.json +++ b/tests/data/ensemble_cards.json @@ -63,5 +63,19 @@ "variant": "distilled", "base": false, "max_sequence_length": 600 + }, + "gibbs": { + "input_types": [ + "protein" + ], + "multichain": true, + "tags": [ + "structure", + "ensemble", + "openprotein" + ], + "variant": null, + "base": true, + "max_sequence_length": 1500 } } diff --git a/tests/data/models_params.json b/tests/data/models_params.json index 87f5506..395a0cd 100644 --- a/tests/data/models_params.json +++ b/tests/data/models_params.json @@ -5896,6 +5896,121 @@ "type": "object" } }, + "gibbs/batch/structures": { + "outputs": [ + "structures" + ], + "params": { + "$defs": { + "GibbsReference": { + "additionalProperties": false, + "properties": { + "constraint": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "PDB or mmCIF text of the part of the reference held fixed while the rest is sampled." + }, + "job_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A structure prediction job of yours to take the reference from, which must predict one structure; give this or structure_file." + }, + "prompt_id": { + "description": "PoET-2 prompt the ensemble embedding is built from.", + "format": "uuid", + "type": "string" + }, + "structure_file": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Reference structure as PDB or mmCIF text; give this or job_id." + }, + "temperature": { + "anyOf": [ + { + "minimum": 1, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Temperature in Kelvin for this reference; null uses the request's temperature." + } + }, + "required": [ + "prompt_id" + ], + "type": "object" + } + }, + "additionalProperties": false, + "properties": { + "num_samples": { + "default": 1, + "description": "Conformations to sample per reference.", + "minimum": 1, + "type": "integer" + }, + "random_seed": { + "anyOf": [ + { + "maximum": 2147483647, + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Random seed. Not used yet by this model, so runs are not reproducible." + }, + "reference_structures": { + "description": "References to sample an ensemble of, one ensemble each.", + "items": { + "$ref": "#/$defs/GibbsReference" + }, + "minItems": 1, + "type": "array" + }, + "temperature": { + "default": 300, + "description": "Sampling temperature in Kelvin.", + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "reference_structures" + ], + "type": "object" + } + }, "gp/batch/predictions": { "outputs": [ "predictions" diff --git a/tests/e2e/models/test_structure_ensemble_e2e.py b/tests/e2e/models/test_structure_ensemble_e2e.py index ce01a24..c92aef4 100644 --- a/tests/e2e/models/test_structure_ensemble_e2e.py +++ b/tests/e2e/models/test_structure_ensemble_e2e.py @@ -126,3 +126,26 @@ def test_flow_samples_from_a_reference_structure( _assert_ensembles(structures, [BASE_SEQUENCE], NUM_SAMPLES) _assert_flow_outputs(future, BASE_SEQUENCE) + + +@pytest.mark.e2e +def test_gibbs_samples_one_ensemble_per_reference( + session: OpenProtein, + msa: MSAFuture, + reference: Protein, + reference_fold: StructurePredictionFuture, +): + prompt = msa.sample_prompt(num_sequences=16, random_seed=SEED) + prompt.wait_until_done(timeout=TIMEOUT) + gibbs = session.models.gibbs + future = gibbs.sample( + [ + gibbs.Input(reference, prompt=prompt), + gibbs.Input(reference_fold, prompt=prompt), + ], + num_samples=NUM_SAMPLES, + ) + + structures = future.wait(timeout=TIMEOUT) + + _assert_ensembles(structures, [BASE_SEQUENCE, BASE_SEQUENCE], NUM_SAMPLES) diff --git a/tests/models/test_ensemble_contracts.py b/tests/models/test_ensemble_contracts.py index 650f1b9..2563ad1 100644 --- a/tests/models/test_ensemble_contracts.py +++ b/tests/models/test_ensemble_contracts.py @@ -8,6 +8,7 @@ "alphaflow-md-distilled-v1", "esmflow-md-base-v1", "esmflow-md-distilled-v1", + "gibbs", ) FLOW_IDS = ENSEMBLE_IDS[1:5] @@ -17,7 +18,7 @@ def test_ensemble_cards_declare_structure_prediction(model_id): metadata = card(model_id) assert "ensemble" in metadata["tags"] assert metadata["input_types"] == ["protein"] - assert metadata["multichain"] is False + assert metadata["multichain"] is (model_id == "gibbs") method = PARAMS["methods"][f"{model_id}/batch/structures"] assert method["outputs"] == ( ["structures", "plddt", "confidence"] @@ -42,7 +43,7 @@ def test_ensemble_params_use_public_names(model_id): assert "num_samples" in properties assert "random_seed" in properties assert not {"steps", "seed", "batch_size", "batch_size_100"} & properties.keys() - assert "complexes" in properties + assert ("complexes" in properties) is (model_id != "gibbs") @pytest.mark.parametrize( @@ -70,6 +71,10 @@ def test_ensemble_params_use_public_names(model_id): ) for model_id in FLOW_IDS ], + ( + "gibbs", + {"num_samples": 1, "temperature": 300, "random_seed": None}, + ), ], ) def test_ensemble_defaults_match_the_card(model_id, expected): diff --git a/tests/models/test_ensemble_examples.py b/tests/models/test_ensemble_examples.py index ff1217f..1a8318e 100644 --- a/tests/models/test_ensemble_examples.py +++ b/tests/models/test_ensemble_examples.py @@ -6,13 +6,15 @@ from openprotein.align import MSAFuture from openprotein.jobs.futures import StructurePredictionFuture -from openprotein.models import AlphaFlow, BioEmu, ESMFlow, ModelsAPI +from openprotein.models import AlphaFlow, BioEmu, ESMFlow, Gibbs, ModelsAPI +from openprotein.prompt import Prompt MSA_ID = "3f1c2a7e-9b4d-4e2a-8c1f-0d5e6a7b8c9d" +PROMPT_ID = "5b2d8e4a-1c7f-4a3e-9d6b-2e8f0a1c3b5d" def _example(method) -> str: - """The method's doctest lines as one script.""" + """The method's doctest lines as one script, prompts stripped.""" lines = (inspect.getdoc(method) or "").splitlines() return "\n".join( line.strip()[4:] @@ -27,6 +29,7 @@ def _example(method) -> str: (BioEmu, ["bioemu-v1-1"] * 2), (AlphaFlow, ["alphaflow-md-base-v1", "alphaflow-md-distilled-v1"]), (ESMFlow, ["esmflow-md-base-v1", "esmflow-md-distilled-v1"]), + (Gibbs, ["esmfold", "gibbs", "gibbs"]), ], ) def test_sample_examples_submit_valid_requests( @@ -35,6 +38,9 @@ def test_sample_examples_submit_valid_requests( monkeypatch.setattr(StructurePredictionFuture, "get", lambda self, **kwargs: []) msa = MagicMock(spec=MSAFuture) msa.id = MSA_ID + prompt = MagicMock(spec=Prompt) + prompt.id = PROMPT_ID + msa.sample_prompt.return_value = prompt sequence = ensemble_reference.sequence.decode() namespace = { "session": SimpleNamespace(models=ModelsAPI(models_session.session)), @@ -42,6 +48,7 @@ def test_sample_examples_submit_valid_requests( "sequence": sequence, "sequences": [sequence, sequence[:40]], "reference": ensemble_reference, + "pocket": ensemble_reference[:10], } exec(compile(_example(handle.sample), handle.__name__, "exec"), namespace) # noqa: S102 assert [path for path, _ in models_session.submissions] == [ diff --git a/tests/models/test_ensemble_inputs.py b/tests/models/test_ensemble_inputs.py index b16cab6..2ae747f 100644 --- a/tests/models/test_ensemble_inputs.py +++ b/tests/models/test_ensemble_inputs.py @@ -1,13 +1,20 @@ import re from pathlib import Path +from unittest.mock import MagicMock import gemmi import numpy as np import pytest +from openprotein.data.prompts.prompts import Prompt as StoredPrompt +from openprotein.fold.future import FoldResultFuture +from openprotein.jobs.futures import StructurePredictionFuture from openprotein.models.ensemble import _inputs as _ensemble_inputs from openprotein.molecules import Complex, Protein, Structure +from openprotein.prompt import Prompt +PROMPT_ID = "5b2d8e4a-1c7f-4a3e-9d6b-2e8f0a1c3b5d" +JOB_ID = "7c1e9a2b-3d4f-4b6a-8e0c-1f2a3b4c5d6e" DATA = Path(__file__).parents[1] / "data" FIELD = "inputs[0].reference_structure" @@ -101,6 +108,19 @@ def test_reference_requires_coordinates(): _flow(Protein(sequence="MKT"), "MKT") +def test_gibbs_preserves_multichain_declared_sequences(ensemble_reference): + path = DATA / "boltzgen_entity_one_letter_missing_residues.cif" + gapped = Complex.from_filepath(path, verbose=False).get_proteins()["B"] + reference = Complex({"A": ensemble_reference, "B": gapped}) + parsed = Structure.from_string( + _ensemble_inputs.gibbs_structure(reference, FIELD), format="cif", verbose=False + )[0] + assert len(parsed.get_proteins()["B"]) == len(gapped) + assert parsed.get_proteins()["B"].get_structure_mask().sum() == ( + gapped.get_structure_mask().sum() + ) + + @pytest.mark.parametrize("filename", ["1A3N.cif", "1MSW.cif"]) def test_flow_rejects_present_nonprotein_chains(filename): reference = Structure.from_filepath(DATA / filename, verbose=False) @@ -108,6 +128,13 @@ def test_flow_rejects_present_nonprotein_chains(filename): _flow(reference, "MKT") +@pytest.mark.parametrize("filename", ["1A3N.cif", "1MSW.cif"]) +def test_gibbs_rejects_present_nonprotein_chains(filename): + reference = Structure.from_filepath(DATA / filename, verbose=False) + with pytest.raises(ValueError, match="non-protein"): + _ensemble_inputs.gibbs_structure(reference, FIELD) + + def test_flow_without_references_sends_none(): assert _ensemble_inputs.flow_references([None, None], ["MKT", "MKT"]) is None @@ -166,12 +193,69 @@ def test_a_protein_with_only_plddt_has_no_coordinates(): assert protein.has_structure with pytest.raises(ValueError, match="coordinates"): _flow(protein, "MKT") + with pytest.raises(ValueError, match="coordinates"): + _ensemble_inputs.gibbs_structure(protein, FIELD) def test_references_use_the_first_complex_of_a_structure(ensemble_reference): shorter = ensemble_reference[:50] structure = Structure([Complex({"A": ensemble_reference}), Complex({"A": shorter})]) assert _residues(_flow(structure, ensemble_reference)) == len(ensemble_reference) + parsed = Structure.from_string( + _ensemble_inputs.gibbs_structure(structure, FIELD), format="cif", verbose=False + ) + assert len(parsed[0].get_proteins()["A"]) == len(ensemble_reference) + + +@pytest.mark.parametrize("format", ["pdb", "cif"]) +def test_gibbs_sends_structure_text_unchanged(ensemble_reference, format): + text = Complex({"A": ensemble_reference}).to_string(format=format) + assert _ensemble_inputs.gibbs_reference(text, FIELD) == {"structure_file": text} + + +def test_gibbs_decodes_structure_bytes(ensemble_reference): + text = Complex({"A": ensemble_reference}).to_string(format="cif") + assert _ensemble_inputs.gibbs_structure(text.encode(), FIELD) == text + + +def test_gibbs_rejects_empty_structure_text(): + with pytest.raises(ValueError, match=r"reference_structure is empty"): + _ensemble_inputs.gibbs_reference(" ", FIELD) + + +def test_gibbs_rejects_nonprotein_constraints(): + constraint = Structure.from_filepath(DATA / "1A3N.cif", verbose=False) + with pytest.raises(ValueError, match=r"constraint contains non-protein"): + _ensemble_inputs.gibbs_structure(constraint, "inputs[0].constraint") + + +def test_gibbs_job_id_text_names_a_prediction(): + assert _ensemble_inputs.gibbs_reference(JOB_ID, FIELD) == {"job_id": JOB_ID} + + +@pytest.mark.parametrize("future_type", [StructurePredictionFuture, FoldResultFuture]) +def test_gibbs_prediction_future_names_its_job_without_reading_it(future_type): + future = MagicMock(spec=future_type) + future.id = JOB_ID + assert _ensemble_inputs.gibbs_reference(future, FIELD) == {"job_id": JOB_ID} + assert future.method_calls == [] + + +def test_gibbs_rejects_other_references(): + with pytest.raises(TypeError, match="must be structure text"): + _ensemble_inputs.gibbs_reference(MagicMock(spec=StoredPrompt), FIELD) + + +@pytest.mark.parametrize("prompt_type", [Prompt, StoredPrompt]) +def test_gibbs_prompt_objects_become_their_id(prompt_type): + prompt = MagicMock(spec=prompt_type) + prompt.id = PROMPT_ID + assert _ensemble_inputs.prompt_id(prompt, "inputs[0].prompt") == PROMPT_ID + + +def test_gibbs_rejects_unsupported_prompts(): + with pytest.raises(TypeError, match=r"inputs\[0\]\.prompt must be a Prompt"): + _ensemble_inputs.prompt_id(42, "inputs[0].prompt") def test_references_leave_caller_molecules_unchanged(ensemble_reference): @@ -179,6 +263,18 @@ def test_references_leave_caller_molecules_unchanged(ensemble_reference): coordinates = ensemble_reference.coordinates.copy() _flow(ensemble_reference, ensemble_reference) + _ensemble_inputs.gibbs_structure(ensemble_reference, FIELD) assert ensemble_reference.to_string(format="pdb") == pdb np.testing.assert_array_equal(ensemble_reference.coordinates, coordinates) + + +@pytest.mark.parametrize("value", [JOB_ID.upper(), JOB_ID.upper().encode()]) +def test_gibbs_job_id_in_any_case_or_bytes_is_sent_lower_cased(value): + assert _ensemble_inputs.gibbs_reference(value, FIELD) == {"job_id": JOB_ID} + + +@pytest.mark.parametrize("value", [JOB_ID, JOB_ID.upper(), JOB_ID.encode()]) +def test_gibbs_constraint_takes_structure_text_not_a_job_id(value): + with pytest.raises(ValueError, match="structure text, not a job id"): + _ensemble_inputs.gibbs_structure(value, "inputs[0].constraint") diff --git a/tests/models/test_ensemble_models.py b/tests/models/test_ensemble_models.py index 995f203..d8292c2 100644 --- a/tests/models/test_ensemble_models.py +++ b/tests/models/test_ensemble_models.py @@ -14,11 +14,14 @@ BioEmuInput, ESMFlow, ESMFlowInput, + Gibbs, + GibbsInput, ModelsAPI, StructureEnsemblePredictionModel, StructurePredictionModel, ) from openprotein.molecules import Protein +from openprotein.prompt import Prompt HANDLES = { "bioemu-v1-1": BioEmu, @@ -26,10 +29,13 @@ "alphaflow-md-distilled-v1": AlphaFlow, "esmflow-md-base-v1": ESMFlow, "esmflow-md-distilled-v1": ESMFlow, + "gibbs": Gibbs, } IDS = tuple(HANDLES) FLOW_IDS = IDS[1:5] MSA_ID = "3f1c2a7e-9b4d-4e2a-8c1f-0d5e6a7b8c9d" +PROMPT_ID = "5b2d8e4a-1c7f-4a3e-9d6b-2e8f0a1c3b5d" +JOB_ID = "7c1e9a2b-3d4f-4b6a-8e0c-1f2a3b4c5d6e" CARD_DEFAULTS = { BioEmu: { @@ -54,6 +60,7 @@ "self_cond": None, "random_seed": None, }, + Gibbs: {"num_samples": 1, "temperature": 300, "random_seed": None}, } @@ -66,7 +73,9 @@ def _input(model_id: str, sequence: str = "MKT", reference: Any = None) -> Any: return BioEmuInput(sequence, msa=MSA_ID) if model_id.startswith("alphaflow-"): return AlphaFlowInput(sequence, msa=MSA_ID, reference_structure=reference) - return ESMFlowInput(sequence, reference_structure=reference) + if model_id.startswith("esmflow-"): + return ESMFlowInput(sequence, reference_structure=reference) + return GibbsInput(JOB_ID, prompt=PROMPT_ID) @pytest.mark.parametrize("model_id", IDS) @@ -89,6 +98,7 @@ def test_ensemble_handles_are_not_structure_prediction_handles(handle): (BioEmu, BioEmuInput), (AlphaFlow, AlphaFlowInput), (ESMFlow, ESMFlowInput), + (Gibbs, GibbsInput), ], ) def test_each_handle_names_its_input_type(handle, input_type): @@ -226,6 +236,41 @@ def test_flow_references_are_given_for_every_input_or_none( models_session.session.post.assert_not_called() +def test_gibbs_sends_one_reference_record_per_input(models_session, ensemble_reference): + prompt = MagicMock(spec=Prompt) + prompt.id = PROMPT_ID + future = ModelsAPI(models_session.session).gibbs.sample( + [ + GibbsInput( + ensemble_reference, + prompt=PROMPT_ID, + constraint=ensemble_reference, + temperature=310, + ), + GibbsInput(JOB_ID, prompt=prompt), + ], + num_samples=2, + temperature=300, + ) + assert type(future) is StructurePredictionFuture + path, body = models_session.submitted + assert path == "v1/models/gibbs/batch/structures" + assert not {"complexes", "templates", "sequences"} & body.keys() + first, second = body["reference_structures"] + assert first.keys() == {"structure_file", "prompt_id", "constraint", "temperature"} + assert first["temperature"] == 310 + assert second == {"job_id": JOB_ID, "prompt_id": PROMPT_ID} + assert body["temperature"] == 300 + + +def test_gibbs_requires_a_prompt(models_session): + with pytest.raises(ValueError, match=r"inputs\[0\]\.prompt is required"): + ModelsAPI(models_session.session).gibbs.sample( + [GibbsInput(JOB_ID, prompt=None)] # ty: ignore[invalid-argument-type] + ) + models_session.session.post.assert_not_called() + + @pytest.mark.parametrize("seed", [0, 7]) def test_explicit_seed_value_is_sent(models_session, seed): ModelsAPI(models_session.session).bioemu_v1_1.sample( @@ -248,6 +293,7 @@ def test_a_none_seed_is_not_sent(models_session): ("alphaflow-md-base-v1", "num_steps", 101), ("esmflow-md-base-v1", "tmax", 0), ("esmflow-md-distilled-v1", "num_samples", 251), + ("gibbs", "temperature", 0), ], ) def test_out_of_range_controls_fail_the_card_schema( diff --git a/tests/models/test_ensemble_results.py b/tests/models/test_ensemble_results.py index 0f573fa..2984fa1 100644 --- a/tests/models/test_ensemble_results.py +++ b/tests/models/test_ensemble_results.py @@ -12,6 +12,7 @@ AlphaFlowInput, BioEmuInput, ESMFlowInput, + GibbsInput, ModelsAPI, ) from openprotein.molecules import Complex, Protein, Structure @@ -23,6 +24,7 @@ "alphaflow-md-distilled-v1", "esmflow-md-base-v1", "esmflow-md-distilled-v1", + "gibbs", ) MSA_ID = "3f1c2a7e-9b4d-4e2a-8c1f-0d5e6a7b8c9d" PROMPT_ID = "5b2d8e4a-1c7f-4a3e-9d6b-2e8f0a1c3b5d" @@ -57,6 +59,9 @@ def _shifts(value: object, reference: Protein) -> list[float]: def _submit(models, model_id, reference): handle = models.get_model(model_id) + if model_id == "gibbs": + entry = GibbsInput(reference, prompt=PROMPT_ID) + return handle.sample([entry, entry], num_samples=2) sequence = reference.sequence if model_id == "bioemu-v1-1": entry = BioEmuInput(sequence, msa=MSA_ID) @@ -96,7 +101,7 @@ def test_ensemble_results_preserve_positions_and_conformations( else job_type ), "model_id": model_id, - "args": {"random_seed": 7}, + "args": {} if model_id == "gibbs" else {"random_seed": 7}, } route = f"v1/models/{model_id}/batch/structures" models_session.post_routes[route] = payload diff --git a/tests/models/test_static_accessors.py b/tests/models/test_static_accessors.py index 4d96ae1..13d4e62 100644 --- a/tests/models/test_static_accessors.py +++ b/tests/models/test_static_accessors.py @@ -21,6 +21,7 @@ ESMFlow, ESMFold, ESMFold2, + Gibbs, GPModel, MiniFold, Model, @@ -81,6 +82,7 @@ "alphaflow-md-distilled-v1": AlphaFlow, "esmflow-md-base-v1": ESMFlow, "esmflow-md-distilled-v1": ESMFlow, + "gibbs": Gibbs, } MODEL_ACCESSORS = [ @@ -128,6 +130,7 @@ ("alphaflow_md_distilled_v1", "alphaflow-md-distilled-v1"), ("esmflow_md_base_v1", "esmflow-md-base-v1"), ("esmflow_md_distilled_v1", "esmflow-md-distilled-v1"), + ("gibbs", "gibbs"), ] @@ -199,7 +202,7 @@ def test_a_listed_id_without_an_accessor_is_a_plain_model(models_session): assert (type(handle), handle.id) == (Model, "other-model") -@pytest.mark.parametrize("model_id", ["not-a-model", "esm2"]) +@pytest.mark.parametrize("model_id", ["not-a-model", "esm2", "gibbs"]) def test_get_model_refuses_an_unlisted_id(mock_session, model_id): _not_found(mock_session) diff --git a/tests/models/test_typecheck_coverage.py b/tests/models/test_typecheck_coverage.py index 5d17c4f..75e6275 100644 --- a/tests/models/test_typecheck_coverage.py +++ b/tests/models/test_typecheck_coverage.py @@ -35,6 +35,7 @@ ("AlphaFlow", "sample"): "StructurePredictionFuture", ("BioEmu", "sample"): "StructurePredictionFuture", ("ESMFlow", "sample"): "StructurePredictionFuture", + ("Gibbs", "sample"): "StructurePredictionFuture", ("_ChainedLanguageModel", "embed"): "EmbeddingFuture", ("_ChainedLanguageModel", "logits"): "LogitsFuture", ("_ChainedLanguageModel", "attn"): "AttentionFuture", diff --git a/tests/models/typecheck_ensemble_models.py b/tests/models/typecheck_ensemble_models.py index ef3150a..d2de6a5 100644 --- a/tests/models/typecheck_ensemble_models.py +++ b/tests/models/typecheck_ensemble_models.py @@ -13,6 +13,8 @@ ESMFlow, ESMFlowInput, ESMFold, + Gibbs, + GibbsInput, ModelsAPI, StructureGenerativeModel, ) @@ -30,19 +32,29 @@ def accessor_types(models: ModelsAPI) -> None: assert_type(models.alphaflow_md_distilled_v1, AlphaFlow) assert_type(models.esmflow_md_base_v1, ESMFlow) assert_type(models.esmflow_md_distilled_v1, ESMFlow) + assert_type(models.gibbs, Gibbs) -def input_types(bioemu: BioEmu, alphaflow: AlphaFlow, esmflow: ESMFlow) -> None: +def input_types( + bioemu: BioEmu, alphaflow: AlphaFlow, esmflow: ESMFlow, gibbs: Gibbs +) -> None: assert_type(bioemu.Input, type[BioEmuInput]) assert_type(alphaflow.Input, type[AlphaFlowInput]) assert_type(esmflow.Input, type[ESMFlowInput]) + assert_type(gibbs.Input, type[GibbsInput]) -def prediction_types(esmflow: ESMFlow, reference: Protein) -> None: +def prediction_types(esmflow: ESMFlow, gibbs: Gibbs, reference: Protein) -> None: assert_type( esmflow.sample([ESMFlowInput("MKT", reference_structure=reference)]), StructurePredictionFuture, ) + assert_type( + gibbs.sample( + [GibbsInput(reference, prompt="5b2d8e4a-1c7f-4a3e-9d6b-2e8f0a1c3b5d")] + ), + StructurePredictionFuture, + ) assert_type(esmflow.sample([ESMFlowInput("MKT")]).get(), list[Structure]) diff --git a/tests/models/typecheck_task_futures.py b/tests/models/typecheck_task_futures.py index 3692016..50ec356 100644 --- a/tests/models/typecheck_task_futures.py +++ b/tests/models/typecheck_task_futures.py @@ -41,6 +41,7 @@ ESMFlow, ESMFold, ESMFold2, + Gibbs, GPModel, MiniFold, Model, @@ -222,6 +223,7 @@ def structure_model_types( bioemu: BioEmu, alphaflow: AlphaFlow, esmflow: ESMFlow, + gibbs: Gibbs, generative: StructureGenerativeModel, ) -> None: assert_type( @@ -232,6 +234,10 @@ def structure_model_types( StructurePredictionFuture, ) assert_type(esmflow.sample([esmflow.Input("MKT")]), StructurePredictionFuture) + assert_type( + gibbs.sample([gibbs.Input("reference", prompt="prompt-id")]), + StructurePredictionFuture, + ) assert_type(generative.generate(), StructureDesignFuture)