From 72ccdd44093b8f6947533b27e494ee52d6e6e4c3 Mon Sep 17 00:00:00 2001 From: "openprotein-bot[bot]" Date: Tue, 1 Dec 2026 09:57:57 +0000 Subject: [PATCH] Release v0.19.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 31 + openprotein/_deprecation.py | 114 + openprotein/base.py | 67 +- openprotein/data/assaydataset.py | 30 + openprotein/data/prompts/_api.py | 2 +- openprotein/data/prompts/schemas.py | 4 +- openprotein/embeddings/api.py | 47 +- openprotein/embeddings/poet.py | 35 +- openprotein/embeddings/poet2.py | 35 +- openprotein/jobs/_api.py | 13 +- openprotein/jobs/_storage.py | 108 +- openprotein/jobs/futures.py | 31 +- openprotein/jobs/jobs.py | 48 +- openprotein/models/__init__.py | 23 +- openprotein/models/fold/__init__.py | 29 + openprotein/models/fold/alphafold2.py | 56 + openprotein/models/{folding => fold}/base.py | 9 +- openprotein/models/fold/boltz1.py | 79 + openprotein/models/fold/boltz1x.py | 76 + openprotein/models/fold/boltz2.py | 113 + openprotein/models/fold/esmfold.py | 40 + openprotein/models/fold/esmfold2.py | 66 + openprotein/models/fold/minifold.py | 40 + openprotein/models/fold/opendde.py | 66 + openprotein/models/fold/protenix.py | 71 + openprotein/models/fold/protenix_v2.py | 72 + openprotein/models/fold/rosettafold3.py | 66 + openprotein/models/folding/__init__.py | 37 +- openprotein/models/folding/alphafold2.py | 14 - openprotein/models/folding/boltz1.py | 15 - openprotein/models/folding/boltz2.py | 15 - openprotein/models/folding/esmfold.py | 14 - openprotein/models/folding/esmfold2.py | 15 - openprotein/models/folding/minifold.py | 14 - openprotein/models/folding/opendde.py | 15 - openprotein/models/folding/protenix.py | 14 - openprotein/models/folding/protenix_v2.py | 15 - openprotein/models/folding/rosettafold3.py | 15 - openprotein/models/foundation/__init__.py | 29 + openprotein/models/foundation/_chains.py | 120 + .../_inverse_folding.py | 0 .../{foundational => foundation}/ablang2.py | 0 .../{foundational => foundation}/base.py | 24 +- .../{foundational => foundation}/esm1.py | 0 .../{foundational => foundation}/esm2.py | 0 .../{foundational => foundation}/esmc.py | 0 openprotein/models/foundation/esmif1.py | 65 + .../{foundational => foundation}/poet.py | 138 +- openprotein/models/foundation/poet2.py | 438 ++ openprotein/models/foundation/proteinmpnn.py | 312 + .../{foundational => foundation}/protseq.py | 4 +- .../{foundational => foundation}/prott5.py | 0 .../{foundational => foundation}/rotaprot.py | 4 +- openprotein/models/foundational/__init__.py | 39 +- openprotein/models/foundational/esmif1.py | 15 - openprotein/models/foundational/poet2.py | 212 - .../models/foundational/proteinmpnn.py | 44 - openprotein/models/generative/boltzgen.py | 54 + openprotein/models/generative/rfdiffusion.py | 36 + openprotein/models/model.py | 6 +- openprotein/models/models.py | 13 +- openprotein/molecules/structure.py | 276 +- pyproject.toml | 2 + scripts/refresh_model_params.py | 36 + tests/data/models_params.json | 5149 +++++++++-------- tests/data/test_assay_resource.py | 104 +- tests/data/test_prompt_resource.py | 4 +- tests/data/test_prompts_api.py | 8 +- tests/data/test_prompts_sample.py | 2 +- tests/e2e/models/test_estimators_e2e.py | 2 +- tests/embeddings/test_embeddings_api.py | 59 + tests/embeddings/test_embeddings_models.py | 59 + tests/jobs/test_job_outputs.py | 303 +- tests/jobs/test_model_result_contracts.py | 12 +- tests/jobs/test_results_by_codec.py | 50 +- tests/models/conftest.py | 11 +- tests/models/support.py | 13 +- tests/models/test_deprecated_names.py | 181 +- tests/models/test_ensemble_models.py | 14 +- tests/models/test_estimators.py | 39 +- tests/models/test_future_results.py | 16 +- tests/models/test_future_unit.py | 173 +- tests/models/test_handles.py | 110 +- tests/models/test_input_checks.py | 1 + tests/models/test_model_taxonomy.py | 12 +- tests/models/test_models_api.py | 11 +- tests/models/test_param_signatures.py | 173 + tests/models/test_parity.py | 131 +- tests/models/test_public_names.py | 6 +- tests/models/test_static_accessors.py | 3 +- .../models/test_structure_prediction_model.py | 9 +- tests/models/test_typecheck_coverage.py | 21 +- tests/models/typecheck_task_futures.py | 62 + tests/molecules/test_structure.py | 201 + tests/molecules/test_structure_xtc.py | 173 + tests/test_auth.py | 169 +- tests/test_submission_transport.py | 9 +- 98 files changed, 7257 insertions(+), 3456 deletions(-) create mode 100644 openprotein/models/fold/__init__.py create mode 100644 openprotein/models/fold/alphafold2.py rename openprotein/models/{folding => fold}/base.py (96%) create mode 100644 openprotein/models/fold/boltz1.py create mode 100644 openprotein/models/fold/boltz1x.py create mode 100644 openprotein/models/fold/boltz2.py create mode 100644 openprotein/models/fold/esmfold.py create mode 100644 openprotein/models/fold/esmfold2.py create mode 100644 openprotein/models/fold/minifold.py create mode 100644 openprotein/models/fold/opendde.py create mode 100644 openprotein/models/fold/protenix.py create mode 100644 openprotein/models/fold/protenix_v2.py create mode 100644 openprotein/models/fold/rosettafold3.py delete mode 100644 openprotein/models/folding/alphafold2.py delete mode 100644 openprotein/models/folding/boltz1.py delete mode 100644 openprotein/models/folding/boltz2.py delete mode 100644 openprotein/models/folding/esmfold.py delete mode 100644 openprotein/models/folding/esmfold2.py delete mode 100644 openprotein/models/folding/minifold.py delete mode 100644 openprotein/models/folding/opendde.py delete mode 100644 openprotein/models/folding/protenix.py delete mode 100644 openprotein/models/folding/protenix_v2.py delete mode 100644 openprotein/models/folding/rosettafold3.py create mode 100644 openprotein/models/foundation/__init__.py create mode 100644 openprotein/models/foundation/_chains.py rename openprotein/models/{foundational => foundation}/_inverse_folding.py (100%) rename openprotein/models/{foundational => foundation}/ablang2.py (100%) rename openprotein/models/{foundational => foundation}/base.py (81%) rename openprotein/models/{foundational => foundation}/esm1.py (100%) rename openprotein/models/{foundational => foundation}/esm2.py (100%) rename openprotein/models/{foundational => foundation}/esmc.py (100%) create mode 100644 openprotein/models/foundation/esmif1.py rename openprotein/models/{foundational => foundation}/poet.py (58%) create mode 100644 openprotein/models/foundation/poet2.py create mode 100644 openprotein/models/foundation/proteinmpnn.py rename openprotein/models/{foundational => foundation}/protseq.py (79%) rename openprotein/models/{foundational => foundation}/prott5.py (100%) rename openprotein/models/{foundational => foundation}/rotaprot.py (79%) delete mode 100644 openprotein/models/foundational/esmif1.py delete mode 100644 openprotein/models/foundational/poet2.py delete mode 100644 openprotein/models/foundational/proteinmpnn.py create mode 100644 scripts/refresh_model_params.py create mode 100644 tests/models/test_param_signatures.py create mode 100644 tests/molecules/test_structure_xtc.py diff --git a/.release-please-manifest.json b/.release-please-manifest.json index e58457c..19ee807 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "0.18.2" + ".": "0.19.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index f2f23f5..7122f93 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,36 @@ # Changelog +## 0.19.0 (2026-12-01) + + +### ⚠ BREAKING CHANGES + +* **jobs:** FutureUnit.get raises JobOutputsNotReady for a unit that isn't finished, where it raised HTTPError 404. catch JobOutputsNotReady or APIError. +* **models:** `embed` on `session.models` handles returns one row per residue unless a reduction is given; v0.18.0 pooled by mean. Pass `reduction="MEAN"` for pooled embeddings, which a GP or UMAP fit needs. + +### Features + +* **jobs:** read results and prompts through authenticated content routes +* **models:** name every model's inference params on its handle +* **models:** embed per residue unless a reduction is given +* **molecules:** structure ensemble analysis + + +### Deprecations + +* `openprotein.models.folding`: use `openprotein.models.fold`. Deprecated since 0.19.0, removed in 0.20.0 +* `openprotein.models.foundational`: use `openprotein.models.foundation`. Deprecated since 0.19.0, removed in 0.20.0 +* `topk=` and `topp=` on `PoETModel.generate`, `PoET2Model.generate` and `request_generate_post`: use `top_k=` and `top_p=`. Deprecated since 0.19.0, removed in 0.20.0 + +### Bug Fixes + +* **base:** keep the backend path when it has no trailing slash +* **data:** refuse to read the rows of an assay that isn't ready +* **embeddings:** name poet generate sampling args top_k and top_p +* **embeddings:** send top_k and top_p in poet generate requests +* **jobs:** say why a unit's output can't be read +* **models:** leave the fit_svd reduction to the server unless given + ## 0.18.2 (2026-11-24) diff --git a/openprotein/_deprecation.py b/openprotein/_deprecation.py index a06dc99..934e667 100644 --- a/openprotein/_deprecation.py +++ b/openprotein/_deprecation.py @@ -1,6 +1,12 @@ """Helper for deprecating public interfaces.""" +import importlib +import pkgutil +import sys import warnings +from collections.abc import Callable +from types import ModuleType +from typing import Any def warn_deprecated( @@ -36,3 +42,111 @@ def warn_deprecated( FutureWarning, stacklevel=stacklevel, ) + + +def alias_package( + old: str, new: ModuleType, *, since: str, removed_in: str +) -> Callable[[str], Any]: + """ + Alias a package under a deprecated name. + + Warns once when the old package is imported, then registers every + submodule of `new` in `sys.modules` under the old name, so the old + submodule paths resolve to the same module objects. Call it from the body + of the old package's ``__init__``. + + Parameters + ---------- + old : str + Dotted name of the deprecated package. + new : ModuleType + The package that replaces it. + since : str + Version the old name was deprecated in. + removed_in : str + Version the old name is removed in. + + Returns + ------- + Callable[[str], Any] + A module ``__getattr__`` for the old package. It warns and returns the + object for each name in ``new.__all__`` and each submodule of `new`, + and raises `AttributeError` for any other name. + """ + warn_deprecated( + old, + f"`{new.__name__}`", + since=since, + removed_in=removed_in, + stacklevel=4, + ) + submodules = {module.name for module in pkgutil.iter_modules(new.__path__)} + for name in submodules: + sys.modules[f"{old}.{name}"] = importlib.import_module(f"{new.__name__}.{name}") + + def __getattr__(name: str) -> Any: + if name not in new.__all__ and name not in submodules: + raise AttributeError(f"module {old!r} has no attribute {name!r}") + warn_deprecated( + f"{old}.{name}", + f"`{new.__name__}.{name}`", + since=since, + removed_in=removed_in, + ) + return getattr(new, name) + + return __getattr__ + + +def renamed_keyword( + kwargs: dict[str, Any], + method: str, + old: str, + new: str, + value: Any, + *, + since: str, + removed_in: str, +) -> Any: + """ + Resolve a keyword argument that was renamed, warning if the old name is used. + + Call it from the public method so the warning points at that method's caller. + + Parameters + ---------- + kwargs : dict + The method's ``**kwargs``. The old keyword is removed from it. + method : str + Name of the method, for the warning. + old, new : str + The deprecated and current keyword names. + value : Any + The value passed under the current name. + since : str + Version the old name was deprecated in. + removed_in : str + Version the old name is removed in. + + Returns + ------- + Any + The value to use under the current name. + + Raises + ------ + TypeError + If both names are given. + """ + if old not in kwargs: + return value + warn_deprecated( + f"{method}({old}=...)", + f"`{method}({new}=...)`", + since=since, + removed_in=removed_in, + stacklevel=4, + ) + if value is not None: + raise TypeError(f"pass {new}, not both {new} and {old}") + return kwargs.pop(old) diff --git a/openprotein/base.py b/openprotein/base.py index 9402613..b0a2436 100644 --- a/openprotein/base.py +++ b/openprotein/base.py @@ -71,6 +71,9 @@ def is_retry(self, method, status_code, has_retry_after=False): # Refresh the access token this many seconds before it expires, to absorb # clock skew and request latency. _SKEW_SECONDS = 30 + +#: Stored-byte reads run at once; also the connection pool size per host. +_DOWNLOAD_WORKERS = 16 _IDEMPOTENCY_KEY_HEADER = "Idempotency-Key" @@ -185,6 +188,10 @@ def __init__( raise AuthError( "Expected username and password. Or use environment variables `OPENPROTEIN_USERNAME` and `OPENPROTEIN_PASSWORD`. Or provide these variables (`username` and `password`) in ~/.openprotein/config.toml." ) + # urljoin replaces the last path segment of a base without a trailing + # slash, so `.../api` would route every call outside `/api`. + if not backend.endswith("/"): + backend += "/" self._init_transport(backend, timeout) # Auth / refresh state. Initialised before any network call so that @@ -219,7 +226,7 @@ def _init_transport(self, backend: str, timeout: float) -> None: status_forcelist=[500, 502, 503, 504, 101, 104], raise_on_status=False, ) - adapter = HTTPAdapter(max_retries=retry) + adapter = HTTPAdapter(max_retries=retry, pool_maxsize=_DOWNLOAD_WORKERS) for scheme in ("https://", "http://"): self.mount(scheme, adapter) model_retry = _ModelSubmissionRetry( @@ -384,9 +391,17 @@ def _adopt(self, record: TokenRecord): self._expires_at = record.expires_at self._set_token(self._username, record.access_token) - def _refresh(self): + def _bearer_token(self) -> str | None: + return self.auth._token if isinstance(self.auth, BearerAuth) else None + + def _refresh(self, stale: str | None = None): """Refresh the access token, serialized across threads and processes. + ``stale`` is the access token the caller found expired or rejected. If + the session now holds a different token, another thread has refreshed. + No token at all means another thread's re-login failed, so this one + tries again. + Re-reads the store under the lock first: if another thread/process already rotated the token, adopt that instead of refreshing again (replaying a superseded refresh token would revoke the session). @@ -396,6 +411,9 @@ def _refresh(self): self._token_store.lock(), _surface_server_warnings(), ): + current = self._bearer_token() + if stale is not None and current is not None and current != stale: + return record = self._token_store.load(self._identity) if ( record is not None @@ -446,8 +464,10 @@ def _should_refresh_proactively(self) -> bool: def request(self, method: str, url: str, *args, **kwargs): kwargs.setdefault("timeout", self.timeout) + token = self._bearer_token() if self._should_refresh_proactively(): - self._refresh() + self._refresh(token) + token = self._bearer_token() # Freeze the JSON body once so a reactive 401 retry resends the same # payload under the same idempotency key. @@ -464,27 +484,34 @@ def request(self, method: str, url: str, *args, **kwargs): and not self._refreshing and not self._legacy_mode ): - self._refresh() + response.close() + self._refresh(token) response = super().request(method, full_url, *args, **kwargs) - _warn_from_server(response) - - if (js := kwargs.get("json")) and _total_size(js) > 1e6: - warnings.warn( - "The requested payload is >1MB. There might be some delays or issues in processing. If the request fails, please try again with smaller sizes." - ) + # A streamed response holds its connection until closed, and the caller + # only gets to close the one returned. + try: + _warn_from_server(response) - if "cloudfront" in response.headers.get("Server", "").lower(): - if response.status_code in (502, 503): - raise CloudFrontError( - f"We're experiencing a temporary backend issue via CloudFront. Please try again later. Error {response.status_code}." - ) - elif response.status_code == 504: - raise TimeoutError( - "Your request took too long to process likely due to it's size. Please try breaking it up into smaller requests if possible." + if (js := kwargs.get("json")) and _total_size(js) > 1e6: + warnings.warn( + "The requested payload is >1MB. There might be some delays or issues in processing. If the request fails, please try again with smaller sizes." ) - if not response.ok: - raise HTTPError(response) + + if "cloudfront" in response.headers.get("Server", "").lower(): + if response.status_code in (502, 503): + raise CloudFrontError( + f"We're experiencing a temporary backend issue via CloudFront. Please try again later. Error {response.status_code}." + ) + elif response.status_code == 504: + raise TimeoutError( + "Your request took too long to process likely due to it's size. Please try breaking it up into smaller requests if possible." + ) + if not response.ok: + raise HTTPError(response) + except BaseException: + response.close() + raise return response diff --git a/openprotein/data/assaydataset.py b/openprotein/data/assaydataset.py index a1d2fb3..651a7f2 100644 --- a/openprotein/data/assaydataset.py +++ b/openprotein/data/assaydataset.py @@ -213,10 +213,22 @@ def _get_all(self, verbose: bool = False) -> pd.DataFrame: """ Get all assay data. + A page after the first that fails to load ends the read, which + returns the rows read before it. + Returns ------- pd.DataFrame Dataframe containing all assay data. + + Raises + ------ + JobOutputsNotReady + If the assay isn't ready yet. + JobFailedException + If the job that makes the assay failed or was canceled. + APIError + If the first page fails to load. """ step = self.page_size @@ -231,6 +243,8 @@ def _get_all(self, verbose: bool = False) -> pd.DataFrame: num_returned = len(result) offset += num_returned except APIError as exc: + if not results: + raise if verbose: print(f"Failed to get results: {exc}") return pd.concat(results) @@ -244,7 +258,15 @@ def get_first(self) -> pd.DataFrame: ------- pd.DataFrame Dataframe containing the slice of assay data. + + Raises + ------ + JobOutputsNotReady + If the assay isn't ready yet. + JobFailedException + If the job that makes the assay failed or was canceled. """ + self._require_ready() rows = [] entries = api.assaydata_page_get( self.session, self.id, page_offset=0, page_size=1 @@ -274,7 +296,15 @@ def get_slice( ------- pd.DataFrame Dataframe containing the slice of assay data. + + Raises + ------ + JobOutputsNotReady + If the assay isn't ready yet. + JobFailedException + If the job that makes the assay failed or was canceled. """ + self._require_ready() rows = [] page_size = self.page_size for i in range(start, end, page_size): diff --git a/openprotein/data/prompts/_api.py b/openprotein/data/prompts/_api.py index 45e9536..2d43b47 100644 --- a/openprotein/data/prompts/_api.py +++ b/openprotein/data/prompts/_api.py @@ -94,7 +94,7 @@ def prompts_download(session: APISession, prompt_id: str) -> bytes: A prompt that isn't ready raises the server's 409; a deleted or unknown id is a 404. """ - return read(session, f"{PATH_PREFIX}/{prompt_id}/download").content + return read(session, f"{PATH_PREFIX}/{prompt_id}/content").content def prompts_sample_post( diff --git a/openprotein/data/prompts/schemas.py b/openprotein/data/prompts/schemas.py index f847b5c..8ae591c 100644 --- a/openprotein/data/prompts/schemas.py +++ b/openprotein/data/prompts/schemas.py @@ -33,14 +33,14 @@ class PromptMetadata(BaseModel): class PromptUnitValue(BaseModel): - """One replicate's presigned value.""" + """One replicate's stored value.""" position: int value: dict[str, Any] class PromptRecord(PromptMetadata): - """One row read in full, carrying each replicate's presigned value. + """One row read in full, carrying each replicate's stored value. ``value`` is ``None`` until the row's job has produced the replicates. """ diff --git a/openprotein/embeddings/api.py b/openprotein/embeddings/api.py index 72a33de..04d4dd7 100644 --- a/openprotein/embeddings/api.py +++ b/openprotein/embeddings/api.py @@ -9,7 +9,7 @@ import numpy as np from pydantic import TypeAdapter -from openprotein import csv +from openprotein import _deprecation, csv from openprotein.base import APISession from openprotein.common import ModelMetadata from openprotein.errors import InvalidParameterError @@ -576,8 +576,8 @@ def request_generate_post( model_id: str, num_samples: int = 100, temperature: float = 1.0, - topk: float | None = None, - topp: float | None = None, + top_k: float | None = None, + top_p: float | None = None, max_length: int = 1000, random_seed: int | None = None, **kwargs, @@ -587,12 +587,19 @@ def request_generate_post( Returns a Job object referring to this request \ that can be used to retrieve results later. + .. deprecated:: 0.19.0 + ``topk=`` and ``topp=`` are removed in 0.20.0; pass ``top_k`` and ``top_p``. + Parameters ---------- session : APISession Session object for API communication. model_id : str model ID to request results from + top_k : float or None, optional + Number of top-k residues to consider during sampling. + top_p : float or None, optional + Cumulative probability threshold for top-p sampling. **kwargs: Optional parameters for models, e.g. prompt_id for PoET @@ -600,14 +607,32 @@ def request_generate_post( ------- job : Job """ + top_k = _deprecation.renamed_keyword( + kwargs, + "request_generate_post", + "topk", + "top_k", + top_k, + since="0.19.0", + removed_in="0.20.0", + ) + top_p = _deprecation.renamed_keyword( + kwargs, + "request_generate_post", + "topp", + "top_p", + top_p, + since="0.19.0", + removed_in="0.20.0", + ) endpoint = _PATH_PREFIX + f"/models/{model_id}/generate" if not (0.1 <= temperature <= 2): raise InvalidParameterError("The 'temperature' must be between 0.1 and 2.") - if topk is not None and not (2 <= topk <= 20): - raise InvalidParameterError("The 'topk' must be between 2 and 20.") - if topp is not None and not (0 <= topp <= 1): - raise InvalidParameterError("The 'topp' must be between 0 and 1.") + if top_k is not None and not (2 <= top_k <= 20): + raise InvalidParameterError("The 'top_k' must be between 2 and 20.") + if top_p is not None and not (0 <= top_p <= 1): + raise InvalidParameterError("The 'top_p' must be between 0 and 1.") if random_seed is not None and not (0 <= random_seed <= 2**32): raise InvalidParameterError("The 'random_seed' must be between 0 and 2^32.") @@ -619,10 +644,10 @@ def request_generate_post( "temperature": temperature, "maxlen": max_length, } - if topk is not None: - body["topk"] = topk - if topp is not None: - body["topp"] = topp + if top_k is not None: + body["top_k"] = top_k + if top_p is not None: + body["top_p"] = top_p if random_seed is not None: body["seed"] = random_seed if kwargs.get("prompt_id"): diff --git a/openprotein/embeddings/poet.py b/openprotein/embeddings/poet.py index ab8bb79..452206c 100644 --- a/openprotein/embeddings/poet.py +++ b/openprotein/embeddings/poet.py @@ -2,6 +2,7 @@ from typing import TYPE_CHECKING +from openprotein import _deprecation from openprotein.base import APISession from openprotein.common import ModelMetadata, Reduction, ReductionType from openprotein.data import AssayDataset, AssayMetadata @@ -279,8 +280,8 @@ def generate( prompt: str | Prompt | StoredPrompt, num_samples: int = 100, temperature: float = 1.0, - topk: float | None = None, - topp: float | None = None, + top_k: float | None = None, + top_p: float | None = None, max_length: int = 1000, seed: int | None = None, **kwargs, @@ -288,6 +289,10 @@ def generate( """ Generate protein sequences conditioned on a prompt. + .. deprecated:: 0.19.0 + ``topk=`` and ``topp=`` are removed in 0.20.0; pass ``top_k`` and + ``top_p``. + Parameters ---------- prompt : str or Prompt @@ -296,9 +301,9 @@ def generate( Number of samples to generate. Default is 100. temperature : float, optional Temperature for sampling. Higher values produce more random outputs. Default is 1.0. - topk : float or None, optional + top_k : float or None, optional Number of top-k residues to consider during sampling. Default is None. - topp : float or None, optional + top_p : float or None, optional Cumulative probability threshold for top-p sampling. Default is None. max_length : int, optional Maximum length of generated proteins. Default is 1000. @@ -312,6 +317,24 @@ def generate( EmbeddingsGenerateFuture Future object representing the status and information about the generation job. """ + top_k = _deprecation.renamed_keyword( + kwargs, + "PoETModel.generate", + "topk", + "top_k", + top_k, + since="0.19.0", + removed_in="0.20.0", + ) + top_p = _deprecation.renamed_keyword( + kwargs, + "PoETModel.generate", + "topp", + "top_p", + top_p, + since="0.19.0", + removed_in="0.20.0", + ) if prompt is not None: kwargs["prompt_id"] = prompt if isinstance(prompt, str) else prompt.id else: @@ -324,8 +347,8 @@ def generate( model_id=self.id, num_samples=num_samples, temperature=temperature, - topk=topk, - topp=topp, + top_k=top_k, + top_p=top_p, max_length=max_length, random_seed=seed, **kwargs, diff --git a/openprotein/embeddings/poet2.py b/openprotein/embeddings/poet2.py index 6c1bdac..5ad65cb 100644 --- a/openprotein/embeddings/poet2.py +++ b/openprotein/embeddings/poet2.py @@ -5,6 +5,7 @@ import numpy as np +from openprotein import _deprecation from openprotein.base import APISession from openprotein.common import ModelMetadata, ReductionType from openprotein.data import AssayDataset, AssayMetadata @@ -335,8 +336,8 @@ def generate( use_query_structure_in_decoder: bool = True, num_samples: int = 100, temperature: float = 1.0, - topk: float | None = None, - topp: float | None = None, + top_k: float | None = None, + top_p: float | None = None, max_length: int = 1000, seed: int | None = None, ensemble_weights: Sequence[float] | None = None, @@ -346,6 +347,10 @@ def generate( """ Generate protein sequences conditioned on a prompt. + .. deprecated:: 0.19.0 + ``topk=`` and ``topp=`` are removed in 0.20.0; pass ``top_k`` and + ``top_p``. + Parameters ---------- prompt : str or Prompt or None, optional @@ -358,9 +363,9 @@ def generate( The number of samples to generate. Default is 100. temperature : float, optional The temperature for sampling. Higher values produce more random outputs. Default is 1.0. - topk : float or None, optional + top_k : float or None, optional The number of top-k residues to consider during sampling. Default is None. - topp : float or None, optional + top_p : float or None, optional The cumulative probability threshold for top-p sampling. Default is None. max_length : int, optional The maximum length of generated proteins. Default is 1000. @@ -386,6 +391,24 @@ def generate( """ from openprotein.models.structure_generation import StructureGenerationFuture + top_k = _deprecation.renamed_keyword( + kwargs, + "PoET2Model.generate", + "topk", + "top_k", + top_k, + since="0.19.0", + removed_in="0.20.0", + ) + top_p = _deprecation.renamed_keyword( + kwargs, + "PoET2Model.generate", + "topp", + "top_p", + top_p, + since="0.19.0", + removed_in="0.20.0", + ) prompt_api = getattr(self.session, "prompt", None) assert isinstance(prompt_api, PromptAPI) query_id = prompt_api._resolve_query(query=query) if query is not None else None @@ -408,8 +431,8 @@ def generate( prompt=prompt, # type: ignore num_samples=num_samples, temperature=temperature, - topk=topk, - topp=topp, + top_k=top_k, + top_p=top_p, max_length=max_length, seed=seed, query_id=query_id, diff --git a/openprotein/jobs/_api.py b/openprotein/jobs/_api.py index abed6fe..8e910b8 100644 --- a/openprotein/jobs/_api.py +++ b/openprotein/jobs/_api.py @@ -106,7 +106,18 @@ def job_output_get( session: APISession, job_id: str, output_name: str, position: int ) -> dict[str, Any]: """Resolve an authorized logical output handle to metadata, never bytes.""" - response = session.get(f"v1/data/results/{job_id}/{output_name}/{position}") + try: + response = session.get(f"v1/data/results/{job_id}/{output_name}/{position}") + except HTTPError as exc: + if exc.status_code != 409: + raise + try: + detail = exc.response.json()["detail"] + except (ValueError, KeyError, TypeError): + detail = None + if not isinstance(detail, str) or not detail: + detail = f"unit {position} of job {job_id} is not complete yet" + raise JobOutputsNotReady(detail) from exc return dict(response.json()) diff --git a/openprotein/jobs/_storage.py b/openprotein/jobs/_storage.py index 8caf9fa..7a78d1f 100644 --- a/openprotein/jobs/_storage.py +++ b/openprotein/jobs/_storage.py @@ -1,108 +1,48 @@ -"""Direct artifact reads; platform authentication is never sent to object storage.""" +"""Stored-byte reads through the platform session, verified against their refs.""" from __future__ import annotations import hashlib -import importlib -import os import re import tempfile from collections.abc import Iterator, Mapping from contextlib import contextmanager from typing import Any, BinaryIO, Protocol -from urllib.parse import urlsplit -import requests -from requests.adapters import HTTPAdapter -from urllib3.util.retry import Retry +from openprotein.base import APISession -#: Artifact downloads `JobsAPI._iter_job_outputs` runs at once. -DOWNLOAD_WORKERS = 16 - - -def _download_session() -> requests.Session: - """A pooled session for signed URLs that retries object-storage 5xx.""" - retry = Retry( - total=4, - backoff_factor=0.5, - status_forcelist=(500, 502, 503, 504), - allowed_methods=frozenset({"GET"}), - raise_on_status=False, - ) - adapter = HTTPAdapter(pool_maxsize=DOWNLOAD_WORKERS, max_retries=retry) - session = requests.Session() - for prefix in ("https://", "http://"): - session.mount(prefix, adapter) - return session +__all__ = [ + "ArtifactStorage", + "ContentStorage", + "verified_artifact", +] class ArtifactStorage(Protocol): - """Injectable backend boundary for authorized stored-value references.""" + """Injectable source of the bytes a stored-value reference names.""" def iter_bytes(self, reference: Mapping[str, Any]) -> Iterator[bytes]: ... -class DirectArtifactStorage: - """Download authorized signed URLs or S3 references with ambient credentials. +class ContentStorage: + """Stream a stored value's bytes from an API ``/content`` route. - HTTP downloads use a separate requests session, never the platform's bearer - token or user headers. + The request goes through the platform session, with its bearer + authentication and token refresh. """ def __init__( - self, - s3_client: Any = None, - *, - chunk_size: int = 1024 * 1024, - http: requests.Session | None = None, + self, session: APISession, path: str, *, chunk_size: int = 1024 * 1024 ): if chunk_size <= 0: raise ValueError("chunk_size must be positive") - self.s3_client = s3_client + self.session = session + self.path = path self.chunk_size = chunk_size - self.http = http if http is not None else _download_session() def iter_bytes(self, reference: Mapping[str, Any]) -> Iterator[bytes]: - download_url = reference.get("download_url") - if download_url is not None: - if not isinstance(download_url, str) or urlsplit( - download_url - ).scheme not in ("https", "http"): - raise ValueError("invalid artifact download URL") - with self.http.get(download_url, stream=True, timeout=180) as response: - response.raise_for_status() - yield from response.iter_content(chunk_size=self.chunk_size) - return - uri = reference.get("uri") - if not isinstance(uri, str): - raise TypeError("artifact reference requires a uri") - parsed = urlsplit(uri) - if ( - parsed.scheme != "s3" - or not parsed.netloc - or not parsed.path.lstrip("/") - or parsed.query - or parsed.fragment - ): - raise ValueError("invalid S3 artifact URI") - if self.s3_client is None: - try: - boto3 = importlib.import_module("boto3") - except ImportError as exc: - raise RuntimeError("S3 reads require boto3") from exc - self.s3_client = boto3.client( - "s3", - endpoint_url=os.environ.get("AWS_ENDPOINT_URL_S3") - or os.environ.get("S3_ENDPOINT_URL"), - ) - body = self.s3_client.get_object( - Bucket=parsed.netloc, Key=parsed.path.lstrip("/") - )["Body"] - try: - while chunk := body.read(self.chunk_size): - yield chunk - finally: - body.close() + with self.session.get(self.path, stream=True) as response: + yield from response.iter_content(chunk_size=self.chunk_size) @contextmanager @@ -111,8 +51,8 @@ def verified_artifact( ) -> Iterator[BinaryIO]: """Spool without a total-size ceiling and verify the entire content digest. - Only a fixed-size transfer buffer is kept in memory. Storage checksums and - multipart ETags deliberately do not substitute for full-content SHA-256. + Only a fixed-size transfer buffer is kept in memory. Response headers such + as Content-Length or ETag do not substitute for the full-content SHA-256. """ size, digest = reference.get("byte_length"), reference.get("sha256") if type(size) is not int or size < 0: @@ -138,13 +78,3 @@ def verified_artifact( ) spool.seek(0) yield spool - - -def download_ref(value: Mapping[str, Any]) -> bytes: - """Fetch and verify raw bytes for a stored ``{ref: Ref}`` value.""" - reference = value.get("ref") - if not isinstance(reference, Mapping): - raise ValueError("expected a ref-backed value") - storage = DirectArtifactStorage() - with verified_artifact(storage, reference) as source: - return source.read() diff --git a/openprotein/jobs/futures.py b/openprotein/jobs/futures.py index b0d8995..b8be1de 100644 --- a/openprotein/jobs/futures.py +++ b/openprotein/jobs/futures.py @@ -39,6 +39,7 @@ APIError, HTTPError, JobFailedException, + JobOutputsNotReady, TimeoutException, ) from openprotein.jobs.schemas import Job, JobStatus, _UnitRecord @@ -448,7 +449,13 @@ def _convert_output(self, output: str, position: int, value: Any) -> Any: return value def get_item(self, position: int, output: str | None = None) -> Any: - """Read one submitted position of ``output``, default the method's own.""" + """Read one submitted position of ``output``, default the method's own. + + Raises + ------ + JobOutputsNotReady + If the server answers that the position's unit has not succeeded. + """ self._require_outputs() name = self._output_name(output) entry = _jobs_api_for(self.session)._get_job_output(self.job_id, position, name) @@ -1287,23 +1294,37 @@ def _raise_if_unsuccessful(self) -> None: def get(self) -> V: """Fetch and decode this unit's selected output. + If the output is missing or not ready, refresh the unit record. + Raises ------ JobFailedException - If the unit failed or was canceled, as the snapshot reports or as a - refresh after a missing output shows. + If the snapshot or refresh reports that the unit failed or was + canceled. + JobOutputsNotReady + If the refresh reports an unfinished unit. If the output read + raises this error and the refresh reports success or fails, + the original error is raised. + HTTPError + If the read fails otherwise, such as a missing output of a unit + that succeeded. """ self._raise_if_unsuccessful() try: return self._future.get_item(self._position, output=self.output) - except HTTPError as error: - if error.status_code != 404: + except (HTTPError, JobOutputsNotReady) as error: + if isinstance(error, HTTPError) and error.status_code != 404: raise try: self.refresh() except Exception as refresh_error: raise error from refresh_error self._raise_if_unsuccessful() + status = self.status + if status is not JobStatus.SUCCESS: + raise JobOutputsNotReady( + f"unit {self._position} of job {self.job_id} is {status.value}" + ) from error raise def wait( diff --git a/openprotein/jobs/jobs.py b/openprotein/jobs/jobs.py index cce3670..31947ff 100644 --- a/openprotein/jobs/jobs.py +++ b/openprotein/jobs/jobs.py @@ -10,7 +10,7 @@ from datetime import datetime from typing import Any -from openprotein import config +from openprotein import base, config from openprotein.base import APISession from openprotein.errors import JobFailedException @@ -35,7 +35,6 @@ class JobsAPI: def __init__(self, session: APISession): self.session = session - self._storage = _storage.DirectArtifactStorage() # Qualify `list` because the method name shadows the builtin in annotations. def list( @@ -92,26 +91,27 @@ def _iter_job_outputs( follow: bool = False, interval: float = config.POLLING_INTERVAL, ) -> Iterator[_JobOutput]: - """Stream decoded outputs in submission order, retaining duplicate positions. + """Stream decoded outputs in submission order. - HTTP resolves authorized metadata; the storage adapter downloads and - verifies artifact bytes directly, a few downloads at a time and at most - twice that many ahead of the caller. ``output_name=None`` reads the - method's default output. + A ref's bytes are read from the API's content route, verified against + the ref, a few reads at a time and at most twice that many ahead of the + caller. ``output_name=None`` reads the method's default output. An emitted output grows while its job runs. The stream ends at the items registered now, or with ``follow`` reads again every ``interval`` seconds until the output is complete. """ - pool = ThreadPoolExecutor(max_workers=_storage.DOWNLOAD_WORKERS) + pool = ThreadPoolExecutor(max_workers=base._DOWNLOAD_WORKERS) pending: deque[Pending[_JobOutput]] = deque() try: - for values in self._iter_output_pages( + for name, values in self._iter_output_pages( job_id, output_name, follow, interval ): for entry in values: - pending.append(pool.submit(self._decode_job_output, job_id, entry)) - if len(pending) >= 2 * _storage.DOWNLOAD_WORKERS: + pending.append( + pool.submit(self._decode_job_output, job_id, name, entry) + ) + if len(pending) >= 2 * base._DOWNLOAD_WORKERS: yield pending.popleft().result() if not values: while pending: @@ -127,15 +127,18 @@ def _iter_output_pages( output_name: str | None, follow: bool, interval: float, - ) -> Iterator[list[dict[str, Any]]]: - """Each page's entries. An empty page that keeps the cursor is caught up.""" + ) -> Iterator[tuple[str | None, list[dict[str, Any]]]]: + """Each page's output name and entries. + + An empty page that keeps the cursor is caught up. + """ cursor: str | None = None while True: page = _api.job_output_page( self.session, job_id, output_name, cursor=cursor ) values = page.get("values", []) - yield values + yield output_name or page.get("output"), values next_cursor = page.get("next_cursor") if not next_cursor: return @@ -145,7 +148,9 @@ def _iter_output_pages( time.sleep(interval) cursor = next_cursor - def _decode_job_output(self, job_id: str, entry: dict[str, Any]) -> _JobOutput: + def _decode_job_output( + self, job_id: str, output_name: str | None, entry: dict[str, Any] + ) -> _JobOutput: position = entry["position"] if type(position) is not int or position < 0: raise ValueError("output position must be a nonnegative integer") @@ -153,10 +158,17 @@ def _decode_job_output(self, job_id: str, entry: dict[str, Any]) -> _JobOutput: raise JobFailedException( job_id, f"output at position {position} failed: {entry['error']}" ) + value = entry.get("value") + if isinstance(value, dict) and "ref" in value and not output_name: + raise ValueError(f"results of job {job_id} do not name their output") + storage = _storage.ContentStorage( + self.session, + f"v1/data/results/{job_id}/{output_name}/{position}/content", + ) return _JobOutput( position=position, unit_id=str(entry["unit_id"]), - value=_decode.decode_value(entry.get("value"), self._storage), + value=_decode.decode_value(value, storage), ) def _get_job_output( @@ -164,7 +176,9 @@ def _get_job_output( ) -> _JobOutput: """Read the stable public (job, position, output) handle.""" return self._decode_job_output( - job_id, _api.job_output_get(self.session, job_id, output_name, position) + job_id, + output_name, + _api.job_output_get(self.session, job_id, output_name, position), ) def _iter_job_units(self, job_id: str) -> Iterator[_UnitRecord]: diff --git a/openprotein/models/__init__.py b/openprotein/models/__init__.py index 0d3dcca..c149885 100644 --- a/openprotein/models/__init__.py +++ b/openprotein/models/__init__.py @@ -1,6 +1,7 @@ """Make the ModelsAPI class available on the package.""" import importlib +import warnings from typing import Any from openprotein import _deprecation @@ -15,9 +16,10 @@ StructureEnsemblePredictionModel, ) from .estimators import GP, SVD, UMAP -from .folding import ( +from .fold import ( AlphaFold2, Boltz1, + Boltz1x, Boltz2, ESMFold, ESMFold2, @@ -28,7 +30,7 @@ RosettaFold3, StructurePredictionModel, ) -from .foundational import ( +from .foundation import ( ESM1, ESM2, ESMC, @@ -85,6 +87,7 @@ "BioEmu", "BioEmuInput", "Boltz1", + "Boltz1x", "Boltz2", "BoltzGen", "BoltzGenFuture", @@ -159,7 +162,21 @@ } +_ALIAS_PACKAGES = {"folding": "fold", "foundational": "foundation"} + + def __getattr__(name: str) -> Any: + if name in _ALIAS_PACKAGES: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", FutureWarning) + module = importlib.import_module(f"{__name__}.{name}") + _deprecation.warn_deprecated( + f"{__name__}.{name}", + f"`{__name__}.{_ALIAS_PACKAGES[name]}`", + since="0.19.0", + removed_in="0.20.0", + ) + return module if name == "SolubleMPNNModel": _deprecation.warn_deprecated( "openprotein.models.SolubleMPNNModel", @@ -167,7 +184,7 @@ def __getattr__(name: str) -> Any: since="0.18.0", removed_in="0.19.0", ) - from .foundational.proteinmpnn import _SolubleMPNN + from .foundation.proteinmpnn import _SolubleMPNN return _SolubleMPNN if name in _RENAMED: diff --git a/openprotein/models/fold/__init__.py b/openprotein/models/fold/__init__.py new file mode 100644 index 0000000..11b83ac --- /dev/null +++ b/openprotein/models/fold/__init__.py @@ -0,0 +1,29 @@ +"""Structure prediction models.""" + +from .alphafold2 import AlphaFold2 +from .base import StructurePredictionModel +from .boltz1 import Boltz1 +from .boltz1x import Boltz1x +from .boltz2 import Boltz2 +from .esmfold import ESMFold +from .esmfold2 import ESMFold2 +from .minifold import MiniFold +from .opendde import OpenDDE +from .protenix import Protenix +from .protenix_v2 import ProtenixV2 +from .rosettafold3 import RosettaFold3 + +__all__ = [ + "AlphaFold2", + "Boltz1", + "Boltz1x", + "Boltz2", + "ESMFold", + "ESMFold2", + "MiniFold", + "OpenDDE", + "Protenix", + "ProtenixV2", + "RosettaFold3", + "StructurePredictionModel", +] diff --git a/openprotein/models/fold/alphafold2.py b/openprotein/models/fold/alphafold2.py new file mode 100644 index 0000000..ec053a0 --- /dev/null +++ b/openprotein/models/fold/alphafold2.py @@ -0,0 +1,56 @@ +"""AlphaFold2.""" + +from typing import Any + +from openprotein.jobs import futures + +from .base import StructurePredictionModel + +__all__ = ["AlphaFold2"] + + +class AlphaFold2(StructurePredictionModel): + """AlphaFold2, which predicts proteins and protein complexes from an MSA. + + Its checkpoint is ``alphafold2``. + """ + + _default_id = "alphafold2" + + def fold( + self, + complexes: Any, + *, + num_models: int = 1, + num_recycles: int | None = None, + num_relax: int = 0, + **params: Any, + ) -> futures.StructurePredictionFuture: + """Predict structures of complexes (``batch/structures``). + + Parameters + ---------- + complexes : str, bytes, Protein, Complex, list of these, or MSAFuture + Complexes to fold, one structure set per list entry. + num_models : int + AlphaFold2 models to run, from 1 to 5. + num_recycles : int or None + Recycles, from 0 to 48. ``None`` lets the model decide. + num_relax : int + Relaxation steps, from 0 to 5. + **params + Other params of the model's ``batch/structures`` method, sent as + given. + + Returns + ------- + StructurePredictionFuture + One structure set per complex, in input order. + """ + return super().fold( + complexes, + num_models=num_models, + num_recycles=num_recycles, + num_relax=num_relax, + **params, + ) diff --git a/openprotein/models/folding/base.py b/openprotein/models/fold/base.py similarity index 96% rename from openprotein/models/folding/base.py rename to openprotein/models/fold/base.py index 1dfe5d4..517f776 100644 --- a/openprotein/models/folding/base.py +++ b/openprotein/models/fold/base.py @@ -2,7 +2,6 @@ import copy import warnings -from collections.abc import Sequence from typing import Any from openprotein.align import MSAFuture @@ -93,13 +92,9 @@ class StructurePredictionModel(Model): are sent where the model's params take them. """ - def fold( - self, - complexes: Any, - templates: Sequence[Protein | Complex | Any] | None = None, - **params: Any, - ) -> futures.StructurePredictionFuture: + def fold(self, complexes: Any, **params: Any) -> futures.StructurePredictionFuture: """Predict structures of complexes (``batch/structures``).""" + templates = params.pop("templates", None) if not _is_serialized(complexes) and not isinstance(complexes, MSAFuture): entities = ( complexes if isinstance(complexes, (list, tuple)) else [complexes] diff --git a/openprotein/models/fold/boltz1.py b/openprotein/models/fold/boltz1.py new file mode 100644 index 0000000..93bdcc0 --- /dev/null +++ b/openprotein/models/fold/boltz1.py @@ -0,0 +1,79 @@ +"""Boltz-1.""" + +from collections.abc import Mapping, Sequence +from typing import Any + +from openprotein.jobs import futures + +from .base import StructurePredictionModel + +__all__ = ["Boltz1"] + + +class Boltz1(StructurePredictionModel): + """Boltz-1, an all-atom structure prediction model. + + It predicts protein, DNA, RNA and ligand complexes. Its checkpoint is ``boltz-1``. + """ + + _default_id = "boltz-1" + + def fold( + self, + complexes: Any, + *, + num_samples: int = 1, + num_steps: int = 200, + num_recycles: int = 3, + step_scale: float = 1.638, + random_seed: int | None = None, + constraints: Sequence[Mapping[str, Any]] | None = None, + use_potentials: bool = False, + allow_msa_seed_mismatch: bool = False, + **params: Any, + ) -> futures.StructurePredictionFuture: + """Predict structures of complexes (``batch/structures``). + + Parameters + ---------- + complexes : str, bytes, Protein, Complex, list of these, or MSAFuture + Complexes to fold, one structure set per list entry. + num_samples : int + Structures to sample per complex, from 1 to 20. + num_steps : int + Diffusion sampling steps, at least 1. + num_recycles : int + Recycling steps, at least 1. + step_scale : float + Scaling factor for diffusion steps. + random_seed : int or None + Random seed, from 0 to 2**31 - 1. ``None`` draws a fresh one. + constraints : sequence of dict or None + Bond, pocket or contact constraints, such as + ``{"bond": {"atom1": ["A", 1, "N"], "atom2": ["L", 1, "C1"]}}``. + use_potentials : bool + Steer sampling with inference-time potentials. + allow_msa_seed_mismatch : bool + Fold a protein against an MSA built for a different sequence of + the same length, such as a point mutant against its wild-type MSA. + **params + Other params of the model's ``batch/structures`` method, sent as + given. + + Returns + ------- + StructurePredictionFuture + One structure set per complex, in input order. + """ + return super().fold( + complexes, + num_samples=num_samples, + num_steps=num_steps, + num_recycles=num_recycles, + step_scale=step_scale, + random_seed=random_seed, + constraints=constraints, + use_potentials=use_potentials, + allow_msa_seed_mismatch=allow_msa_seed_mismatch, + **params, + ) diff --git a/openprotein/models/fold/boltz1x.py b/openprotein/models/fold/boltz1x.py new file mode 100644 index 0000000..dd98055 --- /dev/null +++ b/openprotein/models/fold/boltz1x.py @@ -0,0 +1,76 @@ +"""Boltz-1x.""" + +from collections.abc import Mapping, Sequence +from typing import Any + +from openprotein.jobs import futures + +from .base import StructurePredictionModel + +__all__ = ["Boltz1x"] + + +class Boltz1x(StructurePredictionModel): + """Boltz-1x, Boltz-1 with physical steering potentials always on. + + It predicts protein, DNA, RNA and ligand complexes. Its checkpoint is + ``boltz-1x``. + """ + + _default_id = "boltz-1x" + + def fold( + self, + complexes: Any, + *, + num_samples: int = 1, + num_steps: int = 200, + num_recycles: int = 3, + step_scale: float = 1.638, + random_seed: int | None = None, + constraints: Sequence[Mapping[str, Any]] | None = None, + allow_msa_seed_mismatch: bool = False, + **params: Any, + ) -> futures.StructurePredictionFuture: + """Predict structures of complexes (``batch/structures``). + + Parameters + ---------- + complexes : str, bytes, Protein, Complex, list of these, or MSAFuture + Complexes to fold, one structure set per list entry. + num_samples : int + Structures to sample per complex, from 1 to 20. + num_steps : int + Diffusion sampling steps, at least 1. + num_recycles : int + Recycling steps, at least 1. + step_scale : float + Scaling factor for diffusion steps. + random_seed : int or None + Random seed, from 0 to 2**31 - 1. ``None`` draws a fresh one. + constraints : sequence of dict or None + Bond, pocket or contact constraints, such as + ``{"bond": {"atom1": ["A", 1, "N"], "atom2": ["L", 1, "C1"]}}``. + allow_msa_seed_mismatch : bool + Fold a protein against an MSA built for a different sequence of + the same length, such as a point mutant against its wild-type MSA. + **params + Other params of the model's ``batch/structures`` method, sent as + given. + + Returns + ------- + StructurePredictionFuture + One structure set per complex, in input order. + """ + return super().fold( + complexes, + num_samples=num_samples, + num_steps=num_steps, + num_recycles=num_recycles, + step_scale=step_scale, + random_seed=random_seed, + constraints=constraints, + allow_msa_seed_mismatch=allow_msa_seed_mismatch, + **params, + ) diff --git a/openprotein/models/fold/boltz2.py b/openprotein/models/fold/boltz2.py new file mode 100644 index 0000000..9ba75b8 --- /dev/null +++ b/openprotein/models/fold/boltz2.py @@ -0,0 +1,113 @@ +"""Boltz-2.""" + +from collections.abc import Mapping, Sequence +from typing import Any, Literal + +from openprotein.jobs import futures +from openprotein.molecules import Complex, Protein + +from .base import StructurePredictionModel + +__all__ = ["Boltz2"] + + +_Method = Literal[ + "MD", + "X-RAY DIFFRACTION", + "ELECTRON MICROSCOPY", + "SOLUTION NMR", + "SOLID-STATE NMR", + "NEUTRON DIFFRACTION", + "ELECTRON CRYSTALLOGRAPHY", + "FIBER DIFFRACTION", + "POWDER DIFFRACTION", + "INFRARED SPECTROSCOPY", + "FLUORESCENCE TRANSFER", + "EPR", + "THEORETICAL MODEL", + "SOLUTION SCATTERING", + "OTHER", + "AFDB", + "BOLTZ-1", +] + + +class Boltz2(StructurePredictionModel): + """Boltz-2, an all-atom structure and binding affinity prediction model. + + It predicts protein, DNA, RNA and ligand complexes, and ligand binding affinity. Its + checkpoint is ``boltz-2``. + """ + + _default_id = "boltz-2" + + def fold( + self, + complexes: Any, + *, + num_samples: int = 1, + num_steps: int = 200, + num_recycles: int = 3, + step_scale: float = 1.638, + random_seed: int | None = None, + templates: Sequence[Protein | Complex | Any] | None = None, + constraints: Sequence[Mapping[str, Any]] | None = None, + properties: Sequence[Mapping[str, Any]] | None = None, + method: _Method | None = None, + allow_msa_seed_mismatch: bool = False, + **params: Any, + ) -> futures.StructurePredictionFuture: + """Predict structures of complexes, and ligand binding affinity + (``batch/structures``). + + Parameters + ---------- + complexes : str, bytes, Protein, Complex, list of these, or MSAFuture + Complexes to fold, one structure set per list entry. + num_samples : int + Structures to sample per complex, from 1 to 20. + num_steps : int + Diffusion sampling steps, at least 1. + num_recycles : int + Recycling steps, at least 1. + step_scale : float + Scaling factor for diffusion steps. + random_seed : int or None + Random seed, from 0 to 2**31 - 1. ``None`` draws a fresh one. + templates : sequence of Protein, Complex or Template, or None + Structures to template the prediction on. + constraints : sequence of dict or None + Bond, pocket or contact constraints, such as + ``{"pocket": {"binder": "L", "contacts": [["A", 12]]}}``. + properties : sequence of dict or None + Properties to predict, such as ``{"affinity": {"binder": "L"}}`` + for the binding affinity of ligand chain ``L``. + method : str or None + Experimental method to condition on, such as + ``"X-RAY DIFFRACTION"``. + allow_msa_seed_mismatch : bool + Fold a protein against an MSA built for a different sequence of + the same length, such as a point mutant against its wild-type MSA. + **params + Other params of the model's ``batch/structures`` method, sent as + given. + + Returns + ------- + StructurePredictionFuture + One structure set per complex, in input order. + """ + return super().fold( + complexes, + num_samples=num_samples, + num_steps=num_steps, + num_recycles=num_recycles, + step_scale=step_scale, + random_seed=random_seed, + templates=templates, + constraints=constraints, + properties=properties, + method=method, + allow_msa_seed_mismatch=allow_msa_seed_mismatch, + **params, + ) diff --git a/openprotein/models/fold/esmfold.py b/openprotein/models/fold/esmfold.py new file mode 100644 index 0000000..5d9566e --- /dev/null +++ b/openprotein/models/fold/esmfold.py @@ -0,0 +1,40 @@ +"""ESMFold.""" + +from typing import Any + +from openprotein.jobs import futures + +from .base import StructurePredictionModel + +__all__ = ["ESMFold"] + + +class ESMFold(StructurePredictionModel): + """ESMFold, which predicts protein structures from ESM2 embeddings. + + Its checkpoint is ``esmfold``. + """ + + _default_id = "esmfold" + + def fold( + self, complexes: Any, *, num_recycles: int | None = None, **params: Any + ) -> futures.StructurePredictionFuture: + """Predict structures of complexes (``batch/structures``). + + Parameters + ---------- + complexes : str, bytes, Protein, Complex, list of these, or MSAFuture + Complexes to fold, one structure set per list entry. + num_recycles : int or None + Recycles, from 0 to 48. ``None`` lets the model decide. + **params + Other params of the model's ``batch/structures`` method, sent as + given. + + Returns + ------- + StructurePredictionFuture + One structure set per complex, in input order. + """ + return super().fold(complexes, num_recycles=num_recycles, **params) diff --git a/openprotein/models/fold/esmfold2.py b/openprotein/models/fold/esmfold2.py new file mode 100644 index 0000000..e73ea91 --- /dev/null +++ b/openprotein/models/fold/esmfold2.py @@ -0,0 +1,66 @@ +"""ESMFold2.""" + +from typing import Any + +from openprotein.jobs import futures + +from .base import StructurePredictionModel + +__all__ = ["ESMFold2"] + + +class ESMFold2(StructurePredictionModel): + """ESMFold2, an all-atom structure prediction model. + + It predicts protein, DNA, RNA and ligand complexes. Its checkpoints are + ``esmfold2``, the default, and ``esmfold2-fast``. + """ + + _default_id = "esmfold2" + + def fold( + self, + complexes: Any, + *, + num_samples: int = 1, + num_steps: int = 100, + num_recycles: int = 3, + random_seed: int | None = None, + allow_msa_seed_mismatch: bool = False, + **params: Any, + ) -> futures.StructurePredictionFuture: + """Predict structures of complexes (``batch/structures``). + + Parameters + ---------- + complexes : str, bytes, Protein, Complex, list of these, or MSAFuture + Complexes to fold, one structure set per list entry. + num_samples : int + Structures to sample per complex, at least 1. + num_steps : int + Diffusion sampling steps, at least 1. + num_recycles : int + Recycling steps, at least 1. + random_seed : int or None + Random seed, from 0 to 2**31 - 1. ``None`` draws a fresh one. + allow_msa_seed_mismatch : bool + Fold a protein against an MSA built for a different sequence of + the same length, such as a point mutant against its wild-type MSA. + **params + Other params of the model's ``batch/structures`` method, sent as + given. + + Returns + ------- + StructurePredictionFuture + One structure set per complex, in input order. + """ + return super().fold( + complexes, + num_samples=num_samples, + num_steps=num_steps, + num_recycles=num_recycles, + random_seed=random_seed, + allow_msa_seed_mismatch=allow_msa_seed_mismatch, + **params, + ) diff --git a/openprotein/models/fold/minifold.py b/openprotein/models/fold/minifold.py new file mode 100644 index 0000000..d1181f3 --- /dev/null +++ b/openprotein/models/fold/minifold.py @@ -0,0 +1,40 @@ +"""MiniFold.""" + +from typing import Any + +from openprotein.jobs import futures + +from .base import StructurePredictionModel + +__all__ = ["MiniFold"] + + +class MiniFold(StructurePredictionModel): + """MiniFold, which predicts single protein chains from ESM2 embeddings. + + Its checkpoint is ``minifold``. + """ + + _default_id = "minifold" + + def fold( + self, complexes: Any, *, num_recycles: int | None = None, **params: Any + ) -> futures.StructurePredictionFuture: + """Predict structures of complexes (``batch/structures``). + + Parameters + ---------- + complexes : str, bytes, Protein, Complex, list of these, or MSAFuture + Complexes to fold, one structure set per list entry. + num_recycles : int or None + Recycles, from 0 to 48. ``None`` lets the model decide. + **params + Other params of the model's ``batch/structures`` method, sent as + given. + + Returns + ------- + StructurePredictionFuture + One structure set per complex, in input order. + """ + return super().fold(complexes, num_recycles=num_recycles, **params) diff --git a/openprotein/models/fold/opendde.py b/openprotein/models/fold/opendde.py new file mode 100644 index 0000000..82aebe1 --- /dev/null +++ b/openprotein/models/fold/opendde.py @@ -0,0 +1,66 @@ +"""OpenDDE.""" + +from typing import Any + +from openprotein.jobs import futures + +from .base import StructurePredictionModel + +__all__ = ["OpenDDE"] + + +class OpenDDE(StructurePredictionModel): + """OpenDDE, an all-atom co-folding model. + + It predicts protein, DNA, RNA, ligand and ion complexes. Its checkpoints are + ``opendde``, the default, and ``opendde-abag``, for antibody-antigen complexes. + """ + + _default_id = "opendde" + + def fold( + self, + complexes: Any, + *, + num_samples: int = 1, + num_steps: int = 200, + num_recycles: int = 10, + random_seed: int | None = None, + allow_msa_seed_mismatch: bool = False, + **params: Any, + ) -> futures.StructurePredictionFuture: + """Predict structures of complexes (``batch/structures``). + + Parameters + ---------- + complexes : str, bytes, Protein, Complex, list of these, or MSAFuture + Complexes to fold, one structure set per list entry. + num_samples : int + Structures to sample per complex, at least 1. + num_steps : int + Diffusion sampling steps, at least 1. + num_recycles : int + Recycling steps, at least 1. + random_seed : int or None + Random seed, from 0 to 2**31 - 1. ``None`` draws a fresh one. + allow_msa_seed_mismatch : bool + Fold a protein against an MSA built for a different sequence of + the same length, such as a point mutant against its wild-type MSA. + **params + Other params of the model's ``batch/structures`` method, sent as + given. + + Returns + ------- + StructurePredictionFuture + One structure set per complex, in input order. + """ + return super().fold( + complexes, + num_samples=num_samples, + num_steps=num_steps, + num_recycles=num_recycles, + random_seed=random_seed, + allow_msa_seed_mismatch=allow_msa_seed_mismatch, + **params, + ) diff --git a/openprotein/models/fold/protenix.py b/openprotein/models/fold/protenix.py new file mode 100644 index 0000000..5b9b8f0 --- /dev/null +++ b/openprotein/models/fold/protenix.py @@ -0,0 +1,71 @@ +"""Protenix.""" + +from collections.abc import Sequence +from typing import Any + +from openprotein.jobs import futures +from openprotein.molecules import Complex, Protein + +from .base import StructurePredictionModel + +__all__ = ["Protenix"] + + +class Protenix(StructurePredictionModel): + """Protenix, an all-atom structure prediction model. + + It predicts protein, DNA, RNA and ligand complexes. Its checkpoint is ``protenix``. + """ + + _default_id = "protenix" + + def fold( + self, + complexes: Any, + *, + num_samples: int = 1, + num_steps: int = 200, + num_recycles: int = 10, + random_seed: int | None = None, + templates: Sequence[Protein | Complex | Any] | None = None, + allow_msa_seed_mismatch: bool = False, + **params: Any, + ) -> futures.StructurePredictionFuture: + """Predict structures of complexes (``batch/structures``). + + Parameters + ---------- + complexes : str, bytes, Protein, Complex, list of these, or MSAFuture + Complexes to fold, one structure set per list entry. + num_samples : int + Structures to sample per complex, at least 1. + num_steps : int + Diffusion sampling steps, at least 1. + num_recycles : int + Recycling steps, at least 1. + random_seed : int or None + Random seed, from 0 to 2**31 - 1. ``None`` draws a fresh one. + templates : sequence of Protein, Complex or Template, or None + Structures to template the prediction on. + allow_msa_seed_mismatch : bool + Fold a protein against an MSA built for a different sequence of + the same length, such as a point mutant against its wild-type MSA. + **params + Other params of the model's ``batch/structures`` method, sent as + given. + + Returns + ------- + StructurePredictionFuture + One structure set per complex, in input order. + """ + return super().fold( + complexes, + num_samples=num_samples, + num_steps=num_steps, + num_recycles=num_recycles, + random_seed=random_seed, + templates=templates, + allow_msa_seed_mismatch=allow_msa_seed_mismatch, + **params, + ) diff --git a/openprotein/models/fold/protenix_v2.py b/openprotein/models/fold/protenix_v2.py new file mode 100644 index 0000000..9b1325f --- /dev/null +++ b/openprotein/models/fold/protenix_v2.py @@ -0,0 +1,72 @@ +"""Protenix-v2.""" + +from collections.abc import Sequence +from typing import Any + +from openprotein.jobs import futures +from openprotein.molecules import Complex, Protein + +from .base import StructurePredictionModel + +__all__ = ["ProtenixV2"] + + +class ProtenixV2(StructurePredictionModel): + """Protenix-v2, a larger Protenix. + + It improves on Protenix for antibody-antigen complexes and ligands. Its checkpoint + is ``protenix-v2``. + """ + + _default_id = "protenix-v2" + + def fold( + self, + complexes: Any, + *, + num_samples: int = 1, + num_steps: int = 200, + num_recycles: int = 10, + random_seed: int | None = None, + templates: Sequence[Protein | Complex | Any] | None = None, + allow_msa_seed_mismatch: bool = False, + **params: Any, + ) -> futures.StructurePredictionFuture: + """Predict structures of complexes (``batch/structures``). + + Parameters + ---------- + complexes : str, bytes, Protein, Complex, list of these, or MSAFuture + Complexes to fold, one structure set per list entry. + num_samples : int + Structures to sample per complex, at least 1. + num_steps : int + Diffusion sampling steps, at least 1. + num_recycles : int + Recycling steps, at least 1. + random_seed : int or None + Random seed, from 0 to 2**31 - 1. ``None`` draws a fresh one. + templates : sequence of Protein, Complex or Template, or None + Structures to template the prediction on. + allow_msa_seed_mismatch : bool + Fold a protein against an MSA built for a different sequence of + the same length, such as a point mutant against its wild-type MSA. + **params + Other params of the model's ``batch/structures`` method, sent as + given. + + Returns + ------- + StructurePredictionFuture + One structure set per complex, in input order. + """ + return super().fold( + complexes, + num_samples=num_samples, + num_steps=num_steps, + num_recycles=num_recycles, + random_seed=random_seed, + templates=templates, + allow_msa_seed_mismatch=allow_msa_seed_mismatch, + **params, + ) diff --git a/openprotein/models/fold/rosettafold3.py b/openprotein/models/fold/rosettafold3.py new file mode 100644 index 0000000..fb7d333 --- /dev/null +++ b/openprotein/models/fold/rosettafold3.py @@ -0,0 +1,66 @@ +"""RosettaFold-3.""" + +from typing import Any + +from openprotein.jobs import futures + +from .base import StructurePredictionModel + +__all__ = ["RosettaFold3"] + + +class RosettaFold3(StructurePredictionModel): + """RosettaFold-3, an all-atom structure prediction model. + + It predicts protein and ligand complexes; DNA and RNA chains are left out + with a warning. Its checkpoint is ``rosettafold-3``. + """ + + _default_id = "rosettafold-3" + + def fold( + self, + complexes: Any, + *, + num_samples: int = 1, + num_steps: int = 50, + num_recycles: int = 10, + random_seed: int | None = None, + allow_msa_seed_mismatch: bool = False, + **params: Any, + ) -> futures.StructurePredictionFuture: + """Predict structures of complexes (``batch/structures``). + + Parameters + ---------- + complexes : str, bytes, Protein, Complex, list of these, or MSAFuture + Complexes to fold, one structure set per list entry. + num_samples : int + Structures to sample per complex, from 1 to 20. + num_steps : int + Diffusion sampling steps, at least 1. + num_recycles : int + Recycling steps, at least 1. + random_seed : int or None + Random seed, from 1 to 2**31 - 1. ``None`` draws a fresh one. + allow_msa_seed_mismatch : bool + Fold a protein against an MSA built for a different sequence of + the same length, such as a point mutant against its wild-type MSA. + **params + Other params of the model's ``batch/structures`` method, sent as + given. + + Returns + ------- + StructurePredictionFuture + One structure set per complex, in input order. + """ + return super().fold( + complexes, + num_samples=num_samples, + num_steps=num_steps, + num_recycles=num_recycles, + random_seed=random_seed, + allow_msa_seed_mismatch=allow_msa_seed_mismatch, + **params, + ) diff --git a/openprotein/models/folding/__init__.py b/openprotein/models/folding/__init__.py index 962ce7a..d42bb07 100644 --- a/openprotein/models/folding/__init__.py +++ b/openprotein/models/folding/__init__.py @@ -1,27 +1,14 @@ -"""Structure prediction models.""" +"""Deprecated alias of :py:mod:`openprotein.models.fold`. -from .alphafold2 import AlphaFold2 -from .base import StructurePredictionModel -from .boltz1 import Boltz1 -from .boltz2 import Boltz2 -from .esmfold import ESMFold -from .esmfold2 import ESMFold2 -from .minifold import MiniFold -from .opendde import OpenDDE -from .protenix import Protenix -from .protenix_v2 import ProtenixV2 -from .rosettafold3 import RosettaFold3 +.. deprecated:: 0.19.0 + Use :py:mod:`openprotein.models.fold`. This alias is removed in 0.20.0. +""" -__all__ = [ - "AlphaFold2", - "Boltz1", - "Boltz2", - "ESMFold", - "ESMFold2", - "MiniFold", - "OpenDDE", - "Protenix", - "ProtenixV2", - "RosettaFold3", - "StructurePredictionModel", -] +from openprotein import _deprecation +from openprotein.models import fold + +__all__ = list(fold.__all__) + +__getattr__ = _deprecation.alias_package( + __name__, fold, since="0.19.0", removed_in="0.20.0" +) diff --git a/openprotein/models/folding/alphafold2.py b/openprotein/models/folding/alphafold2.py deleted file mode 100644 index a234910..0000000 --- a/openprotein/models/folding/alphafold2.py +++ /dev/null @@ -1,14 +0,0 @@ -"""AlphaFold2.""" - -from .base import StructurePredictionModel - -__all__ = ["AlphaFold2"] - - -class AlphaFold2(StructurePredictionModel): - """AlphaFold2, which predicts proteins and protein complexes from an MSA. - - Its checkpoint is ``alphafold2``. - """ - - _default_id = "alphafold2" diff --git a/openprotein/models/folding/boltz1.py b/openprotein/models/folding/boltz1.py deleted file mode 100644 index 0ad4720..0000000 --- a/openprotein/models/folding/boltz1.py +++ /dev/null @@ -1,15 +0,0 @@ -"""Boltz-1.""" - -from .base import StructurePredictionModel - -__all__ = ["Boltz1"] - - -class Boltz1(StructurePredictionModel): - """Boltz-1, an all-atom structure prediction model. - - It predicts protein, DNA, RNA and ligand complexes. Its checkpoints are ``boltz-1``, - the default, and ``boltz-1x``. - """ - - _default_id = "boltz-1" diff --git a/openprotein/models/folding/boltz2.py b/openprotein/models/folding/boltz2.py deleted file mode 100644 index 79acfc4..0000000 --- a/openprotein/models/folding/boltz2.py +++ /dev/null @@ -1,15 +0,0 @@ -"""Boltz-2.""" - -from .base import StructurePredictionModel - -__all__ = ["Boltz2"] - - -class Boltz2(StructurePredictionModel): - """Boltz-2, an all-atom structure and binding affinity prediction model. - - It predicts protein, DNA, RNA and ligand complexes, and ligand binding affinity. Its - checkpoint is ``boltz-2``. - """ - - _default_id = "boltz-2" diff --git a/openprotein/models/folding/esmfold.py b/openprotein/models/folding/esmfold.py deleted file mode 100644 index 6840013..0000000 --- a/openprotein/models/folding/esmfold.py +++ /dev/null @@ -1,14 +0,0 @@ -"""ESMFold.""" - -from .base import StructurePredictionModel - -__all__ = ["ESMFold"] - - -class ESMFold(StructurePredictionModel): - """ESMFold, which predicts protein structures from ESM2 embeddings. - - Its checkpoint is ``esmfold``. - """ - - _default_id = "esmfold" diff --git a/openprotein/models/folding/esmfold2.py b/openprotein/models/folding/esmfold2.py deleted file mode 100644 index 65ac190..0000000 --- a/openprotein/models/folding/esmfold2.py +++ /dev/null @@ -1,15 +0,0 @@ -"""ESMFold2.""" - -from .base import StructurePredictionModel - -__all__ = ["ESMFold2"] - - -class ESMFold2(StructurePredictionModel): - """ESMFold2, an all-atom structure prediction model. - - It predicts protein, DNA, RNA and ligand complexes. Its checkpoints are - ``esmfold2``, the default, and ``esmfold2-fast``. - """ - - _default_id = "esmfold2" diff --git a/openprotein/models/folding/minifold.py b/openprotein/models/folding/minifold.py deleted file mode 100644 index fc14ca4..0000000 --- a/openprotein/models/folding/minifold.py +++ /dev/null @@ -1,14 +0,0 @@ -"""MiniFold.""" - -from .base import StructurePredictionModel - -__all__ = ["MiniFold"] - - -class MiniFold(StructurePredictionModel): - """MiniFold, which predicts single protein chains from ESM2 embeddings. - - Its checkpoint is ``minifold``. - """ - - _default_id = "minifold" diff --git a/openprotein/models/folding/opendde.py b/openprotein/models/folding/opendde.py deleted file mode 100644 index 9136651..0000000 --- a/openprotein/models/folding/opendde.py +++ /dev/null @@ -1,15 +0,0 @@ -"""OpenDDE.""" - -from .base import StructurePredictionModel - -__all__ = ["OpenDDE"] - - -class OpenDDE(StructurePredictionModel): - """OpenDDE, an all-atom co-folding model. - - It predicts protein, DNA, RNA, ligand and ion complexes. Its checkpoints are - ``opendde``, the default, and ``opendde-abag``, for antibody-antigen complexes. - """ - - _default_id = "opendde" diff --git a/openprotein/models/folding/protenix.py b/openprotein/models/folding/protenix.py deleted file mode 100644 index 4c1e540..0000000 --- a/openprotein/models/folding/protenix.py +++ /dev/null @@ -1,14 +0,0 @@ -"""Protenix.""" - -from .base import StructurePredictionModel - -__all__ = ["Protenix"] - - -class Protenix(StructurePredictionModel): - """Protenix, an all-atom structure prediction model. - - It predicts protein, DNA, RNA and ligand complexes. Its checkpoint is ``protenix``. - """ - - _default_id = "protenix" diff --git a/openprotein/models/folding/protenix_v2.py b/openprotein/models/folding/protenix_v2.py deleted file mode 100644 index 221870f..0000000 --- a/openprotein/models/folding/protenix_v2.py +++ /dev/null @@ -1,15 +0,0 @@ -"""Protenix-v2.""" - -from .base import StructurePredictionModel - -__all__ = ["ProtenixV2"] - - -class ProtenixV2(StructurePredictionModel): - """Protenix-v2, a larger Protenix. - - It improves on Protenix for antibody-antigen complexes and ligands. Its checkpoint - is ``protenix-v2``. - """ - - _default_id = "protenix-v2" diff --git a/openprotein/models/folding/rosettafold3.py b/openprotein/models/folding/rosettafold3.py deleted file mode 100644 index 01cd3fd..0000000 --- a/openprotein/models/folding/rosettafold3.py +++ /dev/null @@ -1,15 +0,0 @@ -"""RosettaFold-3.""" - -from .base import StructurePredictionModel - -__all__ = ["RosettaFold3"] - - -class RosettaFold3(StructurePredictionModel): - """RosettaFold-3, an all-atom structure prediction model. - - It predicts protein and ligand complexes; DNA and RNA chains are left out - with a warning. Its checkpoint is ``rosettafold-3``. - """ - - _default_id = "rosettafold-3" diff --git a/openprotein/models/foundation/__init__.py b/openprotein/models/foundation/__init__.py new file mode 100644 index 0000000..1623a6b --- /dev/null +++ b/openprotein/models/foundation/__init__.py @@ -0,0 +1,29 @@ +"""Foundational protein models: language models and inverse folding.""" + +from .ablang2 import AbLang2 +from .base import ProteinLanguageModel +from .esm1 import ESM1 +from .esm2 import ESM2 +from .esmc import ESMC +from .esmif1 import ESMIF1 +from .poet import PoET +from .poet2 import PoET2 +from .proteinmpnn import ProteinMPNN +from .protseq import ProtSeq +from .prott5 import ProtT5 +from .rotaprot import RotaProt + +__all__ = [ + "ESM1", + "ESM2", + "ESMC", + "ESMIF1", + "AbLang2", + "PoET", + "PoET2", + "ProtSeq", + "ProtT5", + "ProteinLanguageModel", + "ProteinMPNN", + "RotaProt", +] diff --git a/openprotein/models/foundation/_chains.py b/openprotein/models/foundation/_chains.py new file mode 100644 index 0000000..f0fed16 --- /dev/null +++ b/openprotein/models/foundation/_chains.py @@ -0,0 +1,120 @@ +"""Protein language models that read multichain sequences.""" + +from typing import Any, Literal + +from openprotein.common import Reduction +from openprotein.data.assaydataset import AssayDataset +from openprotein.jobs import futures + +from .base import ProteinLanguageModel + +_ChainMode = Literal["linker", "independent"] +_LINKER = "GGGGSGGGGSGGGGS" + + +class _ChainedLanguageModel(ProteinLanguageModel): + """A protein language model joining a sequence's ``:``-delimited chains.""" + + def embed( + self, + sequences: list[str] | list[bytes] | AssayDataset, + reduction: Reduction | None = None, + *, + chain_mode: _ChainMode = "linker", + chain_linker: str = _LINKER, + **params: Any, + ) -> futures.EmbeddingFuture: + """Embed sequences or an assay's (``batch/embeddings``). + + Parameters + ---------- + sequences : list of str or bytes or AssayDataset + Sequences to embed, or an assay whose sequences are embedded. + ``:`` separates chains. + reduction : {"MEAN", "SUM"} or None + Pool each sequence's embedding over its residues. ``None`` keeps + one row per residue. A GP or UMAP fit on the embeddings needs a pooled + reduction. + chain_mode : {"linker", "independent"} + Join a sequence's chains with ``chain_linker``, or embed each chain + on its own. + chain_linker : str + Linker joining chains when ``chain_mode`` is ``"linker"``. + **params + Other params of the model's ``batch/embeddings`` method, sent as + given. + + Returns + ------- + EmbeddingFuture + Future for the submitted embeddings. + """ + return super().embed( + sequences, + reduction=reduction, + chain_mode=chain_mode, + chain_linker=chain_linker, + **params, + ) + + def logits( + self, + sequences: list[str] | list[bytes], + *, + chain_mode: _ChainMode = "linker", + chain_linker: str = _LINKER, + **params: Any, + ) -> futures.LogitsFuture: + """Per-residue logits for sequences (``batch/logits``). + + Parameters + ---------- + sequences : list of str or bytes + Sequences to read. ``:`` separates chains. + chain_mode : {"linker", "independent"} + Join a sequence's chains with ``chain_linker``, or read each chain + on its own. + chain_linker : str + Linker joining chains when ``chain_mode`` is ``"linker"``. + **params + Other params of the model's ``batch/logits`` method, sent as given. + + Returns + ------- + LogitsFuture + Per-residue logits per sequence. + """ + return super().logits( + sequences, chain_mode=chain_mode, chain_linker=chain_linker, **params + ) + + def attn( + self, + sequences: list[str] | list[bytes], + *, + chain_mode: _ChainMode = "linker", + chain_linker: str = _LINKER, + **params: Any, + ) -> futures.AttentionFuture: + """Attention maps for sequences of up to 3072 residues (``batch/attn``). + + Parameters + ---------- + sequences : list of str or bytes + Sequences to read. ``:`` separates chains. + chain_mode : {"linker", "independent"} + Join a sequence's chains with ``chain_linker``, or read each chain + on its own. + chain_linker : str + Linker joining chains when ``chain_mode`` is ``"linker"``. + **params + Other params of the model's ``batch/attn`` method, sent as given. + + Returns + ------- + AttentionFuture + Attention maps per sequence. + """ + return super().attn( + sequences, chain_mode=chain_mode, chain_linker=chain_linker, **params + ) diff --git a/openprotein/models/foundational/_inverse_folding.py b/openprotein/models/foundation/_inverse_folding.py similarity index 100% rename from openprotein/models/foundational/_inverse_folding.py rename to openprotein/models/foundation/_inverse_folding.py diff --git a/openprotein/models/foundational/ablang2.py b/openprotein/models/foundation/ablang2.py similarity index 100% rename from openprotein/models/foundational/ablang2.py rename to openprotein/models/foundation/ablang2.py diff --git a/openprotein/models/foundational/base.py b/openprotein/models/foundation/base.py similarity index 81% rename from openprotein/models/foundational/base.py rename to openprotein/models/foundation/base.py index 50f8876..2e8ba9d 100644 --- a/openprotein/models/foundational/base.py +++ b/openprotein/models/foundation/base.py @@ -16,7 +16,7 @@ class ProteinLanguageModel(Model): - """A protein language model: embeddings pooled by default, and fits on them. + """A protein language model: embeddings, and fits on them. ``fit_svd``, ``fit_umap`` and ``fit_gp`` fit on this model's embeddings, passing ``params`` as the embedding params, such as ``prompt_id``. @@ -27,11 +27,27 @@ class ProteinLanguageModel(Model): def embed( self, sequences: list[str] | list[bytes] | AssayDataset, - reduction: Reduction | None = "MEAN", + reduction: Reduction | None = None, **params: Any, ) -> futures.EmbeddingFuture: - """Embed sequences or an assay's (``batch/embeddings``); - ``reduction=None`` is per residue. + """Embed sequences or an assay's (``batch/embeddings``). + + Parameters + ---------- + sequences : list of str or bytes or AssayDataset + Sequences to embed, or an assay whose sequences are embedded. + reduction : {"MEAN", "SUM"} or None + Pool each sequence's embedding over its residues. ``None`` keeps + one row per residue. A GP or UMAP fit on the embeddings needs a pooled + reduction. + **params + Other params of the model's ``batch/embeddings`` method, sent as + given. + + Returns + ------- + EmbeddingFuture + Future for the submitted embeddings. """ return super().embed(sequences, reduction=reduction, **params) diff --git a/openprotein/models/foundational/esm1.py b/openprotein/models/foundation/esm1.py similarity index 100% rename from openprotein/models/foundational/esm1.py rename to openprotein/models/foundation/esm1.py diff --git a/openprotein/models/foundational/esm2.py b/openprotein/models/foundation/esm2.py similarity index 100% rename from openprotein/models/foundational/esm2.py rename to openprotein/models/foundation/esm2.py diff --git a/openprotein/models/foundational/esmc.py b/openprotein/models/foundation/esmc.py similarity index 100% rename from openprotein/models/foundational/esmc.py rename to openprotein/models/foundation/esmc.py diff --git a/openprotein/models/foundation/esmif1.py b/openprotein/models/foundation/esmif1.py new file mode 100644 index 0000000..27fcfa1 --- /dev/null +++ b/openprotein/models/foundation/esmif1.py @@ -0,0 +1,65 @@ +"""ESM-IF1.""" + +from typing import Any + +from openprotein.jobs import futures + +from ._inverse_folding import _InverseFoldingModel, _renamed + +__all__ = ["ESMIF1"] + + +class ESMIF1(_InverseFoldingModel): + """ESM-IF1, an inverse-folding model. + + It scores and designs sequences for a fixed backbone. Its checkpoint is + ``esm-if1``. + """ + + _default_id = "esm-if1" + + def generate( + self, + query: Any = None, + design: Any = None, + *, + num_samples: int = 100, + temperature: float = 1.0, + random_seed: int | None = None, + **params: Any, + ) -> futures.SequenceGenerationFuture: + """Design sequences for the query's backbone (``generate/sequences``). + + .. deprecated:: 0.18.0 + ``seed=`` is removed in 0.19.0; pass ``random_seed``. + + Parameters + ---------- + query : Protein, Complex, Query or str, optional + The structure to design for, or its id. + design : Future or str, optional + An RFdiffusion or BoltzGen job or its id, in any state, in place of + ``query``: its designed structures are the queries, and the job runs + once the design has finished. + num_samples : int + Sequences per query, at least 1. + temperature : float + Sampling temperature, from 1e-6 to 1e6. Low favours recovery, + high favours diversity. + random_seed : int or None + Random seed, from 0 to 2**32. Sample ``i`` draws with + ``seed + i``. ``None`` draws a fresh one. + **params + Other params of the model's ``generate/sequences`` method, sent as + given. + + Returns + ------- + SequenceGenerationFuture + The designed sequences. + """ + params["random_seed"] = random_seed + _renamed(params, "generate", "seed", "random_seed") + return super().generate( + query, design, num_samples=num_samples, temperature=temperature, **params + ) diff --git a/openprotein/models/foundational/poet.py b/openprotein/models/foundation/poet.py similarity index 58% rename from openprotein/models/foundational/poet.py rename to openprotein/models/foundation/poet.py index 36987bf..5bde6ae 100644 --- a/openprotein/models/foundational/poet.py +++ b/openprotein/models/foundation/poet.py @@ -47,12 +47,30 @@ def _conditioned( def embed( self, sequences: list[str] | list[bytes] | AssayDataset, - reduction: Reduction | None = "MEAN", + reduction: Reduction | None = None, prompt: Any = None, **params: Any, ) -> futures.EmbeddingFuture: - """Embed sequences or an assay's (``batch/embeddings``); - ``reduction=None`` is per residue. + """Embed sequences or an assay's (``batch/embeddings``). + + Parameters + ---------- + sequences : list of str or bytes or AssayDataset + Sequences to embed, or an assay whose sequences are embedded. + reduction : {"MEAN", "SUM"} or None + Pool each sequence's embedding over its residues. ``None`` keeps + one row per residue. A GP or UMAP fit on the embeddings needs a pooled + reduction. + prompt : Prompt or str, optional + The prompt to condition on, or its id. + **params + Other params of the model's ``batch/embeddings`` method, sent as + given. + + Returns + ------- + EmbeddingFuture + Future for the submitted embeddings. """ sequences = _prepared(sequences) return super().embed( @@ -84,14 +102,39 @@ def score( ) def single_site( - self, base_sequence: str | bytes, prompt: Any = None, **params: Any + self, + base_sequence: str | bytes, + prompt: Any = None, + *, + include_gaps: bool = False, + **params: Any, ) -> futures.SingleSiteScoreFuture: - """Score every single-site mutant of ``base_sequence`` (``single-site/scores``).""" + """Score every single-site mutant of ``base_sequence`` (``single-site/scores``). + + Parameters + ---------- + base_sequence : str or bytes + The sequence to mutate. + prompt : Prompt or str, optional + The prompt to condition on, or its id. + include_gaps : bool + Include gap substitutions, and scan gap positions. + **params + Other params of the model's ``single-site/scores`` method, sent as + given. + + Returns + ------- + SingleSiteScoreFuture + Scores of every single-site mutant. + """ base_sequence = _text(base_sequence, "base_sequence") return super().single_site( base_sequence, **self._conditioned( - params, prompt, method=("single_site", "single-site/*") + {"include_gaps": include_gaps, **params}, + prompt, + method=("single_site", "single-site/*"), ), ) @@ -103,21 +146,88 @@ def indel( prompt: Any = None, **params: Any, ) -> futures.IndelScoreFuture: - """Score ``base_sequence`` with ``insert`` added, or ``delete`` sizes removed, at each site.""" + """Score ``base_sequence`` with ``insert`` added, or ``delete`` sizes + removed, at each site (``indel/scores``). + + Parameters + ---------- + base_sequence : str or bytes + The sequence to edit. + insert : str or None + Fragment inserted at, or in place of, each site. + delete : list of int or None + Sizes of the fragment deleted at each site. + prompt : Prompt or str, optional + The prompt to condition on, or its id. + **params + Other params of the model's ``indel/scores`` method, sent as given. + + Returns + ------- + IndelScoreFuture + Scores of every variant. + """ base_sequence = _text(base_sequence, "base_sequence") - if insert is not None: - params["insert"] = insert - if delete is not None: - params["delete"] = delete return super().indel( base_sequence, - **self._conditioned(params, prompt, method=("indel", "indel/*")), + **self._conditioned( + {"insert": insert, "delete": delete, **params}, + prompt, + method=("indel", "indel/*"), + ), ) def generate( - self, prompt: Any = None, **params: Any + self, + prompt: Any = None, + *, + num_samples: int = 100, + temperature: float = 1.0, + top_k: int = 20, + top_p: float = 1.0, + max_length: int = 1000, + random_seed: int | None = None, + **params: Any, ) -> futures.SequenceGenerationFuture: - """Sample sequences (``generate/sequences``).""" + """Sample sequences (``generate/sequences``). + + Parameters + ---------- + prompt : Prompt or str + The prompt to condition on, or its id. + num_samples : int + Sequences to sample, at least 1. + temperature : float + Sampling temperature, from 1e-6 to 1e6. + top_k : int + Sample from the ``top_k`` likeliest tokens. 0 samples from all. + top_p : float + Sample from the smallest set of tokens with total probability + ``top_p``, from 0 to 1. 1 samples from all. + max_length : int + A sample holds at most ``max_length + 1`` residues, from 1 to + 15999. + random_seed : int or None + Random seed, from 0 to 2**32 - 1. Sample ``i`` draws with + ``(seed + i) mod 2**32``. ``None`` draws a fresh one. + **params + Other params of the model's ``generate/sequences`` method, sent as + given. + + Returns + ------- + SequenceGenerationFuture + The sampled sequences. + """ + params = { + "num_samples": num_samples, + "temperature": temperature, + "top_k": top_k, + "top_p": top_p, + "max_length": max_length, + "random_seed": random_seed, + **params, + } return cast( futures.SequenceGenerationFuture, super().generate( diff --git a/openprotein/models/foundation/poet2.py b/openprotein/models/foundation/poet2.py new file mode 100644 index 0000000..dae6c10 --- /dev/null +++ b/openprotein/models/foundation/poet2.py @@ -0,0 +1,438 @@ +"""PoET-2.""" + +from collections.abc import Sequence +from typing import TYPE_CHECKING, Any, Literal + +from openprotein.common import Reduction +from openprotein.data.assaydataset import AssayDataset +from openprotein.jobs import futures + +from .. import _inputs +from ..model import _prepared, _text +from .poet import PoET + +if TYPE_CHECKING: + from openprotein.jobs.futures import GPFitFuture, SVDFitFuture, UMAPFitFuture + +__all__ = ["PoET2"] + +_Decoder = Literal["mlm", "clm"] + + +class PoET2(PoET): + """PoET-2, a multi-modal protein language model conditioned on a protein family. + + Like PoET, every verb takes ``prompt``. Verbs other than ``indel`` also + take ``query``, a sequence, ``Protein``, ``Complex``, ``Query`` or query id, + sent as ``query_id``, which conditions on a protein's sequence or + structure. Its checkpoint is ``poet-2``. + """ + + _default_id = "poet-2" + + def embed( + self, + sequences: list[str] | list[bytes] | AssayDataset, + reduction: Reduction | None = None, + prompt: Any = None, + query: Any = None, + *, + decoder_type: _Decoder | None = None, + use_query_structure_in_decoder: bool = True, + **params: Any, + ) -> futures.EmbeddingFuture: + """Embed sequences or an assay's (``batch/embeddings``). + + Parameters + ---------- + sequences : list of str or bytes or AssayDataset + Sequences to embed, or an assay whose sequences are embedded. + reduction : {"MEAN", "SUM"} or None + Pool each sequence's embedding over its residues. ``None`` keeps + one row per residue. A GP or UMAP fit on the embeddings needs a pooled + reduction. + prompt : Prompt or str, optional + The prompt to condition on, or its id. + query : str, Protein, Complex or Query, optional + A protein whose sequence or structure to condition on, or its id. + decoder_type : {"mlm", "clm"} or None + Decoder to read out. ``None`` reads the MLM decoder. + use_query_structure_in_decoder : bool + Give the decoder the query's structure alongside each sequence. + Ignored without a query. + **params + Other params of the model's ``batch/embeddings`` method, sent as + given. + + Returns + ------- + EmbeddingFuture + Future for the submitted embeddings. + """ + sequences = _prepared(sequences) + return super().embed( + sequences, + reduction=reduction, + **self._conditioned( + { + "decoder_type": decoder_type, + "use_query_structure_in_decoder": use_query_structure_in_decoder, + **params, + }, + prompt, + query, + method=("embed", "batch/embeddings"), + ), + ) + + def logits( + self, + sequences: list[str] | list[bytes], + prompt: Any = None, + query: Any = None, + *, + decoder_type: _Decoder | None = None, + use_query_structure_in_decoder: bool = True, + **params: Any, + ) -> futures.LogitsFuture: + """Per-position logits for sequences (``batch/logits``). + + Parameters + ---------- + sequences : list of str or bytes + Sequences to score. + prompt : Prompt or str, optional + The prompt to condition on, or its id. + query : str, Protein, Complex or Query, optional + A protein whose sequence or structure to condition on, or its id. + decoder_type : {"mlm", "clm"} or None + Decoder to read out. ``None`` reads the MLM decoder. + use_query_structure_in_decoder : bool + Give the decoder the query's structure alongside each sequence. + Ignored without a query. + **params + Other params of the model's ``batch/logits`` method, sent as + given. + + Returns + ------- + LogitsFuture + Per-position logits. + """ + sequences = _prepared(sequences) + return super().logits( + sequences, + **self._conditioned( + { + "decoder_type": decoder_type, + "use_query_structure_in_decoder": use_query_structure_in_decoder, + **params, + }, + prompt, + query, + method=("logits", "batch/logits"), + ), + ) + + def attn( + self, + sequences: list[str] | list[bytes], + prompt: Any = None, + query: Any = None, + *, + decoder_type: _Decoder | None = None, + use_query_structure_in_decoder: bool = True, + **params: Any, + ) -> futures.AttentionFuture: + """Attention maps for sequences (``batch/attn``). + + Parameters + ---------- + sequences : list of str or bytes + Sequences to read attention from. + prompt : Prompt or str, optional + The prompt to condition on, or its id. + query : str, Protein, Complex or Query, optional + A protein whose sequence or structure to condition on, or its id. + decoder_type : {"mlm", "clm"} or None + Decoder to read out. ``None`` reads the MLM decoder. + use_query_structure_in_decoder : bool + Give the decoder the query's structure alongside each sequence. + Ignored without a query. + **params + Other params of the model's ``batch/attn`` method, sent as + given. + + Returns + ------- + AttentionFuture + Attention maps. + """ + sequences = _prepared(sequences) + return super().attn( + sequences, + **self._conditioned( + { + "decoder_type": decoder_type, + "use_query_structure_in_decoder": use_query_structure_in_decoder, + **params, + }, + prompt, + query, + method=("attn", "batch/attn"), + ), + ) + + def score( + self, + sequences: list[str] | list[bytes], + prompt: Any = None, + query: Any = None, + *, + use_query_structure_in_decoder: bool = True, + **params: Any, + ) -> futures.LogLikelihoodFuture: + """Log-likelihoods of sequences (``batch/loglikelihood``). + + Parameters + ---------- + sequences : list of str or bytes + Sequences to score. + prompt : Prompt or str, optional + The prompt to condition on, or its id. + query : str, Protein, Complex or Query, optional + A protein whose sequence or structure to condition on, or its id. + use_query_structure_in_decoder : bool + Give the decoder the query's structure alongside each sequence. + Ignored without a query. + **params + Other params of the model's ``batch/loglikelihood`` method, sent as + given. + + Returns + ------- + LogLikelihoodFuture + Log-likelihood of each sequence. + """ + sequences = _prepared(sequences) + return super().score( + sequences, + **self._conditioned( + { + "use_query_structure_in_decoder": use_query_structure_in_decoder, + **params, + }, + prompt, + query, + method=("score", "batch/loglikelihood"), + ), + ) + + def single_site( + self, + base_sequence: str | bytes, + prompt: Any = None, + query: Any = None, + *, + use_query_structure_in_decoder: bool = True, + include_gaps: bool = False, + **params: Any, + ) -> futures.SingleSiteScoreFuture: + """Score every single-site mutant of ``base_sequence`` (``single-site/scores``). + + Parameters + ---------- + base_sequence : str or bytes + The sequence to mutate. + prompt : Prompt or str, optional + The prompt to condition on, or its id. + query : str, Protein, Complex or Query, optional + A protein whose sequence or structure to condition on, or its id. + use_query_structure_in_decoder : bool + Give the decoder the query's structure alongside each sequence. + Ignored without a query. + include_gaps : bool + Include gap substitutions, and scan gap positions. + **params + Other params of the model's ``single-site/scores`` method, sent as + given. + + Returns + ------- + SingleSiteScoreFuture + Scores of every single-site mutant. + """ + base_sequence = _text(base_sequence, "base_sequence") + return super().single_site( + base_sequence, + **self._conditioned( + { + "use_query_structure_in_decoder": use_query_structure_in_decoder, + "include_gaps": include_gaps, + **params, + }, + prompt, + query, + method=("single_site", "single-site/*"), + ), + ) + + def generate( + self, + prompt: Any = None, + query: Any = None, + design: Any = None, + *, + num_samples: int = 100, + temperature: float = 1.0, + top_k: int = 20, + top_p: float = 1.0, + max_length: int = 1000, + random_seed: int | None = None, + use_query_structure_in_decoder: bool = True, + ensemble_weights: Sequence[float] | None = None, + ensemble_method: Literal["arithmetic", "geometric"] | None = None, + **params: Any, + ) -> futures.SequenceGenerationFuture: + """Sample sequences (``generate/sequences``). + + Parameters + ---------- + prompt : Prompt or str, optional + The prompt to condition on, or its id. + query : str, Protein, Complex, Query, or list of these, optional + Proteins whose sequence or structure to condition on, or their ids. + design : Future or str, optional + An RFdiffusion or BoltzGen job or its id, in any state, in place of + ``query``: its designed structures are the queries, and the job runs + once the design has finished. + num_samples : int + Sequences to sample, at least 1. + temperature : float + Sampling temperature, from 1e-6 to 1e6. + top_k : int + Sample from the ``top_k`` likeliest tokens. 0 samples from all. + top_p : float + Sample from the smallest set of tokens with total probability + ``top_p``, from 0 to 1. 1 samples from all. + max_length : int + Most residues in a sample, from 1 to 16000. A query's length + takes its place. + random_seed : int or None + Random seed, from 0 to 2**32 - 1. Sample ``i`` draws with + ``(seed + i) mod 2**32``. ``None`` draws a fresh one. + use_query_structure_in_decoder : bool + Give the decoder the query's structure alongside each sequence. + Ignored without a query. + ensemble_weights : sequence of float or None + Weight of each prompt replicate's likelihood when sampling. + ensemble_method : {"arithmetic", "geometric"} or None + How replicate likelihoods combine. ``None`` is arithmetic. + **params + Other params of the model's ``generate/sequences`` method, sent as + given. + + Returns + ------- + SequenceGenerationFuture + The sampled sequences. + """ + params = { + "num_samples": num_samples, + "temperature": temperature, + "top_k": top_k, + "top_p": top_p, + "max_length": max_length, + "random_seed": random_seed, + "use_query_structure_in_decoder": use_query_structure_in_decoder, + "ensemble_weights": ensemble_weights, + "ensemble_method": ensemble_method, + **params, + } + _inputs.check_inputs(params, prompt=prompt, query=query, design=design) + _inputs.check_one_structure_source(params, query, design) + self._method("generate", "generate/*") + many = _inputs.takes_list(self._params_schema("generate/sequences"), "query_id") + params = dict(params) + _inputs.with_param(params, "prompt_id", _inputs.prompt_id(prompt), "prompt") + _inputs.with_param( + params, + "query_id", + _inputs.query_ids(self.session, query, many=many), + "query", + ) + _inputs.with_param(params, "design_id", _inputs.design_id(design), "design") + return super().generate(**params) + + def fit_svd( + self, + sequences: list[str] | list[bytes] | None = None, + assay: Any = None, + n_components: int | None = None, + reduction: Reduction | None = None, + prompt: Any = None, + query: Any = None, + **params: Any, + ) -> "SVDFitFuture": + """Fit an SVD on this model's embeddings of ``sequences`` or an assay's.""" + _inputs.check_fit_source(sequences, assay) + sequences = _prepared(sequences) + return super().fit_svd( + sequences, + assay, + n_components=n_components, + reduction=reduction, + **self._conditioned(params, prompt, query, assay), + ) + + def fit_umap( + self, + sequences: list[str] | list[bytes] | None = None, + assay: Any = None, + n_components: int | None = None, + reduction: Reduction = "MEAN", + n_neighbors: int | None = None, + min_dist: float | None = None, + prompt: Any = None, + query: Any = None, + **params: Any, + ) -> "UMAPFitFuture": + """Fit a UMAP on this model's embeddings of ``sequences`` or an assay's.""" + _inputs.check_fit_source(sequences, assay) + sequences = _prepared(sequences) + return super().fit_umap( + sequences, + assay, + n_components=n_components, + reduction=reduction, + n_neighbors=n_neighbors, + min_dist=min_dist, + **self._conditioned(params, prompt, query, assay), + ) + + def fit_gp( + self, + assay: Any, + properties: list[str], + reduction: Reduction, + name: str | None = None, + description: str | None = None, + kernel: str = "rbf", + period: float | None = None, + alpha: float | None = None, + prompt: Any = None, + query: Any = None, + **params: Any, + ) -> "GPFitFuture": + """Train a Gaussian process on an assay's properties, featurized by this model.""" + return super().fit_gp( + assay, + properties, + reduction, + name=name, + description=description, + kernel=kernel, + period=period, + alpha=alpha, + **self._conditioned(params, prompt, query, assay), + ) diff --git a/openprotein/models/foundation/proteinmpnn.py b/openprotein/models/foundation/proteinmpnn.py new file mode 100644 index 0000000..dd39310 --- /dev/null +++ b/openprotein/models/foundation/proteinmpnn.py @@ -0,0 +1,312 @@ +"""ProteinMPNN.""" + +from collections.abc import Mapping, Sequence +from typing import Any, Literal + +from openprotein.common import Reduction +from openprotein.data.assaydataset import AssayDataset +from openprotein.jobs import futures + +from ..model import _prepared +from ._inverse_folding import _InverseFoldingModel, _renamed + +__all__ = ["ProteinMPNN"] + +_Weights = Literal["v_48_002", "v_48_010", "v_48_020", "v_48_030"] + + +class ProteinMPNN(_InverseFoldingModel): + """ProteinMPNN, a message-passing inverse-folding model. + + It scores, embeds and designs sequences for a fixed backbone. Its + checkpoints are ``proteinmpnn``, the default, and ``solublempnn``, trained + on soluble proteins. + """ + + _default_id = "proteinmpnn" + + def embed( + self, + sequences: list[str] | list[bytes] | AssayDataset, + query: Any = None, + reduction: Reduction | None = None, + *, + model_name: _Weights = "v_48_020", + ca_only: bool = False, + soluble_model: bool = False, + **params: Any, + ) -> futures.EmbeddingFuture: + """Embed sequences or an assay's on the query's backbone + (``batch/embeddings``). + + Parameters + ---------- + sequences : list of str or bytes or AssayDataset + Sequences to embed, or an assay whose sequences are embedded. + query : Protein, Complex, Query or str + The structure to condition on, or its id. + reduction : {"MEAN", "SUM"} or None + Pool each sequence's embedding over its residues. ``None`` keeps + one row per residue. A GP or UMAP fit on the embeddings needs a pooled + reduction. + model_name : {"v_48_002", "v_48_010", "v_48_020", "v_48_030"} + Weights version, named by its training noise level. + ca_only : bool + Use the CA-only model. + soluble_model : bool + Use the soluble model. Always on for ``solublempnn``. + **params + Other params of the model's ``batch/embeddings`` method, sent as + given. + + Returns + ------- + EmbeddingFuture + Future for the submitted embeddings. + """ + sequences = _prepared(sequences) + return super().embed( + sequences, + reduction=reduction, + **self._on_structure( + { + "model_name": model_name, + "ca_only": ca_only, + "soluble_model": soluble_model, + **params, + }, + query, + method=("embed", "batch/embeddings"), + ), + ) + + def score( + self, + sequences: list[str] | list[bytes], + query: Any = None, + *, + decoding_orders: int = 1, + random_seed: int = 1, + model_name: _Weights = "v_48_020", + ca_only: bool = False, + soluble_model: bool = False, + **params: Any, + ) -> futures.LogLikelihoodFuture: + """Log-likelihoods of sequences on the query's backbone + (``batch/loglikelihood``). + + Parameters + ---------- + sequences : list of str or bytes + Sequences to score. + query : Protein, Complex, Query or str + The structure to condition on, or its id. + decoding_orders : int + Random decoding orders to average each score over, from 1 to 10. + random_seed : int + Random seed picking the decoding orders, from 1 to 2**32. + model_name : {"v_48_002", "v_48_010", "v_48_020", "v_48_030"} + Weights version, named by its training noise level. + ca_only : bool + Use the CA-only model. + soluble_model : bool + Use the soluble model. Always on for ``solublempnn``. + **params + Other params of the model's ``batch/loglikelihood`` method, sent as + given. + + Returns + ------- + LogLikelihoodFuture + One log-likelihood per sequence. + """ + return super().score( + sequences, + query, + decoding_orders=decoding_orders, + random_seed=random_seed, + model_name=model_name, + ca_only=ca_only, + soluble_model=soluble_model, + **params, + ) + + def single_site( + self, + base_sequence: str | bytes | None = None, + query: Any = None, + *, + decoding_orders: int = 1, + random_seed: int = 1, + model_name: _Weights = "v_48_020", + ca_only: bool = False, + soluble_model: bool = False, + **params: Any, + ) -> futures.SingleSiteScoreFuture: + """Score every single-site mutant of ``base_sequence`` on the query's + backbone (``single-site/scores``). + + .. deprecated:: 0.18.0 + ``sequence=`` is removed in 0.19.0; pass ``base_sequence``. + + Parameters + ---------- + base_sequence : str or bytes + The sequence to mutate. + query : Protein, Complex, Query or str + The structure to condition on, or its id. + decoding_orders : int + Random decoding orders to average each score over, from 1 to 10. + random_seed : int + Random seed picking the decoding orders, from 1 to 2**32. + model_name : {"v_48_002", "v_48_010", "v_48_020", "v_48_030"} + Weights version, named by its training noise level. + ca_only : bool + Use the CA-only model. + soluble_model : bool + Use the soluble model. Always on for ``solublempnn``. + **params + Other params of the model's ``single-site/scores`` method, sent as + given. + + Returns + ------- + SingleSiteScoreFuture + Scores of every single-site mutant. + """ + if base_sequence is not None: + params["base_sequence"] = base_sequence + _renamed(params, "single_site", "sequence", "base_sequence") + base_sequence = params.pop("base_sequence", None) + return super().single_site( + base_sequence, + query, + decoding_orders=decoding_orders, + random_seed=random_seed, + model_name=model_name, + ca_only=ca_only, + soluble_model=soluble_model, + **params, + ) + + def generate( + self, + query: Any = None, + design: Any = None, + *, + num_samples: int = 100, + temperature: float = 0.1, + random_seed: int | None = None, + model_name: _Weights = "v_48_020", + ca_only: bool = False, + soluble_model: bool = False, + chains_to_design: Sequence[str] | None = None, + fixed_positions: Sequence[Sequence[int]] | None = None, + tie_positions: Sequence[Sequence[int]] | None = None, + omit_aas_global: Sequence[str] | None = None, + omit_aas_per_chain_position: Mapping[str, Sequence[tuple[Sequence[int], str]]] + | None = None, + aa_bias_global: Mapping[str, float] | None = None, + aa_bias_per_position: Mapping[str, Sequence[Sequence[float]]] | None = None, + backbone_noise: float | None = None, + pssm: Mapping[str, Mapping[str, Sequence[float]]] | None = None, + pssm_multi: float = 0.0, + pssm_threshold: float = 0.0, + pssm_bias: bool = False, + pssm_log_odds: bool = False, + **params: Any, + ) -> futures.SequenceGenerationFuture: + """Design sequences for the query's backbone (``generate/sequences``). + + .. deprecated:: 0.18.0 + ``seed=`` is removed in 0.19.0; pass ``random_seed``. + + Parameters + ---------- + query : Protein, Complex, Query, str, or list of these, optional + Structures to design for, or their ids. + design : Future or str, optional + An RFdiffusion or BoltzGen job or its id, in any state, in place of + ``query``: its designed structures are the queries, and the job runs + once the design has finished. + num_samples : int + Sequences per query, from 1 to 1000. + temperature : float + Sampling temperature, from 1e-6 to 1e6. Low favours recovery, + high favours diversity. + random_seed : int or None + Random seed, from 0 to 2**32. The sample at overall position ``p`` + draws with ``seed + p``. ``None`` draws a fresh one. + model_name : {"v_48_002", "v_48_010", "v_48_020", "v_48_030"} + Weights version, named by its training noise level. + ca_only : bool + Use the CA-only model. + soluble_model : bool + Use the soluble model. Always on for ``solublempnn``. + chains_to_design : sequence of str or None + Chains to redesign. Other chains are kept fixed. + fixed_positions : sequence of sequence of int, or None + Positions to hold fixed, one list per designed chain. + tie_positions : sequence of sequence of int, or None + Positions tied to one residue, one list per designed chain. + omit_aas_global : sequence of str or None + Amino acids to exclude from every position. + omit_aas_per_chain_position : dict or None + Per chain, ``[positions, amino acids]`` pairs excluding those + amino acids at those positions. + aa_bias_global : dict of str to float, or None + Logit bias per amino acid, at every position. + aa_bias_per_position : dict or None + Per chain, one 21-element logit bias row per residue. + backbone_noise : float or None + Gaussian noise in Angstrom added to backbone atoms, from 0 to 10. + pssm : dict or None + Per chain, ``pssm_coef``, ``pssm_bias`` and ``pssm_log_odds`` + arrays over its residues. + pssm_multi : float + Weight of the PSSM against the model's own distribution, from 0 + to 1. + pssm_threshold : float + Log-odds cutoff restricting the allowed residues. + pssm_bias : bool + Apply the PSSM bias. + pssm_log_odds : bool + Apply the PSSM log-odds mask. + **params + Other params of the model's ``generate/sequences`` method, sent as + given. + + Returns + ------- + SequenceGenerationFuture + The designed sequences. + """ + params["random_seed"] = random_seed + _renamed(params, "generate", "seed", "random_seed") + return super().generate( + query, + design, + num_samples=num_samples, + temperature=temperature, + model_name=model_name, + ca_only=ca_only, + soluble_model=soluble_model, + chains_to_design=chains_to_design, + fixed_positions=fixed_positions, + tie_positions=tie_positions, + omit_aas_global=omit_aas_global, + omit_aas_per_chain_position=omit_aas_per_chain_position, + aa_bias_global=aa_bias_global, + aa_bias_per_position=aa_bias_per_position, + backbone_noise=backbone_noise, + pssm=pssm, + pssm_multi=pssm_multi, + pssm_threshold=pssm_threshold, + pssm_bias=pssm_bias, + pssm_log_odds=pssm_log_odds, + **params, + ) + + +class _SolubleMPNN(ProteinMPNN): + _default_id = "solublempnn" diff --git a/openprotein/models/foundational/protseq.py b/openprotein/models/foundation/protseq.py similarity index 79% rename from openprotein/models/foundational/protseq.py rename to openprotein/models/foundation/protseq.py index 3190eca..2d89f41 100644 --- a/openprotein/models/foundational/protseq.py +++ b/openprotein/models/foundation/protseq.py @@ -1,11 +1,11 @@ """ProtSeq.""" -from .base import ProteinLanguageModel +from ._chains import _ChainedLanguageModel __all__ = ["ProtSeq"] -class ProtSeq(ProteinLanguageModel): +class ProtSeq(_ChainedLanguageModel): """ProtSeq, a masked protein language model trained on UniRef50. It has about 300M parameters and was trained with contact and secondary structure diff --git a/openprotein/models/foundational/prott5.py b/openprotein/models/foundation/prott5.py similarity index 100% rename from openprotein/models/foundational/prott5.py rename to openprotein/models/foundation/prott5.py diff --git a/openprotein/models/foundational/rotaprot.py b/openprotein/models/foundation/rotaprot.py similarity index 79% rename from openprotein/models/foundational/rotaprot.py rename to openprotein/models/foundation/rotaprot.py index f8f2d3a..76627df 100644 --- a/openprotein/models/foundational/rotaprot.py +++ b/openprotein/models/foundation/rotaprot.py @@ -1,11 +1,11 @@ """RotaProt.""" -from .base import ProteinLanguageModel +from ._chains import _ChainedLanguageModel __all__ = ["RotaProt"] -class RotaProt(ProteinLanguageModel): +class RotaProt(_ChainedLanguageModel): """RotaProt, a masked protein language model. It has about 900M parameters and uses rotary position embeddings. Its checkpoints diff --git a/openprotein/models/foundational/__init__.py b/openprotein/models/foundational/__init__.py index 1623a6b..c878bc2 100644 --- a/openprotein/models/foundational/__init__.py +++ b/openprotein/models/foundational/__init__.py @@ -1,29 +1,14 @@ -"""Foundational protein models: language models and inverse folding.""" +"""Deprecated alias of :py:mod:`openprotein.models.foundation`. -from .ablang2 import AbLang2 -from .base import ProteinLanguageModel -from .esm1 import ESM1 -from .esm2 import ESM2 -from .esmc import ESMC -from .esmif1 import ESMIF1 -from .poet import PoET -from .poet2 import PoET2 -from .proteinmpnn import ProteinMPNN -from .protseq import ProtSeq -from .prott5 import ProtT5 -from .rotaprot import RotaProt +.. deprecated:: 0.19.0 + Use :py:mod:`openprotein.models.foundation`. This alias is removed in 0.20.0. +""" -__all__ = [ - "ESM1", - "ESM2", - "ESMC", - "ESMIF1", - "AbLang2", - "PoET", - "PoET2", - "ProtSeq", - "ProtT5", - "ProteinLanguageModel", - "ProteinMPNN", - "RotaProt", -] +from openprotein import _deprecation +from openprotein.models import foundation + +__all__ = list(foundation.__all__) + +__getattr__ = _deprecation.alias_package( + __name__, foundation, since="0.19.0", removed_in="0.20.0" +) diff --git a/openprotein/models/foundational/esmif1.py b/openprotein/models/foundational/esmif1.py deleted file mode 100644 index 17ad19f..0000000 --- a/openprotein/models/foundational/esmif1.py +++ /dev/null @@ -1,15 +0,0 @@ -"""ESM-IF1.""" - -from ._inverse_folding import _InverseFoldingModel - -__all__ = ["ESMIF1"] - - -class ESMIF1(_InverseFoldingModel): - """ESM-IF1, an inverse-folding model. - - It scores and designs sequences for a fixed backbone. Its checkpoint is - ``esm-if1``. - """ - - _default_id = "esm-if1" diff --git a/openprotein/models/foundational/poet2.py b/openprotein/models/foundational/poet2.py deleted file mode 100644 index b3bf2b1..0000000 --- a/openprotein/models/foundational/poet2.py +++ /dev/null @@ -1,212 +0,0 @@ -"""PoET-2.""" - -from typing import TYPE_CHECKING, Any - -from openprotein.common import Reduction -from openprotein.data.assaydataset import AssayDataset -from openprotein.jobs import futures - -from .. import _inputs -from ..model import _prepared, _text -from .poet import PoET - -if TYPE_CHECKING: - from openprotein.jobs.futures import GPFitFuture, SVDFitFuture, UMAPFitFuture - -__all__ = ["PoET2"] - - -class PoET2(PoET): - """PoET-2, a multi-modal protein language model conditioned on a protein family. - - Like PoET, every verb takes ``prompt``. Verbs other than ``indel`` also - take ``query``, a sequence, ``Protein``, ``Complex``, ``Query`` or query id, - sent as ``query_id``, which conditions on a protein's sequence or - structure. Its checkpoint is ``poet-2``. - """ - - _default_id = "poet-2" - - def embed( - self, - sequences: list[str] | list[bytes] | AssayDataset, - reduction: Reduction | None = "MEAN", - prompt: Any = None, - query: Any = None, - **params: Any, - ) -> futures.EmbeddingFuture: - """Embed sequences or an assay's (``batch/embeddings``); - ``reduction=None`` is per residue. - """ - sequences = _prepared(sequences) - return super().embed( - sequences, - reduction=reduction, - **self._conditioned( - params, prompt, query, method=("embed", "batch/embeddings") - ), - ) - - def logits( - self, - sequences: list[str] | list[bytes], - prompt: Any = None, - query: Any = None, - **params: Any, - ) -> futures.LogitsFuture: - """Per-position logits for sequences (``batch/logits``).""" - sequences = _prepared(sequences) - return super().logits( - sequences, - **self._conditioned( - params, prompt, query, method=("logits", "batch/logits") - ), - ) - - def attn( - self, - sequences: list[str] | list[bytes], - prompt: Any = None, - query: Any = None, - **params: Any, - ) -> futures.AttentionFuture: - """Attention maps for sequences (``batch/attn``).""" - sequences = _prepared(sequences) - return super().attn( - sequences, - **self._conditioned(params, prompt, query, method=("attn", "batch/attn")), - ) - - def score( - self, - sequences: list[str] | list[bytes], - prompt: Any = None, - query: Any = None, - **params: Any, - ) -> futures.LogLikelihoodFuture: - """Log-likelihoods of sequences (``batch/loglikelihood``).""" - sequences = _prepared(sequences) - return super().score( - sequences, - **self._conditioned( - params, prompt, query, method=("score", "batch/loglikelihood") - ), - ) - - def single_site( - self, - base_sequence: str | bytes, - prompt: Any = None, - query: Any = None, - **params: Any, - ) -> futures.SingleSiteScoreFuture: - """Score every single-site mutant of ``base_sequence`` (``single-site/scores``).""" - base_sequence = _text(base_sequence, "base_sequence") - return super().single_site( - base_sequence, - **self._conditioned( - params, prompt, query, method=("single_site", "single-site/*") - ), - ) - - def generate( - self, - prompt: Any = None, - query: Any = None, - design: Any = None, - **params: Any, - ) -> futures.SequenceGenerationFuture: - """Sample sequences (``generate/sequences``). - - ``query`` is one or a list. ``design``, an RFdiffusion or BoltzGen job or - its id, in any state, takes the place of ``query``: its designed - structures are the queries, and the job runs once the design has - finished. - """ - _inputs.check_inputs(params, prompt=prompt, query=query, design=design) - _inputs.check_one_structure_source(params, query, design) - self._method("generate", "generate/*") - many = _inputs.takes_list(self._params_schema("generate/sequences"), "query_id") - params = dict(params) - _inputs.with_param(params, "prompt_id", _inputs.prompt_id(prompt), "prompt") - _inputs.with_param( - params, - "query_id", - _inputs.query_ids(self.session, query, many=many), - "query", - ) - _inputs.with_param(params, "design_id", _inputs.design_id(design), "design") - return super().generate(**params) - - def fit_svd( - self, - sequences: list[str] | list[bytes] | None = None, - assay: Any = None, - n_components: int | None = None, - reduction: Reduction | None = None, - prompt: Any = None, - query: Any = None, - **params: Any, - ) -> "SVDFitFuture": - """Fit an SVD on this model's embeddings of ``sequences`` or an assay's.""" - _inputs.check_fit_source(sequences, assay) - sequences = _prepared(sequences) - return super().fit_svd( - sequences, - assay, - n_components=n_components, - reduction=reduction, - **self._conditioned(params, prompt, query, assay), - ) - - def fit_umap( - self, - sequences: list[str] | list[bytes] | None = None, - assay: Any = None, - n_components: int | None = None, - reduction: Reduction = "MEAN", - n_neighbors: int | None = None, - min_dist: float | None = None, - prompt: Any = None, - query: Any = None, - **params: Any, - ) -> "UMAPFitFuture": - """Fit a UMAP on this model's embeddings of ``sequences`` or an assay's.""" - _inputs.check_fit_source(sequences, assay) - sequences = _prepared(sequences) - return super().fit_umap( - sequences, - assay, - n_components=n_components, - reduction=reduction, - n_neighbors=n_neighbors, - min_dist=min_dist, - **self._conditioned(params, prompt, query, assay), - ) - - def fit_gp( - self, - assay: Any, - properties: list[str], - reduction: Reduction, - name: str | None = None, - description: str | None = None, - kernel: str = "rbf", - period: float | None = None, - alpha: float | None = None, - prompt: Any = None, - query: Any = None, - **params: Any, - ) -> "GPFitFuture": - """Train a Gaussian process on an assay's properties, featurized by this model.""" - return super().fit_gp( - assay, - properties, - reduction, - name=name, - description=description, - kernel=kernel, - period=period, - alpha=alpha, - **self._conditioned(params, prompt, query, assay), - ) diff --git a/openprotein/models/foundational/proteinmpnn.py b/openprotein/models/foundational/proteinmpnn.py deleted file mode 100644 index e959258..0000000 --- a/openprotein/models/foundational/proteinmpnn.py +++ /dev/null @@ -1,44 +0,0 @@ -"""ProteinMPNN.""" - -from typing import Any - -from openprotein.common import Reduction -from openprotein.data.assaydataset import AssayDataset -from openprotein.jobs import futures - -from ..model import _prepared -from ._inverse_folding import _InverseFoldingModel - -__all__ = ["ProteinMPNN"] - - -class ProteinMPNN(_InverseFoldingModel): - """ProteinMPNN, a message-passing inverse-folding model. - - It scores, embeds and designs sequences for a fixed backbone. Its - checkpoints are ``proteinmpnn``, the default, and ``solublempnn``, trained - on soluble proteins. - """ - - _default_id = "proteinmpnn" - - def embed( - self, - sequences: list[str] | list[bytes] | AssayDataset, - query: Any = None, - reduction: Reduction | None = "MEAN", - **params: Any, - ) -> futures.EmbeddingFuture: - """Embed sequences or an assay's on the query's backbone; - ``reduction=None`` is per residue. - """ - sequences = _prepared(sequences) - return super().embed( - sequences, - reduction=reduction, - **self._on_structure(params, query, method=("embed", "batch/embeddings")), - ) - - -class _SolubleMPNN(ProteinMPNN): - _default_id = "solublempnn" diff --git a/openprotein/models/generative/boltzgen.py b/openprotein/models/generative/boltzgen.py index 8b3fbe1..243ca24 100644 --- a/openprotein/models/generative/boltzgen.py +++ b/openprotein/models/generative/boltzgen.py @@ -1,5 +1,9 @@ """BoltzGen.""" +from typing import Any + +from openprotein.jobs import futures + from .base import StructureGenerativeModel __all__ = ["BoltzGen"] @@ -13,3 +17,53 @@ class BoltzGen(StructureGenerativeModel): """ _default_id = "boltzgen" + + def generate( + self, + query: Any = None, + *, + num_samples: int = 1, + diffusion_batch_size: int | None = None, + noise_scale: float | None = None, + step_scale: float | None = None, + random_seed: int | None = None, + **params: Any, + ) -> futures.StructureDesignFuture: + """Generate structures from a design query (``generate/structures``). + + Parameters + ---------- + query : Protein, Complex, Query or str, optional + The design query or its id. + num_samples : int + Designs to generate, at least 1. + diffusion_batch_size : int or None + Samples diffused in parallel, at least 1. ``None`` keeps the + model's setting. + noise_scale : float or None + Scaling factor for the noise schedule, in (0, 1]. ``None`` keeps + the model's setting. + step_scale : float or None + Scaling factor for diffusion steps, above 0. ``None`` keeps the + model's setting. + random_seed : int or None + Random seed, from 0 to 2**32. Runs are not reproducible, even + with a seed. + **params + Other params of the model's ``generate/structures`` method, sent + as given. + + Returns + ------- + StructureDesignFuture + The submitted structure-design job. + """ + return super().generate( + query, + num_samples=num_samples, + diffusion_batch_size=diffusion_batch_size, + noise_scale=noise_scale, + step_scale=step_scale, + random_seed=random_seed, + **params, + ) diff --git a/openprotein/models/generative/rfdiffusion.py b/openprotein/models/generative/rfdiffusion.py index c8cff19..008f31f 100644 --- a/openprotein/models/generative/rfdiffusion.py +++ b/openprotein/models/generative/rfdiffusion.py @@ -1,5 +1,9 @@ """RFdiffusion.""" +from typing import Any + +from openprotein.jobs import futures + from .base import StructureGenerativeModel __all__ = ["RFdiffusion"] @@ -13,3 +17,35 @@ class RFdiffusion(StructureGenerativeModel): """ _default_id = "rfdiffusion" + + def generate( + self, + query: Any = None, + *, + num_samples: int = 1, + random_seed: int | None = None, + **params: Any, + ) -> futures.StructureDesignFuture: + """Generate structures from a design query (``generate/structures``). + + Parameters + ---------- + query : Protein, Complex, Query or str, optional + The design query or its id. Masked positions are designed. + num_samples : int + Designs to generate, at least 1. + random_seed : int or None + Random seed, from 0 to 2**32. Runs are not reproducible, even + with a seed. + **params + Other params of the model's ``generate/structures`` method, sent + as given. + + Returns + ------- + StructureDesignFuture + The submitted structure-design job. + """ + return super().generate( + query, num_samples=num_samples, random_seed=random_seed, **params + ) diff --git a/openprotein/models/model.py b/openprotein/models/model.py index cc7608b..1acfc29 100644 --- a/openprotein/models/model.py +++ b/openprotein/models/model.py @@ -151,8 +151,12 @@ def _method(self, verb: str, path: str) -> MethodDescriptor: return method def _run(self, verb: str, path: str, **params: Any) -> Future: - """Submit the card's first method matching ``path`` for ``verb``.""" + """Submit the card's first method matching ``path`` for ``verb``. + + A ``None`` param is left to the server's default. + """ method = self._method(verb, path) + params = {name: value for name, value in params.items() if value is not None} job = _api.run_method(self.session, self.id, method.path, params) return _dispatch.create( self.session, diff --git a/openprotein/models/models.py b/openprotein/models/models.py index 6ab8e97..b540d97 100644 --- a/openprotein/models/models.py +++ b/openprotein/models/models.py @@ -9,9 +9,10 @@ from . import _api, estimators, gp, svd, umap from .ensemble import AlphaFlow, BioEmu, ESMFlow -from .folding import ( +from .fold import ( AlphaFold2, Boltz1, + Boltz1x, Boltz2, ESMFold, ESMFold2, @@ -21,7 +22,7 @@ ProtenixV2, RosettaFold3, ) -from .foundational import ( +from .foundation import ( ESM1, ESM2, ESMC, @@ -34,7 +35,7 @@ ProtT5, RotaProt, ) -from .foundational.proteinmpnn import _SolubleMPNN +from .foundation.proteinmpnn import _SolubleMPNN from .generative import BoltzGen, RFdiffusion from .gp import GPModel from .model import Model @@ -285,12 +286,12 @@ def boltz1(self) -> Boltz1: return self.boltz_1 @property - def boltz_1x(self) -> Boltz1: + def boltz_1x(self) -> Boltz1x: """``boltz-1x``.""" - return self._handle("boltz-1x", Boltz1) + return self._handle("boltz-1x", Boltz1x) @property - def boltz1x(self) -> Boltz1: + def boltz1x(self) -> Boltz1x: """``boltz-1x``.""" return self.boltz_1x diff --git a/openprotein/molecules/structure.py b/openprotein/molecules/structure.py index ee2d5e6..3aaf7af 100644 --- a/openprotein/molecules/structure.py +++ b/openprotein/molecules/structure.py @@ -1,14 +1,18 @@ import gzip -from collections.abc import Sequence +import string +from collections.abc import Mapping, Sequence from pathlib import Path from typing import Literal import gemmi +import numpy as np +import numpy.typing as npt import requests import openprotein.utils.cif as cif_utils from .complex import Complex +from .protein import _ATOM_TYPE_TO_IDX, Protein, _calc_rmsd_and_transform __all__ = ["Structure"] @@ -67,20 +71,7 @@ def from_filepath( path: Path | str, use_bfactor_as_plddt: bool | None = None, verbose: bool = True ) -> "Structure": path = Path(path) - if path.suffix == ".gz": - if path.name.endswith(".cif.gz"): - ext, format = ".cif.gz", "cif" - elif path.name.endswith(".pdb.gz"): - ext, format = ".pdb.gz", "pdb" - else: - raise ValueError(f"unsupported format: {path}") - with gzip.open(path, "rb") as f: - data = f.read() - else: - ext = path.suffix - format = ext.removeprefix(".") - assert format == "cif" or format == "pdb" - data = path.read_bytes() + data, format, ext = _read_structure_file(path) return Structure.from_string( filestring=data, format=format, @@ -143,11 +134,233 @@ def from_pdb_id(pdb_id: str, verbose: bool = True) -> "Structure": verbose=verbose, ).set_name(pdb_id) + @staticmethod + def from_xtc( + xtc_path: Path | str, + topology: Path | str, + verbose: bool = True, + ) -> "Structure": + """ + Creates a Structure with one model per frame of an XTC trajectory. + + Reads the chains, residues and atom names from the topology file, and the + coordinates from the trajectory. Each frame is then built with + ``Complex._from_structure_block``. + + Requires mdtraj (``pip install openprotein-python[xtc]``). + + Parameters + ---------- + xtc_path : Path or str + The XTC trajectory. + topology : Path or str + PDB or mmCIF file, optionally gzipped. Its atoms must be in the same order + as in the trajectory. Only the first model is used. + verbose : bool, optional + Whether to print warnings about the topology to stdout. Defaults to True. + + Returns + ------- + Structure + One :class:`Complex` per frame, with coordinates converted to Å from nm. + + Raises + ------ + ImportError + If mdtraj is not installed. + ValueError + If the topology and the trajectory have different numbers of atoms. + + Examples + -------- + >>> structure = Structure.from_xtc("md.xtc", "md_topology.pdb") + """ + try: + from mdtraj.formats import XTCTrajectoryFile + except ImportError as exc: + raise ImportError( + "mdtraj is not installed. Install it with openprotein-python[xtc] to read XTC files" + ) from exc + with XTCTrajectoryFile(str(xtc_path)) as file: + xyz, _, _, _ = file.read() + data, format, _ = _read_structure_file(Path(topology)) + block = cif_utils.StructureCIFBlock(filestring=data, format=format) + if len(block.structure) == 0: + raise ValueError(f"the topology {topology} has no atoms") + structure = block.structure + # PDB files from MD tools like GROMACS often have a blank chain id, which + # Complex._from_structure_block cannot read. Give each blank chain a chain id. + used = {chain.name for chain in structure[0]} + if "" in used: + free = ( + c + for c in string.ascii_uppercase + string.ascii_lowercase + if c not in used + ) + for chain in structure[0]: + if chain.name == "": + chain.name = next(free) + structure.assign_subchains(force=True) + structure.setup_entities() + structure.assign_label_seq_id() + atoms = [cra.atom for cra in structure[0].all()] + if xyz.shape[1] != len(atoms): + raise ValueError( + f"the topology has {len(atoms)} atoms and the trajectory has {xyz.shape[1]}" + ) + complexes: list[Complex] = [] + for frame in xyz.astype(np.float64) * 10.0: # nm to Å + for atom, position in zip(atoms, frame): + atom.pos = gemmi.Position(*position) + complexes.append( + Complex._from_structure_block( + structure_block=block, + use_bfactor_as_plddt=False, + model_idx=0, + verbose=verbose and not complexes, + ) + ) + return Structure(complexes, name=Path(xtc_path).name.removesuffix(".xtc")) + def copy(self) -> "Structure": return Structure( [complex.copy() for complex in self._complexes], name=self._name ) + def rmsf(self, passes: int = 1) -> npt.NDArray[np.float64]: + """ + Computes the RMSF of the alpha carbon of each residue over the models. + + Models are superposed on the first model and then on their mean, using the + alpha carbons present in all models. For multi-chain structures, all protein + chains are fitted together and their residues are joined in chain order. + + Parameters + ---------- + passes : int, optional + Number of times the models are superposed on their mean. Defaults to 1. + The app uses 2. + + Returns + ------- + np.ndarray + RMSF in Å, one value per residue. A residue with no alpha + carbon in some model has the value NaN. + + Raises + ------ + ValueError + If ``passes`` is less than 1, if there are fewer than two models, if the + models differ in their protein chains or residue counts, or if fewer than + three alpha carbons are present in every model. + AssertionError + If a model has a chain that is not a protein. + """ + if passes < 1: + raise ValueError(f"passes must be at least 1, got {passes}") + if len(self._complexes) < 2: + raise ValueError("rmsf needs at least two models") + models = self._get_protein_chains("rmsf") + alpha_carbons = np.array( + [ + np.concatenate( + [ + p.coordinates[:, _ATOM_TYPE_TO_IDX["CA"]] + for p in proteins.values() + ] + ) + for proteins in models + ], + dtype=np.float64, + ) + present = ~np.isnan(alpha_carbons).any(axis=(0, 2)) + if present.sum() < 3: + raise ValueError("rmsf needs at least three alpha carbons in every model") + fitted = alpha_carbons[:, present] + reference = fitted[0] + for _ in range(passes + 1): + for i, model in enumerate(fitted): + _, rotation, translation = _calc_rmsd_and_transform(reference, model) + fitted[i] = model @ rotation.T + translation + reference = fitted.mean(axis=0) + rmsf = np.full(present.shape, np.nan) + rmsf[present] = np.sqrt(((fitted - reference) ** 2).sum(axis=-1).mean(axis=0)) + return rmsf + + def phi_psi(self, max_bond: float = 2.0) -> npt.NDArray[np.float64]: + """ + Computes the backbone phi and psi angles of each residue in every model. + + To compute the phi/psi angle, the N, CA and C atoms of the residue and the + neighboring residue must be in the same chain, and at most max_bond Å between + the C and the N atom. Residues of protein chains are joined in chain order. + + Parameters + ---------- + max_bond : float + Longest distance in Å between the C and N atoms of neighbouring residues + that is read as a peptide bond. Defaults to 2. The app uses 2. + + Returns + ------- + np.ndarray + Angles in degrees, with shape (models, residues, 2). The last axis holds + phi and psi. An angle that is not defined has the value NaN. + + Raises + ------ + ValueError + If the models differ in their protein chains or residue counts. + AssertionError + If a model has a chain that is not a protein. + """ + models = self._get_protein_chains("phi_psi") + n_residues = sum(len(protein) for protein in models[0].values()) + angles = np.full((len(models), n_residues, 2), np.nan) + for i, proteins in enumerate(models): + start = 0 + for protein in proteins.values(): + n, ca, c = ( + protein.coordinates[:, _ATOM_TYPE_TO_IDX[atom]].astype(np.float64) + for atom in ("N", "CA", "C") + ) + # the same bond gives phi of a residue and psi of the one before it + bonded = np.linalg.norm(c[:-1] - n[1:], axis=1) <= max_bond + phi = np.where(bonded, _dihedral(c[:-1], n[1:], ca[1:], c[1:]), np.nan) + psi = np.where( + bonded, _dihedral(n[:-1], ca[:-1], c[:-1], n[1:]), np.nan + ) + angles[i, start + 1 : start + len(protein), 0] = phi + angles[i, start : start + len(protein) - 1, 1] = psi + start += len(protein) + return angles + + def _get_protein_chains(self, method: str) -> list[Mapping[str, Protein]]: + """ + Returns a chain id to Protein mapping for each model. + + Every chain of every model must be a Protein, and all models must have the + same chain ids and residue counts. ``method`` names the caller in the error + message. + """ + models = [] + for complex in self._complexes: + assert all( + isinstance(chain, Protein) for chain in complex.get_chains().values() + ), ( + f"{method} supported only for Protein chains, not supported for non-protein chains" + ) + models.append(complex.get_proteins()) + lengths = [len(protein) for protein in models[0].values()] + for proteins in models[1:]: + if proteins.keys() != models[0].keys() or lengths != [ + len(protein) for protein in proteins.values() + ]: + raise ValueError( + "all models must have the same protein chains and residue counts" + ) + return models + def _make_cif_string(self) -> str: structure = self._make_structure() block = structure.make_mmcif_block( @@ -213,6 +426,39 @@ def _make_structure(self) -> gemmi.Structure: return structure +def _read_structure_file(path: Path) -> tuple[bytes, Literal["cif", "pdb"], str]: + """Reads a (optionally, gzipped) cif or pdb file and returns its bytes, format and extension.""" + if path.suffix == ".gz": + if path.name.endswith(".cif.gz"): + ext, format = ".cif.gz", "cif" + elif path.name.endswith(".pdb.gz"): + ext, format = ".pdb.gz", "pdb" + else: + raise ValueError(f"unsupported format: {path}") + with gzip.open(path, "rb") as f: + data = f.read() + else: + ext = path.suffix + format = ext.removeprefix(".") + assert format == "cif" or format == "pdb" + data = path.read_bytes() + return data, format, ext + + +def _dihedral( + p0: npt.NDArray[np.float64], + p1: npt.NDArray[np.float64], + p2: npt.NDArray[np.float64], + p3: npt.NDArray[np.float64], +) -> npt.NDArray[np.float64]: + """Returns the dihedral angles in degrees, with the IUPAC sign, of four arrays of points with shape (n, 3).""" + b1, b2, b3 = p1 - p0, p2 - p1, p3 - p2 + n1, n2 = np.cross(b1, b2), np.cross(b2, b3) + y = np.linalg.norm(b2, axis=1) * (b1 * n2).sum(axis=1) + x = (n1 * n2).sum(axis=1) + return np.degrees(np.arctan2(y, x)) + + def _structure_has_no_atoms(structure: gemmi.Structure) -> bool: if len(structure) == 0: return True diff --git a/pyproject.toml b/pyproject.toml index cfdddf4..f0f52f9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -30,6 +30,7 @@ requires-python = ">=3.10,<3.15" [project.optional-dependencies] msa = ["pyarrow>=14"] +xtc = ["mdtraj>=1.10"] [dependency-groups] dev = [ @@ -47,6 +48,7 @@ dev = [ "jupyterlab>=4.4.1", "torch>=2.2.0,<3", "jsonschema>=4.26", + "mdtraj>=1.10", ] [tool.uv.sources] diff --git a/scripts/refresh_model_params.py b/scripts/refresh_model_params.py new file mode 100644 index 0000000..41d693b --- /dev/null +++ b/scripts/refresh_model_params.py @@ -0,0 +1,36 @@ +"""Refresh ``tests/data/models_params.json`` from the models API. + +Every listed system model's method params and outputs replace its entries. +Models the listing leaves out, and the ``fits`` schemas, are kept. + +Run: ``uv run python scripts/refresh_model_params.py``. +""" + +import json +from pathlib import Path +from typing import cast + +from openprotein import connect +from openprotein.models import ModelMetadata, _api + +FIXTURE = Path(__file__).parents[1] / "tests" / "data" / "models_params.json" + + +def main() -> None: + session = connect() + fixture = json.loads(FIXTURE.read_text()) + methods = fixture["methods"] + for card in cast(list[ModelMetadata], _api.list_models(session, verbose=True)): + prefix = f"{card.model_id}/" + for key in [key for key in methods if key.startswith(prefix)]: + del methods[key] + for method in card.methods: + methods[prefix + method.path] = { + "outputs": method.outputs, + "params": _api.get_method_params(session, card.model_id, method.path), + } + FIXTURE.write_text(json.dumps(fixture, indent=1, sort_keys=True) + "\n") + + +if __name__ == "__main__": + main() diff --git a/tests/data/models_params.json b/tests/data/models_params.json index d74c727..87f5506 100644 --- a/tests/data/models_params.json +++ b/tests/data/models_params.json @@ -651,7 +651,30 @@ "type": "object" } }, + "ablang2/single-site/scores": { + "outputs": [ + "score" + ], + "params": { + "additionalProperties": false, + "properties": { + "base_sequence": { + "description": "Sequence whose single substitutions are scored.", + "type": "string" + } + }, + "required": [ + "base_sequence" + ], + "type": "object" + } + }, "alphaflow-md-base-v1/batch/structures": { + "outputs": [ + "structures", + "plddt", + "confidence" + ], "params": { "$defs": { "FlowReference": { @@ -702,12 +725,12 @@ ], "description": "Unique chain identifier(s); a list for identical chains." }, - "sequence": { - "type": "string" - }, "msa_id": { "format": "uuid", "type": "string" + }, + "sequence": { + "type": "string" } }, "required": [ @@ -730,20 +753,18 @@ }, "type": "array" }, - "reference_structures": { + "msa_subsample": { "anyOf": [ { - "items": { - "$ref": "#/$defs/FlowReference" - }, - "type": "array" + "minimum": 2, + "type": "integer" }, { "type": "null" } ], "default": null, - "description": "Reference structures to use as templates, one per complex in complex order; null samples without a reference." + "description": "Caps the MSA depth the model reads; null keeps the checkpoint's default." }, "num_samples": { "default": 1, @@ -759,17 +780,11 @@ "minimum": 1, "type": "integer" }, - "tmax": { - "default": 1.0, - "description": "Noise level the flow starts from, in (0, 1].", - "exclusiveMinimum": 0, - "maximum": 1, - "type": "number" - }, - "msa_subsample": { + "random_seed": { "anyOf": [ { - "minimum": 2, + "maximum": 2147483647, + "minimum": 0, "type": "integer" }, { @@ -777,19 +792,22 @@ } ], "default": null, - "description": "Caps the MSA depth the model reads; null keeps the checkpoint's default." + "description": "Random seed; null for a random seed." }, - "self_cond": { + "reference_structures": { "anyOf": [ { - "type": "boolean" + "items": { + "$ref": "#/$defs/FlowReference" + }, + "type": "array" }, { "type": "null" } ], "default": null, - "description": "Feed each step's prediction back in as the next step's input; null uses the checkpoint's default." + "description": "Reference structures to use as templates, one per complex in complex order; null samples without a reference." }, "resample": { "anyOf": [ @@ -803,33 +821,38 @@ "default": null, "description": "Redraw the MSA clusters for each conformation; null uses the checkpoint's default." }, - "random_seed": { + "self_cond": { "anyOf": [ { - "maximum": 2147483647, - "minimum": 0, - "type": "integer" + "type": "boolean" }, { "type": "null" } ], "default": null, - "description": "Random seed; null for a random seed." + "description": "Feed each step's prediction back in as the next step's input; null uses the checkpoint's default." + }, + "tmax": { + "default": 1.0, + "description": "Noise level the flow starts from, in (0, 1].", + "exclusiveMinimum": 0, + "maximum": 1, + "type": "number" } }, "required": [ "complexes" ], "type": "object" - }, + } + }, + "alphaflow-md-distilled-v1/batch/structures": { "outputs": [ "structures", "plddt", "confidence" - ] - }, - "alphaflow-md-distilled-v1/batch/structures": { + ], "params": { "$defs": { "FlowReference": { @@ -880,12 +903,12 @@ ], "description": "Unique chain identifier(s); a list for identical chains." }, - "sequence": { - "type": "string" - }, "msa_id": { "format": "uuid", "type": "string" + }, + "sequence": { + "type": "string" } }, "required": [ @@ -908,20 +931,18 @@ }, "type": "array" }, - "reference_structures": { + "msa_subsample": { "anyOf": [ { - "items": { - "$ref": "#/$defs/FlowReference" - }, - "type": "array" + "minimum": 2, + "type": "integer" }, { "type": "null" } ], "default": null, - "description": "Reference structures to use as templates, one per complex in complex order; null samples without a reference." + "description": "Caps the MSA depth the model reads; null keeps the checkpoint's default." }, "num_samples": { "default": 1, @@ -937,17 +958,11 @@ "minimum": 1, "type": "integer" }, - "tmax": { - "default": 1.0, - "description": "Noise level the flow starts from, in (0, 1].", - "exclusiveMinimum": 0, - "maximum": 1, - "type": "number" - }, - "msa_subsample": { + "random_seed": { "anyOf": [ { - "minimum": 2, + "maximum": 2147483647, + "minimum": 0, "type": "integer" }, { @@ -955,19 +970,22 @@ } ], "default": null, - "description": "Caps the MSA depth the model reads; null keeps the checkpoint's default." + "description": "Random seed; null for a random seed." }, - "self_cond": { + "reference_structures": { "anyOf": [ { - "type": "boolean" + "items": { + "$ref": "#/$defs/FlowReference" + }, + "type": "array" }, { "type": "null" } ], "default": null, - "description": "Feed each step's prediction back in as the next step's input; null uses the checkpoint's default." + "description": "Reference structures to use as templates, one per complex in complex order; null samples without a reference." }, "resample": { "anyOf": [ @@ -981,31 +999,31 @@ "default": null, "description": "Redraw the MSA clusters for each conformation; null uses the checkpoint's default." }, - "random_seed": { + "self_cond": { "anyOf": [ { - "maximum": 2147483647, - "minimum": 0, - "type": "integer" + "type": "boolean" }, { "type": "null" } ], "default": null, - "description": "Random seed; null for a random seed." + "description": "Feed each step's prediction back in as the next step's input; null uses the checkpoint's default." + }, + "tmax": { + "default": 1.0, + "description": "Noise level the flow starts from, in (0, 1].", + "exclusiveMinimum": 0, + "maximum": 1, + "type": "number" } }, "required": [ "complexes" ], "type": "object" - }, - "outputs": [ - "structures", - "plddt", - "confidence" - ] + } }, "alphafold2/batch/structures": { "outputs": [ @@ -1124,6 +1142,9 @@ } }, "bioemu-v1-1/batch/structures": { + "outputs": [ + "structures" + ], "params": { "$defs": { "MsaProteinChain": { @@ -1162,9 +1183,6 @@ ], "description": "Unique chain identifier(s); a list for identical chains." }, - "sequence": { - "type": "string" - }, "msa_id": { "anyOf": [ { @@ -1176,6 +1194,9 @@ } ], "default": null + }, + "sequence": { + "type": "string" } }, "required": [ @@ -1197,12 +1218,6 @@ }, "type": "array" }, - "num_samples": { - "default": 1, - "description": "Conformations to sample per complex.", - "minimum": 1, - "type": "integer" - }, "denoiser": { "default": "dpm", "description": "Sampler for the reverse diffusion.", @@ -1218,6 +1233,12 @@ "description": "Drop samples that fail BioEmu's physicality checks, so a complex can come back with fewer models.", "type": "boolean" }, + "num_samples": { + "default": 1, + "description": "Conformations to sample per complex.", + "minimum": 1, + "type": "integer" + }, "random_seed": { "anyOf": [ { @@ -1237,10 +1258,7 @@ "complexes" ], "type": "object" - }, - "outputs": [ - "structures" - ] + } }, "boltz-1/batch/structures": { "outputs": [ @@ -1806,7 +1824,7 @@ } ], "default": null, - "description": "Random seed. Not used yet by this model, so runs are not reproducible." + "description": "Random seed; null for a random seed." }, "step_scale": { "default": 1.638, @@ -2389,7 +2407,7 @@ } ], "default": null, - "description": "Random seed. Not used yet by this model, so runs are not reproducible." + "description": "Random seed; null for a random seed." }, "step_scale": { "default": 1.638, @@ -3141,7 +3159,7 @@ } ], "default": null, - "description": "Random seed. Not used yet by this model, so runs are not reproducible." + "description": "Random seed; null for a random seed." }, "step_scale": { "default": 1.638, @@ -3463,6 +3481,24 @@ "type": "object" } }, + "esm1b_t33_650M_UR50S/single-site/scores": { + "outputs": [ + "score" + ], + "params": { + "additionalProperties": false, + "properties": { + "base_sequence": { + "description": "Sequence whose single substitutions are scored.", + "type": "string" + } + }, + "required": [ + "base_sequence" + ], + "type": "object" + } + }, "esm1v_t33_650M_UR90S_1/batch/attn": { "outputs": [ "attn" @@ -3560,6 +3596,24 @@ "type": "object" } }, + "esm1v_t33_650M_UR90S_1/single-site/scores": { + "outputs": [ + "score" + ], + "params": { + "additionalProperties": false, + "properties": { + "base_sequence": { + "description": "Sequence whose single substitutions are scored.", + "type": "string" + } + }, + "required": [ + "base_sequence" + ], + "type": "object" + } + }, "esm1v_t33_650M_UR90S_2/batch/attn": { "outputs": [ "attn" @@ -3657,6 +3711,24 @@ "type": "object" } }, + "esm1v_t33_650M_UR90S_2/single-site/scores": { + "outputs": [ + "score" + ], + "params": { + "additionalProperties": false, + "properties": { + "base_sequence": { + "description": "Sequence whose single substitutions are scored.", + "type": "string" + } + }, + "required": [ + "base_sequence" + ], + "type": "object" + } + }, "esm1v_t33_650M_UR90S_3/batch/attn": { "outputs": [ "attn" @@ -3754,6 +3826,24 @@ "type": "object" } }, + "esm1v_t33_650M_UR90S_3/single-site/scores": { + "outputs": [ + "score" + ], + "params": { + "additionalProperties": false, + "properties": { + "base_sequence": { + "description": "Sequence whose single substitutions are scored.", + "type": "string" + } + }, + "required": [ + "base_sequence" + ], + "type": "object" + } + }, "esm1v_t33_650M_UR90S_4/batch/attn": { "outputs": [ "attn" @@ -3851,6 +3941,24 @@ "type": "object" } }, + "esm1v_t33_650M_UR90S_4/single-site/scores": { + "outputs": [ + "score" + ], + "params": { + "additionalProperties": false, + "properties": { + "base_sequence": { + "description": "Sequence whose single substitutions are scored.", + "type": "string" + } + }, + "required": [ + "base_sequence" + ], + "type": "object" + } + }, "esm1v_t33_650M_UR90S_5/batch/attn": { "outputs": [ "attn" @@ -3948,6 +4056,24 @@ "type": "object" } }, + "esm1v_t33_650M_UR90S_5/single-site/scores": { + "outputs": [ + "score" + ], + "params": { + "additionalProperties": false, + "properties": { + "base_sequence": { + "description": "Sequence whose single substitutions are scored.", + "type": "string" + } + }, + "required": [ + "base_sequence" + ], + "type": "object" + } + }, "esm2_t12_35M_UR50D/batch/attn": { "outputs": [ "attn" @@ -4869,6 +4995,11 @@ } }, "esmflow-md-base-v1/batch/structures": { + "outputs": [ + "structures", + "plddt", + "confidence" + ], "params": { "$defs": { "FlowReference": { @@ -4944,21 +5075,6 @@ }, "type": "array" }, - "reference_structures": { - "anyOf": [ - { - "items": { - "$ref": "#/$defs/FlowReference" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Reference structures to use as templates, one per complex in complex order; null samples without a reference." - }, "num_samples": { "default": 1, "description": "Conformations to sample per complex.", @@ -4973,52 +5089,67 @@ "minimum": 1, "type": "integer" }, - "tmax": { - "default": 1.0, - "description": "Noise level the flow starts from, in (0, 1].", - "exclusiveMinimum": 0, - "maximum": 1, - "type": "number" + "random_seed": { + "anyOf": [ + { + "maximum": 2147483647, + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Random seed; null for a random seed." }, - "self_cond": { + "reference_structures": { "anyOf": [ { - "type": "boolean" + "items": { + "$ref": "#/$defs/FlowReference" + }, + "type": "array" }, { "type": "null" } ], "default": null, - "description": "Feed each step's prediction back in as the next step's input; null uses the checkpoint's default." + "description": "Reference structures to use as templates, one per complex in complex order; null samples without a reference." }, - "random_seed": { + "self_cond": { "anyOf": [ { - "maximum": 2147483647, - "minimum": 0, - "type": "integer" + "type": "boolean" }, { "type": "null" } ], "default": null, - "description": "Random seed; null for a random seed." + "description": "Feed each step's prediction back in as the next step's input; null uses the checkpoint's default." + }, + "tmax": { + "default": 1.0, + "description": "Noise level the flow starts from, in (0, 1].", + "exclusiveMinimum": 0, + "maximum": 1, + "type": "number" } }, "required": [ "complexes" ], "type": "object" - }, + } + }, + "esmflow-md-distilled-v1/batch/structures": { "outputs": [ "structures", "plddt", "confidence" - ] - }, - "esmflow-md-distilled-v1/batch/structures": { + ], "params": { "$defs": { "FlowReference": { @@ -5094,21 +5225,6 @@ }, "type": "array" }, - "reference_structures": { - "anyOf": [ - { - "items": { - "$ref": "#/$defs/FlowReference" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Reference structures to use as templates, one per complex in complex order; null samples without a reference." - }, "num_samples": { "default": 1, "description": "Conformations to sample per complex.", @@ -5123,50 +5239,60 @@ "minimum": 1, "type": "integer" }, - "tmax": { - "default": 1.0, - "description": "Noise level the flow starts from, in (0, 1].", - "exclusiveMinimum": 0, - "maximum": 1, - "type": "number" + "random_seed": { + "anyOf": [ + { + "maximum": 2147483647, + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Random seed; null for a random seed." }, - "self_cond": { + "reference_structures": { "anyOf": [ { - "type": "boolean" + "items": { + "$ref": "#/$defs/FlowReference" + }, + "type": "array" }, { "type": "null" } ], "default": null, - "description": "Feed each step's prediction back in as the next step's input; null uses the checkpoint's default." + "description": "Reference structures to use as templates, one per complex in complex order; null samples without a reference." }, - "random_seed": { + "self_cond": { "anyOf": [ { - "maximum": 2147483647, - "minimum": 0, - "type": "integer" + "type": "boolean" }, { "type": "null" } ], "default": null, - "description": "Random seed; null for a random seed." + "description": "Feed each step's prediction back in as the next step's input; null uses the checkpoint's default." + }, + "tmax": { + "default": 1.0, + "description": "Noise level the flow starts from, in (0, 1].", + "exclusiveMinimum": 0, + "maximum": 1, + "type": "number" } }, "required": [ "complexes" ], "type": "object" - }, - "outputs": [ - "structures", - "plddt", - "confidence" - ] + } }, "esmfold/batch/structures": { "outputs": [ @@ -5895,464 +6021,614 @@ "type": "object" } }, - "poet-2/batch/embeddings": { + "opendde-abag/batch/structures": { "outputs": [ - "embeddings" + "structures", + "plddt", + "pae", + "pde", + "confidence", + "ipae" ], "params": { - "additionalProperties": false, - "properties": { - "assay_id": { - "anyOf": [ - { - "format": "uuid", - "type": "string" + "$defs": { + "Chain": { + "additionalProperties": false, + "properties": { + "dna": { + "anyOf": [ + { + "$ref": "#/$defs/DNA" + }, + { + "type": "null" + } + ], + "default": null }, - { - "type": "null" - } - ], - "default": null, - "description": "ID of an assay whose sequences to run, in place of `sequences`." - }, - "decoder_type": { - "anyOf": [ - { - "enum": [ - "mlm", - "clm" + "ion": { + "anyOf": [ + { + "$ref": "#/$defs/Ion" + }, + { + "type": "null" + } ], - "type": "string" + "default": null }, - { - "type": "null" - } - ], - "default": null, - "description": "Decoder to read out; null is the MLM decoder." - }, - "prompt_id": { - "anyOf": [ - { - "type": "string" + "ligand": { + "anyOf": [ + { + "$ref": "#/$defs/Ligand" + }, + { + "type": "null" + } + ], + "default": null }, - { - "type": "null" + "protein": { + "anyOf": [ + { + "$ref": "#/$defs/ProteinWithMSA" + }, + { + "type": "null" + } + ], + "default": null + }, + "rna": { + "anyOf": [ + { + "$ref": "#/$defs/RNA" + }, + { + "type": "null" + } + ], + "default": null } - ], - "default": null, - "description": "ID of the prompt to condition on; null runs unconditioned." + }, + "type": "object" }, - "query_id": { - "anyOf": [ - { - "format": "uuid", - "type": "string" + "DNA": { + "additionalProperties": false, + "description": "DNA chain to fold.", + "properties": { + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "description": "Unique chain identifier(s); a list for identical chains." }, - { - "type": "null" + "sequence": { + "type": "string" } + }, + "required": [ + "id", + "sequence" ], - "default": null, - "description": "ID of the query to condition on. Each sequence must have the query's chains, ':'-delimited, with as many residues in each once gaps are dropped." + "type": "object" }, - "reduction": { - "anyOf": [ - { - "enum": [ - "MEAN", - "SUM" - ], + "Ion": { + "additionalProperties": false, + "properties": { + "ccd": { "type": "string" }, - { - "type": "null" + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "description": "Unique chain identifier(s); a list for identical chains." } + }, + "required": [ + "id", + "ccd" ], - "default": null, - "description": "Pool each sequence's embedding over its residues; null keeps one row per residue." + "type": "object" }, - "sequences": { - "anyOf": [ - { - "items": { - "type": "string" - }, - "type": "array" + "Ligand": { + "additionalProperties": false, + "description": "Small-molecule ligand, given as exactly one of SMILES or CCD code.", + "properties": { + "ccd": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null }, - { - "type": "null" + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "description": "Unique chain identifier(s); a list for identical chains." + }, + "smiles": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null } + }, + "required": [ + "id" ], - "default": null, - "description": "Sequences to run. Use ':' to delimit chains. Null with `assay_id`." + "type": "object" }, - "use_query_structure_in_decoder": { - "default": true, - "description": "Give the decoder the query's structure alongside each sequence. Ignored without a query.", - "type": "boolean" - } - }, - "type": "object" - } - }, - "poet-2/batch/logits": { - "outputs": [ - "logits" - ], - "params": { - "additionalProperties": false, - "properties": { - "decoder_type": { - "anyOf": [ - { - "enum": [ - "mlm", - "clm" + "ProteinWithMSA": { + "additionalProperties": false, + "description": "Protein chain to fold, with an optional MSA.", + "properties": { + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } ], - "type": "string" + "description": "Unique chain identifier(s); a list for identical chains." }, - { - "type": "null" + "msa_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + }, + "sequence": { + "type": "string" } + }, + "required": [ + "id", + "sequence" ], - "default": null, - "description": "Decoder to read out; null is the MLM decoder." + "type": "object" }, - "prompt_id": { - "anyOf": [ - { - "type": "string" + "RNA": { + "additionalProperties": false, + "properties": { + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "description": "Unique chain identifier(s); a list for identical chains." }, - { - "type": "null" + "sequence": { + "type": "string" } + }, + "required": [ + "id", + "sequence" ], - "default": null, - "description": "ID of the prompt to condition on; null runs unconditioned." + "type": "object" + } + }, + "additionalProperties": false, + "properties": { + "allow_msa_seed_mismatch": { + "default": false, + "description": "Fold a protein against an MSA built for a different sequence of the same length, such as a point mutant against its wild-type MSA.", + "type": "boolean" }, - "query_id": { + "complexes": { + "description": "Complexes to fold. Each complex is a list of chain entities.", + "items": { + "items": { + "$ref": "#/$defs/Chain" + }, + "type": "array" + }, + "type": "array" + }, + "num_recycles": { + "default": 10, + "description": "Number of recycling steps to use.", + "minimum": 1, + "type": "integer" + }, + "num_samples": { + "default": 1, + "description": "Number of samples to generate.", + "minimum": 1, + "type": "integer" + }, + "num_steps": { + "default": 200, + "description": "Number of sampling steps to use.", + "minimum": 1, + "type": "integer" + }, + "random_seed": { "anyOf": [ { - "format": "uuid", - "type": "string" + "maximum": 2147483647, + "minimum": 0, + "type": "integer" }, { "type": "null" } ], "default": null, - "description": "ID of the query to condition on. Each sequence must have the query's chains, ':'-delimited, with as many residues in each once gaps are dropped." - }, - "sequences": { - "description": "Sequences to run. Use ':' to delimit chains.", - "items": { - "type": "string" - }, - "type": "array" - }, - "use_query_structure_in_decoder": { - "default": true, - "description": "Give the decoder the query's structure alongside each sequence. Ignored without a query.", - "type": "boolean" + "description": "Random seed; null for a random seed." } }, "required": [ - "sequences" + "complexes" ], "type": "object" } }, - "poet-2/batch/loglikelihood": { + "opendde/batch/structures": { "outputs": [ - "loglikelihood" + "structures", + "plddt", + "pae", + "pde", + "confidence", + "ipae" ], "params": { - "additionalProperties": false, - "properties": { - "decoder_type": { - "anyOf": [ - { - "const": "clm", - "type": "string" + "$defs": { + "Chain": { + "additionalProperties": false, + "properties": { + "dna": { + "anyOf": [ + { + "$ref": "#/$defs/DNA" + }, + { + "type": "null" + } + ], + "default": null }, - { - "type": "null" - } - ], - "default": null, - "description": "Scoring always reads the CLM decoder." - }, - "prompt_id": { - "anyOf": [ - { - "type": "string" + "ion": { + "anyOf": [ + { + "$ref": "#/$defs/Ion" + }, + { + "type": "null" + } + ], + "default": null }, - { - "type": "null" - } - ], - "default": null, - "description": "ID of the prompt to condition on; null runs unconditioned." - }, - "query_id": { - "anyOf": [ - { - "format": "uuid", - "type": "string" + "ligand": { + "anyOf": [ + { + "$ref": "#/$defs/Ligand" + }, + { + "type": "null" + } + ], + "default": null }, - { - "type": "null" + "protein": { + "anyOf": [ + { + "$ref": "#/$defs/ProteinWithMSA" + }, + { + "type": "null" + } + ], + "default": null + }, + "rna": { + "anyOf": [ + { + "$ref": "#/$defs/RNA" + }, + { + "type": "null" + } + ], + "default": null } - ], - "default": null, - "description": "ID of the query to condition on. Each sequence must have the query's chains, ':'-delimited, with as many residues in each once gaps are dropped." - }, - "sequences": { - "description": "Sequences to run. Use ':' to delimit chains.", - "items": { - "type": "string" }, - "type": "array" + "type": "object" }, - "use_query_structure_in_decoder": { - "default": true, - "description": "Give the decoder the query's structure alongside each sequence. Ignored without a query.", - "type": "boolean" - } - }, - "required": [ - "sequences" - ], - "type": "object" - } - }, - "poet-2/generate/sequences": { - "outputs": [ - "sequences", - "loglikelihood" - ], - "params": { - "additionalProperties": false, - "properties": { - "design_id": { - "anyOf": [ - { - "format": "uuid", - "type": "string" + "DNA": { + "additionalProperties": false, + "description": "DNA chain to fold.", + "properties": { + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "description": "Unique chain identifier(s); a list for identical chains." }, - { - "type": "null" + "sequence": { + "type": "string" } + }, + "required": [ + "id", + "sequence" ], - "default": null, - "description": "ID of an RFdiffusion or BoltzGen design job whose structures are the queries, in place of query_id. The job runs once the design has finished." + "type": "object" }, - "ensemble_method": { - "anyOf": [ - { - "enum": [ - "arithmetic", - "geometric" - ], + "Ion": { + "additionalProperties": false, + "properties": { + "ccd": { "type": "string" }, - { - "type": "null" + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "description": "Unique chain identifier(s); a list for identical chains." } + }, + "required": [ + "id", + "ccd" ], - "default": null, - "description": "How replicate likelihoods combine; null is arithmetic." + "type": "object" }, - "ensemble_weights": { - "anyOf": [ - { - "items": { - "type": "number" - }, - "type": "array" + "Ligand": { + "additionalProperties": false, + "description": "Small-molecule ligand, given as exactly one of SMILES or CCD code.", + "properties": { + "ccd": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null }, - { - "type": "null" + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "description": "Unique chain identifier(s); a list for identical chains." + }, + "smiles": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null } + }, + "required": [ + "id" ], - "default": null, - "description": "Weight of each prompt replicate's likelihood when sampling." - }, - "max_length": { - "default": 1000, - "description": "Maximum residues in a sample.", - "maximum": 16000, - "minimum": 1, - "type": "integer" - }, - "num_samples": { - "default": 100, - "description": "Number of samples.", - "minimum": 1, - "type": "integer" - }, - "prompt_id": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "ID of the prompt to condition on; null runs unconditioned." + "type": "object" }, - "query_id": { - "anyOf": [ - { - "format": "uuid", - "type": "string" + "ProteinWithMSA": { + "additionalProperties": false, + "description": "Protein chain to fold, with an optional MSA.", + "properties": { + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "description": "Unique chain identifier(s); a list for identical chains." }, - { - "items": { - "format": "uuid", - "type": "string" - }, - "type": "array" + "msa_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null }, - { - "type": "null" + "sequence": { + "type": "string" } + }, + "required": [ + "id", + "sequence" ], - "default": null, - "description": "Query, or queries, to sample against; each query takes num_samples. A sample spans its query, so max_length does not apply." + "type": "object" }, - "random_seed": { - "anyOf": [ - { - "maximum": 4294967295, - "minimum": 0, - "type": "integer" + "RNA": { + "additionalProperties": false, + "properties": { + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "description": "Unique chain identifier(s); a list for identical chains." }, - { - "type": "null" + "sequence": { + "type": "string" } + }, + "required": [ + "id", + "sequence" ], - "default": null, - "description": "Random seed; sample i draws with (seed + i) mod 2^32. Null for a random seed." - }, - "temperature": { - "default": 1.0, - "description": "Sampling temperature.", - "maximum": 1000000.0, - "minimum": 1e-06, - "type": "number" - }, - "top_k": { - "default": 20, - "description": "Sample from the k likeliest tokens; 0 for all.", - "minimum": 0, - "type": "integer" - }, - "top_p": { - "default": 1.0, - "description": "Sample from the smallest set of tokens this likely; 1 for all.", - "maximum": 1, - "minimum": 0, - "type": "number" - }, - "use_query_structure_in_decoder": { - "default": true, - "description": "Give the decoder the query's structure alongside each sequence. Ignored without a query.", - "type": "boolean" + "type": "object" } }, - "type": "object" - } - }, - "poet-2/indel/scores": { - "outputs": [ - "score" - ], - "params": { "additionalProperties": false, "properties": { - "base_sequence": { - "description": "Sequence whose variants are scored, ':' delimiting chains.", - "type": "string" + "allow_msa_seed_mismatch": { + "default": false, + "description": "Fold a protein against an MSA built for a different sequence of the same length, such as a point mutant against its wild-type MSA.", + "type": "boolean" }, - "decoder_type": { - "anyOf": [ - { - "const": "clm", - "type": "string" + "complexes": { + "description": "Complexes to fold. Each complex is a list of chain entities.", + "items": { + "items": { + "$ref": "#/$defs/Chain" }, - { - "type": "null" - } - ], - "default": null, - "description": "Scoring always reads the CLM decoder." + "type": "array" + }, + "type": "array" }, - "delete": { - "anyOf": [ - { - "items": { - "minimum": 0, - "type": "integer" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Sizes of the fragment deleted at each site." + "num_recycles": { + "default": 10, + "description": "Number of recycling steps to use.", + "minimum": 1, + "type": "integer" }, - "insert": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Fragment inserted at, or in place of, each site." + "num_samples": { + "default": 1, + "description": "Number of samples to generate.", + "minimum": 1, + "type": "integer" }, - "prompt_id": { + "num_steps": { + "default": 200, + "description": "Number of sampling steps to use.", + "minimum": 1, + "type": "integer" + }, + "random_seed": { "anyOf": [ { - "type": "string" + "maximum": 2147483647, + "minimum": 0, + "type": "integer" }, { "type": "null" } ], "default": null, - "description": "ID of the prompt to condition on; null runs unconditioned." + "description": "Random seed; null for a random seed." } }, "required": [ - "base_sequence" + "complexes" ], "type": "object" } }, - "poet-2/single-site/scores": { + "poet-2/batch/attn": { "outputs": [ - "score" + "attn" ], "params": { "additionalProperties": false, "properties": { - "base_sequence": { - "description": "Sequence whose variants are scored, ':' delimiting chains.", - "type": "string" - }, "decoder_type": { "anyOf": [ { - "const": "clm", + "enum": [ + "mlm", + "clm" + ], "type": "string" }, { @@ -6360,12 +6636,7 @@ } ], "default": null, - "description": "Scoring always reads the CLM decoder." - }, - "include_gaps": { - "default": false, - "description": "Include gap substitutions and scan gap positions.", - "type": "boolean" + "description": "Decoder to read out; null is the MLM decoder." }, "prompt_id": { "anyOf": [ @@ -6392,6 +6663,13 @@ "default": null, "description": "ID of the query to condition on. Each sequence must have the query's chains, ':'-delimited, with as many residues in each once gaps are dropped." }, + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + }, "use_query_structure_in_decoder": { "default": true, "description": "Give the decoder the query's structure alongside each sequence. Ignored without a query.", @@ -6399,12 +6677,12 @@ } }, "required": [ - "base_sequence" + "sequences" ], "type": "object" } }, - "poet/batch/embeddings": { + "poet-2/batch/embeddings": { "outputs": [ "embeddings" ], @@ -6424,7 +6702,23 @@ "default": null, "description": "ID of an assay whose sequences to run, in place of `sequences`." }, - "prompt_id": { + "decoder_type": { + "anyOf": [ + { + "enum": [ + "mlm", + "clm" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Decoder to read out; null is the MLM decoder." + }, + "prompt_id": { "anyOf": [ { "type": "string" @@ -6436,6 +6730,19 @@ "default": null, "description": "ID of the prompt to condition on; null runs unconditioned." }, + "query_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of the query to condition on. Each sequence must have the query's chains, ':'-delimited, with as many residues in each once gaps are dropped." + }, "reduction": { "anyOf": [ { @@ -6466,18 +6773,39 @@ ], "default": null, "description": "Sequences to run. Use ':' to delimit chains. Null with `assay_id`." + }, + "use_query_structure_in_decoder": { + "default": true, + "description": "Give the decoder the query's structure alongside each sequence. Ignored without a query.", + "type": "boolean" } }, "type": "object" } }, - "poet/batch/logits": { + "poet-2/batch/logits": { "outputs": [ "logits" ], "params": { "additionalProperties": false, "properties": { + "decoder_type": { + "anyOf": [ + { + "enum": [ + "mlm", + "clm" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Decoder to read out; null is the MLM decoder." + }, "prompt_id": { "anyOf": [ { @@ -6490,12 +6818,30 @@ "default": null, "description": "ID of the prompt to condition on; null runs unconditioned." }, + "query_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of the query to condition on. Each sequence must have the query's chains, ':'-delimited, with as many residues in each once gaps are dropped." + }, "sequences": { "description": "Sequences to run. Use ':' to delimit chains.", "items": { "type": "string" }, "type": "array" + }, + "use_query_structure_in_decoder": { + "default": true, + "description": "Give the decoder the query's structure alongside each sequence. Ignored without a query.", + "type": "boolean" } }, "required": [ @@ -6504,13 +6850,26 @@ "type": "object" } }, - "poet/batch/loglikelihood": { + "poet-2/batch/loglikelihood": { "outputs": [ "loglikelihood" ], "params": { "additionalProperties": false, "properties": { + "decoder_type": { + "anyOf": [ + { + "const": "clm", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Scoring always reads the CLM decoder." + }, "prompt_id": { "anyOf": [ { @@ -6523,12 +6882,30 @@ "default": null, "description": "ID of the prompt to condition on; null runs unconditioned." }, + "query_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of the query to condition on. Each sequence must have the query's chains, ':'-delimited, with as many residues in each once gaps are dropped." + }, "sequences": { "description": "Sequences to run. Use ':' to delimit chains.", "items": { "type": "string" }, "type": "array" + }, + "use_query_structure_in_decoder": { + "default": true, + "description": "Give the decoder the query's structure alongside each sequence. Ignored without a query.", + "type": "boolean" } }, "required": [ @@ -6537,7 +6914,7 @@ "type": "object" } }, - "poet/generate/sequences": { + "poet-2/generate/sequences": { "outputs": [ "sequences", "loglikelihood" @@ -6545,10 +6922,54 @@ "params": { "additionalProperties": false, "properties": { + "design_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of an RFdiffusion or BoltzGen design job whose structures are the queries, in place of query_id. The job runs once the design has finished." + }, + "ensemble_method": { + "anyOf": [ + { + "enum": [ + "arithmetic", + "geometric" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "How replicate likelihoods combine; null is arithmetic." + }, + "ensemble_weights": { + "anyOf": [ + { + "items": { + "type": "number" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Weight of each prompt replicate's likelihood when sampling." + }, "max_length": { "default": 1000, - "description": "A sample holds at most max_length + 1 residues.", - "maximum": 15999, + "description": "Maximum residues in a sample.", + "maximum": 16000, "minimum": 1, "type": "integer" }, @@ -6559,8 +6980,36 @@ "type": "integer" }, "prompt_id": { - "description": "ID of the prompt to sample from.", - "type": "string" + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of the prompt to condition on; null runs unconditioned." + }, + "query_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "items": { + "format": "uuid", + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Query, or queries, to sample against; each query takes num_samples. A sample spans its query, so max_length does not apply." }, "random_seed": { "anyOf": [ @@ -6595,15 +7044,17 @@ "maximum": 1, "minimum": 0, "type": "number" + }, + "use_query_structure_in_decoder": { + "default": true, + "description": "Give the decoder the query's structure alongside each sequence. Ignored without a query.", + "type": "boolean" } }, - "required": [ - "prompt_id" - ], "type": "object" } }, - "poet/indel/scores": { + "poet-2/indel/scores": { "outputs": [ "score" ], @@ -6614,6 +7065,19 @@ "description": "Sequence whose variants are scored, ':' delimiting chains.", "type": "string" }, + "decoder_type": { + "anyOf": [ + { + "const": "clm", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Scoring always reads the CLM decoder." + }, "delete": { "anyOf": [ { @@ -6661,7 +7125,7 @@ "type": "object" } }, - "poet/single-site/scores": { + "poet-2/single-site/scores": { "outputs": [ "score" ], @@ -6672,6 +7136,19 @@ "description": "Sequence whose variants are scored, ':' delimiting chains.", "type": "string" }, + "decoder_type": { + "anyOf": [ + { + "const": "clm", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Scoring always reads the CLM decoder." + }, "include_gaps": { "default": false, "description": "Include gap substitutions and scan gap positions.", @@ -6688,6 +7165,24 @@ ], "default": null, "description": "ID of the prompt to condition on; null runs unconditioned." + }, + "query_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of the query to condition on. Each sequence must have the query's chains, ':'-delimited, with as many residues in each once gaps are dropped." + }, + "use_query_structure_in_decoder": { + "default": true, + "description": "Give the decoder the query's structure alongside each sequence. Ignored without a query.", + "type": "boolean" } }, "required": [ @@ -6696,45 +7191,9 @@ "type": "object" } }, - "prot-seq/batch/attn": { + "poet/batch/embeddings": { "outputs": [ - "attn" - ], - "params": { - "additionalProperties": false, - "properties": { - "chain_linker": { - "default": "GGGGSGGGGSGGGGS", - "description": "Linker joining chains when `chain_mode` is 'linker'.", - "type": "string" - }, - "chain_mode": { - "default": "linker", - "description": "Join a sequence's ':'-delimited chains with `chain_linker`, or embed each chain on its own.", - "enum": [ - "linker", - "independent" - ], - "type": "string" - }, - "sequences": { - "description": "Sequences to run. Use ':' to delimit chains.", - "items": { - "maxLength": 3072, - "type": "string" - }, - "type": "array" - } - }, - "required": [ - "sequences" - ], - "type": "object" - } - }, - "prot-seq/batch/embeddings": { - "outputs": [ - "embeddings" + "embeddings" ], "params": { "additionalProperties": false, @@ -6752,19 +7211,17 @@ "default": null, "description": "ID of an assay whose sequences to run, in place of `sequences`." }, - "chain_linker": { - "default": "GGGGSGGGGSGGGGS", - "description": "Linker joining chains when `chain_mode` is 'linker'.", - "type": "string" - }, - "chain_mode": { - "default": "linker", - "description": "Join a sequence's ':'-delimited chains with `chain_linker`, or embed each chain on its own.", - "enum": [ - "linker", - "independent" + "prompt_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } ], - "type": "string" + "default": null, + "description": "ID of the prompt to condition on; null runs unconditioned." }, "reduction": { "anyOf": [ @@ -6801,26 +7258,24 @@ "type": "object" } }, - "prot-seq/batch/logits": { + "poet/batch/logits": { "outputs": [ "logits" ], "params": { "additionalProperties": false, "properties": { - "chain_linker": { - "default": "GGGGSGGGGSGGGGS", - "description": "Linker joining chains when `chain_mode` is 'linker'.", - "type": "string" - }, - "chain_mode": { - "default": "linker", - "description": "Join a sequence's ':'-delimited chains with `chain_linker`, or embed each chain on its own.", - "enum": [ - "linker", - "independent" + "prompt_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } ], - "type": "string" + "default": null, + "description": "ID of the prompt to condition on; null runs unconditioned." }, "sequences": { "description": "Sequences to run. Use ':' to delimit chains.", @@ -6836,41 +7291,16 @@ "type": "object" } }, - "proteinmpnn/batch/embeddings": { + "poet/batch/loglikelihood": { "outputs": [ - "embeddings" + "loglikelihood" ], "params": { "additionalProperties": false, "properties": { - "ca_only": { - "default": false, - "description": "Use the CA-only model.", - "type": "boolean" - }, - "model_name": { - "default": "v_48_020", - "description": "Model weights version.", - "enum": [ - "v_48_002", - "v_48_010", - "v_48_020", - "v_48_030" - ], - "type": "string" - }, - "query_id": { - "description": "ID of a query (sequence or structure) to condition on.", - "format": "uuid", - "type": "string" - }, - "reduction": { + "prompt_id": { "anyOf": [ { - "enum": [ - "MEAN", - "SUM" - ], "type": "string" }, { @@ -6878,174 +7308,165 @@ } ], "default": null, - "description": "Pool each sequence's embedding over its residues; null keeps one row per residue." + "description": "ID of the prompt to condition on; null runs unconditioned." }, "sequences": { - "description": "Sequences to embed, one ':'-delimited segment per query chain in chain-id order.", + "description": "Sequences to run. Use ':' to delimit chains.", "items": { "type": "string" }, - "minItems": 1, "type": "array" - }, - "soluble_model": { - "default": false, - "description": "Use the soluble model. Always on for solublempnn.", - "type": "boolean" } }, "required": [ - "query_id", "sequences" ], "type": "object" } }, - "proteinmpnn/batch/loglikelihood": { + "poet/generate/sequences": { "outputs": [ + "sequences", "loglikelihood" ], "params": { "additionalProperties": false, "properties": { - "ca_only": { - "default": false, - "description": "Use the CA-only model.", - "type": "boolean" - }, - "decoding_orders": { - "default": 1, - "description": "Random decoding orders to average each score over.", - "maximum": 10, + "max_length": { + "default": 1000, + "description": "A sample holds at most max_length + 1 residues.", + "maximum": 15999, "minimum": 1, "type": "integer" }, - "model_name": { - "default": "v_48_020", - "description": "Model weights version.", - "enum": [ - "v_48_002", - "v_48_010", - "v_48_020", - "v_48_030" - ], - "type": "string" + "num_samples": { + "default": 100, + "description": "Number of samples.", + "minimum": 1, + "type": "integer" }, - "query_id": { - "description": "ID of a query (sequence or structure) to condition on.", - "format": "uuid", + "prompt_id": { + "description": "ID of the prompt to sample from.", "type": "string" }, "random_seed": { - "default": 1, - "description": "Random seed picking the decoding orders.", - "maximum": 4294967296, - "minimum": 1, - "type": "integer" + "anyOf": [ + { + "maximum": 4294967295, + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Random seed; sample i draws with (seed + i) mod 2^32. Null for a random seed." }, - "sequences": { - "description": "Sequences to score, one ':'-delimited segment per query chain in chain-id order.", - "items": { - "type": "string" - }, - "minItems": 1, - "type": "array" + "temperature": { + "default": 1.0, + "description": "Sampling temperature.", + "maximum": 1000000.0, + "minimum": 1e-06, + "type": "number" }, - "soluble_model": { - "default": false, - "description": "Use the soluble model. Always on for solublempnn.", - "type": "boolean" + "top_k": { + "default": 20, + "description": "Sample from the k likeliest tokens; 0 for all.", + "minimum": 0, + "type": "integer" + }, + "top_p": { + "default": 1.0, + "description": "Sample from the smallest set of tokens this likely; 1 for all.", + "maximum": 1, + "minimum": 0, + "type": "number" } }, "required": [ - "query_id", - "sequences" + "prompt_id" ], "type": "object" } }, - "proteinmpnn/generate/sequences": { + "poet/indel/scores": { "outputs": [ - "sequences", - "loglikelihood" + "score" ], "params": { "additionalProperties": false, "properties": { - "aa_bias_global": { - "anyOf": [ - { - "additionalProperties": { - "type": "number" - }, - "type": "object" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Logit bias per amino acid, at every position." + "base_sequence": { + "description": "Sequence whose variants are scored, ':' delimiting chains.", + "type": "string" }, - "aa_bias_per_position": { + "delete": { "anyOf": [ { - "additionalProperties": { - "items": { - "items": { - "type": "number" - }, - "type": "array" - }, - "type": "array" + "items": { + "minimum": 0, + "type": "integer" }, - "type": "object" + "type": "array" }, { "type": "null" } ], "default": null, - "description": "Per chain, one 21-element logit bias row per residue." + "description": "Sizes of the fragment deleted at each site." }, - "backbone_noise": { + "insert": { "anyOf": [ { - "maximum": 10, - "minimum": 0, - "type": "number" + "type": "string" }, { "type": "null" } ], "default": null, - "description": "Gaussian noise (Angstrom) added to backbone atoms." - }, - "ca_only": { - "default": false, - "description": "Use the CA-only model.", - "type": "boolean" + "description": "Fragment inserted at, or in place of, each site." }, - "chains_to_design": { + "prompt_id": { "anyOf": [ { - "items": { - "type": "string" - }, - "type": "array" + "type": "string" }, { "type": "null" } ], "default": null, - "description": "Chains to redesign; others are kept fixed." - }, - "design_id": { + "description": "ID of the prompt to condition on; null runs unconditioned." + } + }, + "required": [ + "base_sequence" + ], + "type": "object" + } + }, + "poet/single-site/scores": { + "outputs": [ + "score" + ], + "params": { + "additionalProperties": false, + "properties": { + "base_sequence": { + "description": "Sequence whose variants are scored, ':' delimiting chains.", + "type": "string" + }, + "include_gaps": { + "default": false, + "description": "Include gap substitutions and scan gap positions.", + "type": "boolean" + }, + "prompt_id": { "anyOf": [ { - "format": "uuid", "type": "string" }, { @@ -7053,225 +7474,227 @@ } ], "default": null, - "description": "ID of an RFdiffusion or BoltzGen design job to design for, in place of query_id. Each designed structure is one query, and the job runs once the design has finished." + "description": "ID of the prompt to condition on; null runs unconditioned." + } + }, + "required": [ + "base_sequence" + ], + "type": "object" + } + }, + "prot-seq/batch/attn": { + "outputs": [ + "attn" + ], + "params": { + "additionalProperties": false, + "properties": { + "chain_linker": { + "default": "GGGGSGGGGSGGGGS", + "description": "Linker joining chains when `chain_mode` is 'linker'.", + "type": "string" }, - "fixed_positions": { + "chain_mode": { + "default": "linker", + "description": "Join a sequence's ':'-delimited chains with `chain_linker`, or embed each chain on its own.", + "enum": [ + "linker", + "independent" + ], + "type": "string" + }, + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "maxLength": 3072, + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "prot-seq/batch/embeddings": { + "outputs": [ + "embeddings" + ], + "params": { + "additionalProperties": false, + "properties": { + "assay_id": { "anyOf": [ { - "items": { - "items": { - "type": "integer" - }, - "type": "array" - }, - "type": "array" + "format": "uuid", + "type": "string" }, { "type": "null" } ], "default": null, - "description": "Positions to hold fixed, per designed chain." + "description": "ID of an assay whose sequences to run, in place of `sequences`." }, - "model_name": { - "default": "v_48_020", - "description": "Model weights version.", + "chain_linker": { + "default": "GGGGSGGGGSGGGGS", + "description": "Linker joining chains when `chain_mode` is 'linker'.", + "type": "string" + }, + "chain_mode": { + "default": "linker", + "description": "Join a sequence's ':'-delimited chains with `chain_linker`, or embed each chain on its own.", "enum": [ - "v_48_002", - "v_48_010", - "v_48_020", - "v_48_030" + "linker", + "independent" ], "type": "string" }, - "num_samples": { - "default": 100, - "description": "Number of sequences per query.", - "maximum": 1000, - "minimum": 1, - "type": "integer" - }, - "omit_aas_global": { + "reduction": { "anyOf": [ { - "items": { - "type": "string" - }, - "type": "array" + "enum": [ + "MEAN", + "SUM" + ], + "type": "string" }, { "type": "null" } ], "default": null, - "description": "Amino acids to exclude from every position." + "description": "Pool each sequence's embedding over its residues; null keeps one row per residue." }, - "omit_aas_per_chain_position": { + "sequences": { "anyOf": [ { - "additionalProperties": { - "items": { - "maxItems": 2, - "minItems": 2, - "prefixItems": [ - { - "items": { - "type": "integer" - }, - "type": "array" - }, - { - "type": "string" - } - ], - "type": "array" - }, - "type": "array" + "items": { + "type": "string" }, - "type": "object" + "type": "array" }, { "type": "null" } ], "default": null, - "description": "Per chain, [positions, amino acids] pairs excluding those amino acids at those positions." + "description": "Sequences to run. Use ':' to delimit chains. Null with `assay_id`." + } + }, + "type": "object" + } + }, + "prot-seq/batch/logits": { + "outputs": [ + "logits" + ], + "params": { + "additionalProperties": false, + "properties": { + "chain_linker": { + "default": "GGGGSGGGGSGGGGS", + "description": "Linker joining chains when `chain_mode` is 'linker'.", + "type": "string" }, - "probabilities_output_mode": { - "default": "none", - "description": "Accepted for compatibility; selects no output.", + "chain_mode": { + "default": "linker", + "description": "Join a sequence's ':'-delimited chains with `chain_linker`, or embed each chain on its own.", "enum": [ - "none", - "per_position", - "conditional", - "conditional_backbone", - "unconditional" + "linker", + "independent" ], "type": "string" }, - "pssm": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "proteinmpnn/batch/embeddings": { + "outputs": [ + "embeddings" + ], + "params": { + "additionalProperties": false, + "properties": { + "ca_only": { + "default": false, + "description": "Use the CA-only model.", + "type": "boolean" + }, + "model_name": { + "default": "v_48_020", + "description": "Model weights version.", + "enum": [ + "v_48_002", + "v_48_010", + "v_48_020", + "v_48_030" + ], + "type": "string" + }, + "query_id": { + "description": "ID of a query (sequence or structure) to condition on.", + "format": "uuid", + "type": "string" + }, + "reduction": { "anyOf": [ { - "additionalProperties": { - "additionalProperties": { - "items": { - "type": "number" - }, - "type": "array" - }, - "type": "object" - }, - "type": "object" + "enum": [ + "MEAN", + "SUM" + ], + "type": "string" }, { "type": "null" } ], "default": null, - "description": "Per chain, pssm_coef, pssm_bias and pssm_log_odds arrays over its residues." + "description": "Pool each sequence's embedding over its residues; null keeps one row per residue." }, - "pssm_bias": { - "default": false, - "description": "Apply the PSSM bias.", - "type": "boolean" - }, - "pssm_log_odds": { - "default": false, - "description": "Apply the PSSM log-odds mask.", - "type": "boolean" - }, - "pssm_multi": { - "default": 0.0, - "description": "Weight of the PSSM against the model's own distribution.", - "maximum": 1, - "minimum": 0, - "type": "number" - }, - "pssm_threshold": { - "default": 0.0, - "description": "Log-odds cutoff restricting the allowed residues.", - "type": "number" - }, - "query_id": { - "anyOf": [ - { - "format": "uuid", - "type": "string" - }, - { - "items": { - "format": "uuid", - "type": "string" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "default": null, - "description": "ID of the structure query to design for, or a list of them. A list designs num_samples sequences for each, query by query. Pass this or design_id." - }, - "random_seed": { - "anyOf": [ - { - "maximum": 4294967296, - "minimum": 0, - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Random seed; the sample at overall position p draws with seed + p. Null for a random seed." + "sequences": { + "description": "Sequences to embed, one ':'-delimited segment per query chain in chain-id order.", + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" }, "soluble_model": { "default": false, "description": "Use the soluble model. Always on for solublempnn.", "type": "boolean" - }, - "temperature": { - "default": 0.1, - "description": "Sampling temperature; low favours recovery, high favours diversity.", - "maximum": 1000000.0, - "minimum": 1e-06, - "type": "number" - }, - "tie_positions": { - "anyOf": [ - { - "items": { - "items": { - "type": "integer" - }, - "type": "array" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Positions tied to one residue, per designed chain." } }, + "required": [ + "query_id", + "sequences" + ], "type": "object" } }, - "proteinmpnn/single-site/scores": { + "proteinmpnn/batch/loglikelihood": { "outputs": [ - "score" + "loglikelihood" ], "params": { "additionalProperties": false, "properties": { - "base_sequence": { - "description": "Sequence every single substitution is scored against, one ':'-delimited segment per query chain in chain-id order.", - "minLength": 1, - "type": "string" - }, "ca_only": { "default": false, "description": "Use the CA-only model.", @@ -7307,6 +7730,14 @@ "minimum": 1, "type": "integer" }, + "sequences": { + "description": "Sequences to score, one ':'-delimited segment per query chain in chain-id order.", + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, "soluble_model": { "default": false, "description": "Use the soluble model. Always on for solublempnn.", @@ -7315,407 +7746,263 @@ }, "required": [ "query_id", - "base_sequence" + "sequences" ], "type": "object" } }, - "protenix-v2/batch/structures": { + "proteinmpnn/generate/sequences": { "outputs": [ - "structures", - "plddt", - "pae", - "pde", - "confidence", - "ipae" + "sequences", + "loglikelihood" ], "params": { - "$defs": { - "Chain": { - "additionalProperties": false, - "properties": { - "dna": { - "anyOf": [ - { - "$ref": "#/$defs/DNA" - }, - { - "type": "null" - } - ], - "default": null - }, - "ion": { - "anyOf": [ - { - "$ref": "#/$defs/Ion" - }, - { - "type": "null" - } - ], - "default": null - }, - "ligand": { - "anyOf": [ - { - "$ref": "#/$defs/Ligand" - }, - { - "type": "null" - } - ], - "default": null - }, - "protein": { - "anyOf": [ - { - "$ref": "#/$defs/ProteinWithMSA" - }, - { - "type": "null" - } - ], - "default": null + "additionalProperties": false, + "properties": { + "aa_bias_global": { + "anyOf": [ + { + "additionalProperties": { + "type": "number" + }, + "type": "object" }, - "rna": { - "anyOf": [ - { - "$ref": "#/$defs/RNA" - }, - { - "type": "null" - } - ], - "default": null + { + "type": "null" } - }, - "type": "object" + ], + "default": null, + "description": "Logit bias per amino acid, at every position." }, - "DNA": { - "additionalProperties": false, - "description": "DNA chain to fold.", - "properties": { - "id": { - "anyOf": [ - { - "type": "string" - }, - { + "aa_bias_per_position": { + "anyOf": [ + { + "additionalProperties": { + "items": { "items": { - "type": "string" + "type": "number" }, "type": "array" - } - ], - "description": "Unique chain identifier(s); a list for identical chains." + }, + "type": "array" + }, + "type": "object" }, - "sequence": { - "type": "string" + { + "type": "null" } - }, - "required": [ - "id", - "sequence" ], - "type": "object" + "default": null, + "description": "Per chain, one 21-element logit bias row per residue." }, - "Ion": { - "additionalProperties": false, - "properties": { - "ccd": { - "type": "string" + "backbone_noise": { + "anyOf": [ + { + "maximum": 10, + "minimum": 0, + "type": "number" }, - "id": { - "anyOf": [ - { - "type": "string" - }, - { - "items": { - "type": "string" - }, - "type": "array" - } - ], - "description": "Unique chain identifier(s); a list for identical chains." + { + "type": "null" } - }, - "required": [ - "id", - "ccd" ], - "type": "object" + "default": null, + "description": "Gaussian noise (Angstrom) added to backbone atoms." }, - "Ligand": { - "additionalProperties": false, - "description": "Small-molecule ligand, given as exactly one of SMILES or CCD code.", - "properties": { - "ccd": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null + "ca_only": { + "default": false, + "description": "Use the CA-only model.", + "type": "boolean" + }, + "chains_to_design": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" }, - "id": { - "anyOf": [ - { - "type": "string" - }, - { - "items": { - "type": "string" - }, - "type": "array" - } - ], - "description": "Unique chain identifier(s); a list for identical chains." + { + "type": "null" + } + ], + "default": null, + "description": "Chains to redesign; others are kept fixed." + }, + "design_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" }, - "smiles": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null + { + "type": "null" } - }, - "required": [ - "id" ], - "type": "object" + "default": null, + "description": "ID of an RFdiffusion or BoltzGen design job to design for, in place of query_id. Each designed structure is one query, and the job runs once the design has finished." }, - "ProteinWithMSA": { - "additionalProperties": false, - "description": "Protein chain to fold, with an optional MSA.", - "properties": { - "id": { - "anyOf": [ - { - "type": "string" + "fixed_positions": { + "anyOf": [ + { + "items": { + "items": { + "type": "integer" }, - { - "items": { - "type": "string" - }, - "type": "array" - } - ], - "description": "Unique chain identifier(s); a list for identical chains." + "type": "array" + }, + "type": "array" }, - "msa_id": { - "anyOf": [ - { - "format": "uuid", - "type": "string" - }, - { - "type": "null" - } - ], - "default": null + { + "type": "null" + } + ], + "default": null, + "description": "Positions to hold fixed, per designed chain." + }, + "model_name": { + "default": "v_48_020", + "description": "Model weights version.", + "enum": [ + "v_48_002", + "v_48_010", + "v_48_020", + "v_48_030" + ], + "type": "string" + }, + "num_samples": { + "default": 100, + "description": "Number of sequences per query.", + "maximum": 1000, + "minimum": 1, + "type": "integer" + }, + "omit_aas_global": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" }, - "sequence": { - "type": "string" + { + "type": "null" } - }, - "required": [ - "id", - "sequence" ], - "type": "object" + "default": null, + "description": "Amino acids to exclude from every position." }, - "RNA": { - "additionalProperties": false, - "description": "RNA chain to fold, with an optional MSA.", - "properties": { - "id": { - "anyOf": [ - { - "type": "string" - }, - { - "items": { - "type": "string" - }, + "omit_aas_per_chain_position": { + "anyOf": [ + { + "additionalProperties": { + "items": { + "maxItems": 2, + "minItems": 2, + "prefixItems": [ + { + "items": { + "type": "integer" + }, + "type": "array" + }, + { + "type": "string" + } + ], "type": "array" - } - ], - "description": "Unique chain identifier(s); a list for identical chains." - }, - "msa_id": { - "anyOf": [ - { - "format": "uuid", - "type": "string" }, - { - "type": "null" - } - ], - "default": null + "type": "array" + }, + "type": "object" }, - "sequence": { - "type": "string" + { + "type": "null" } - }, - "required": [ - "id", - "sequence" ], - "type": "object" + "default": null, + "description": "Per chain, [positions, amino acids] pairs excluding those amino acids at those positions." }, - "Template": { - "properties": { - "chain_id": { - "anyOf": [ - { - "type": "string" - }, - { + "probabilities_output_mode": { + "default": "none", + "description": "Accepted for compatibility; selects no output.", + "enum": [ + "none", + "per_position", + "conditional", + "conditional_backbone", + "unconditional" + ], + "type": "string" + }, + "pssm": { + "anyOf": [ + { + "additionalProperties": { + "additionalProperties": { "items": { - "type": "string" + "type": "number" }, "type": "array" }, - { - "type": "null" - } - ], - "default": null, - "description": "Chain(s) of the complex the template applies to." - }, - "force": { - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "null" - } - ], - "default": null + "type": "object" + }, + "type": "object" }, - "index": { - "anyOf": [ - { - "items": { - "type": "integer" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Complexes the template applies to; all if unset." - }, - "index_intervals": { - "anyOf": [ - { - "items": { - "items": { - "type": "integer" - }, - "type": "array" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Half-open [start, end) ranges of complexes." - }, - "query_id": { - "format": "uuid", - "type": "string" - }, - "template_id": { - "anyOf": [ - { - "type": "string" - }, - { - "items": { - "type": "string" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Chain(s) of the template structure to use." - }, - "threshold": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ], - "default": null + { + "type": "null" } - }, - "required": [ - "query_id" ], - "type": "object" - } - }, - "additionalProperties": false, - "properties": { - "allow_msa_seed_mismatch": { + "default": null, + "description": "Per chain, pssm_coef, pssm_bias and pssm_log_odds arrays over its residues." + }, + "pssm_bias": { "default": false, - "description": "Fold a protein against an MSA built for a different sequence of the same length, such as a point mutant against its wild-type MSA.", + "description": "Apply the PSSM bias.", "type": "boolean" }, - "complexes": { - "description": "Complexes to fold. Each complex is a list of chain entities.", - "items": { - "items": { - "$ref": "#/$defs/Chain" - }, - "type": "array" - }, - "type": "array" + "pssm_log_odds": { + "default": false, + "description": "Apply the PSSM log-odds mask.", + "type": "boolean" }, - "num_recycles": { - "default": 10, - "description": "Number of recycling steps to use.", - "minimum": 1, - "type": "integer" + "pssm_multi": { + "default": 0.0, + "description": "Weight of the PSSM against the model's own distribution.", + "maximum": 1, + "minimum": 0, + "type": "number" }, - "num_samples": { - "default": 1, - "description": "Number of samples to generate.", - "minimum": 1, - "type": "integer" + "pssm_threshold": { + "default": 0.0, + "description": "Log-odds cutoff restricting the allowed residues.", + "type": "number" }, - "num_steps": { - "default": 200, - "description": "Number of sampling steps to use.", - "minimum": 1, - "type": "integer" + "query_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "items": { + "format": "uuid", + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of the structure query to design for, or a list of them. A list designs num_samples sequences for each, query by query. Pass this or design_id." }, "random_seed": { "anyOf": [ { - "maximum": 2147483647, + "maximum": 4294967296, "minimum": 0, "type": "integer" }, @@ -7724,14 +8011,28 @@ } ], "default": null, - "description": "Random seed. Not used yet by this model, so runs are not reproducible." + "description": "Random seed; the sample at overall position p draws with seed + p. Null for a random seed." }, - "templates": { + "soluble_model": { + "default": false, + "description": "Use the soluble model. Always on for solublempnn.", + "type": "boolean" + }, + "temperature": { + "default": 0.1, + "description": "Sampling temperature; low favours recovery, high favours diversity.", + "maximum": 1000000.0, + "minimum": 1e-06, + "type": "number" + }, + "tie_positions": { "anyOf": [ { - "description": "Optional structural templates for prediction.", "items": { - "$ref": "#/$defs/Template" + "items": { + "type": "integer" + }, + "type": "array" }, "type": "array" }, @@ -7739,16 +8040,74 @@ "type": "null" } ], - "default": null + "default": null, + "description": "Positions tied to one residue, per designed chain." + } + }, + "type": "object" + } + }, + "proteinmpnn/single-site/scores": { + "outputs": [ + "score" + ], + "params": { + "additionalProperties": false, + "properties": { + "base_sequence": { + "description": "Sequence every single substitution is scored against, one ':'-delimited segment per query chain in chain-id order.", + "minLength": 1, + "type": "string" + }, + "ca_only": { + "default": false, + "description": "Use the CA-only model.", + "type": "boolean" + }, + "decoding_orders": { + "default": 1, + "description": "Random decoding orders to average each score over.", + "maximum": 10, + "minimum": 1, + "type": "integer" + }, + "model_name": { + "default": "v_48_020", + "description": "Model weights version.", + "enum": [ + "v_48_002", + "v_48_010", + "v_48_020", + "v_48_030" + ], + "type": "string" + }, + "query_id": { + "description": "ID of a query (sequence or structure) to condition on.", + "format": "uuid", + "type": "string" + }, + "random_seed": { + "default": 1, + "description": "Random seed picking the decoding orders.", + "maximum": 4294967296, + "minimum": 1, + "type": "integer" + }, + "soluble_model": { + "default": false, + "description": "Use the soluble model. Always on for solublempnn.", + "type": "boolean" } }, "required": [ - "complexes" + "query_id", + "base_sequence" ], "type": "object" } }, - "protenix/batch/structures": { + "protenix-v2/batch/structures": { "outputs": [ "structures", "plddt", @@ -8152,7 +8511,7 @@ } ], "default": null, - "description": "Random seed. Not used yet by this model, so runs are not reproducible." + "description": "Random seed; null for a random seed." }, "templates": { "anyOf": [ @@ -8176,108 +8535,133 @@ "type": "object" } }, - "prott5-xl/batch/embeddings": { + "protenix/batch/structures": { "outputs": [ - "embeddings" + "structures", + "plddt", + "pae", + "pde", + "confidence", + "ipae" ], "params": { - "additionalProperties": false, - "properties": { - "assay_id": { - "anyOf": [ - { - "format": "uuid", - "type": "string" + "$defs": { + "Chain": { + "additionalProperties": false, + "properties": { + "dna": { + "anyOf": [ + { + "$ref": "#/$defs/DNA" + }, + { + "type": "null" + } + ], + "default": null }, - { - "type": "null" - } - ], - "default": null, - "description": "ID of an assay whose sequences to run, in place of `sequences`." - }, - "reduction": { - "anyOf": [ - { - "enum": [ - "MEAN", - "SUM" + "ion": { + "anyOf": [ + { + "$ref": "#/$defs/Ion" + }, + { + "type": "null" + } ], - "type": "string" + "default": null }, - { - "type": "null" + "ligand": { + "anyOf": [ + { + "$ref": "#/$defs/Ligand" + }, + { + "type": "null" + } + ], + "default": null + }, + "protein": { + "anyOf": [ + { + "$ref": "#/$defs/ProteinWithMSA" + }, + { + "type": "null" + } + ], + "default": null + }, + "rna": { + "anyOf": [ + { + "$ref": "#/$defs/RNA" + }, + { + "type": "null" + } + ], + "default": null } - ], - "default": null, - "description": "Pool each sequence's embedding over its residues; null keeps one row per residue." + }, + "type": "object" }, - "sequences": { - "anyOf": [ - { - "items": { - "type": "string" - }, - "type": "array" + "DNA": { + "additionalProperties": false, + "description": "DNA chain to fold.", + "properties": { + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "description": "Unique chain identifier(s); a list for identical chains." }, - { - "type": "null" + "sequence": { + "type": "string" } + }, + "required": [ + "id", + "sequence" ], - "default": null, - "description": "Sequences to run. Use ':' to delimit chains. Null with `assay_id`." - } - }, - "type": "object" - } - }, - "rfdiffusion/generate/structures": { - "outputs": [ - "structures" - ], - "params": { - "additionalProperties": false, - "properties": { - "num_samples": { - "default": 1, - "description": "Number of designs.", - "minimum": 1, - "type": "integer" - }, - "query_id": { - "description": "Input structure. Its masked positions are designed and its resolved positions are kept, so a fully masked chain is designed de novo.", - "format": "uuid", - "type": "string" + "type": "object" }, - "random_seed": { - "anyOf": [ - { - "maximum": 4294967296, - "minimum": 0, - "type": "integer" + "Ion": { + "additionalProperties": false, + "properties": { + "ccd": { + "type": "string" }, - { - "type": "null" + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "description": "Unique chain identifier(s); a list for identical chains." } + }, + "required": [ + "id", + "ccd" ], - "default": null, - "description": "Random seed; design i draws with seed + i. Not used yet by this model, so runs are not reproducible." - } - }, - "required": [ - "query_id" - ], - "type": "object" - } - }, - "rosettafold-3/batch/structures": { - "outputs": [ - "structures", - "score", - "metrics" - ], - "params": { - "$defs": { + "type": "object" + }, "Ligand": { "additionalProperties": false, "description": "Small-molecule ligand, given as exactly one of SMILES or CCD code.", @@ -8324,38 +8708,49 @@ ], "type": "object" }, - "MsaProteinLigandChain": { + "ProteinWithMSA": { "additionalProperties": false, - "description": "A protein (with optional MSA) or ligand chain.", + "description": "Protein chain to fold, with an optional MSA.", "properties": { - "ligand": { + "id": { "anyOf": [ { - "$ref": "#/$defs/Ligand" + "type": "string" }, { - "type": "null" + "items": { + "type": "string" + }, + "type": "array" } ], - "default": null + "description": "Unique chain identifier(s); a list for identical chains." }, - "protein": { + "msa_id": { "anyOf": [ { - "$ref": "#/$defs/ProteinWithMSA" + "format": "uuid", + "type": "string" }, { "type": "null" } ], "default": null + }, + "sequence": { + "type": "string" } }, + "required": [ + "id", + "sequence" + ], "type": "object" }, - "ProteinWithMSA": { + "RNA": { "additionalProperties": false, - "description": "Protein chain to fold, with an optional MSA.", + "description": "RNA chain to fold, with an optional MSA.", "properties": { "id": { "anyOf": [ @@ -8392,537 +8787,219 @@ "sequence" ], "type": "object" - } - }, - "additionalProperties": false, - "properties": { - "allow_msa_seed_mismatch": { - "default": false, - "description": "Fold a protein against an MSA built for a different sequence of the same length, such as a point mutant against its wild-type MSA.", - "type": "boolean" - }, - "complexes": { - "description": "Protein/ligand complexes to fold; proteins may carry an MSA.", - "items": { - "items": { - "$ref": "#/$defs/MsaProteinLigandChain" - }, - "type": "array" - }, - "type": "array" - }, - "num_recycles": { - "default": 10, - "description": "Number of recycling steps to use.", - "minimum": 1, - "type": "integer" - }, - "num_samples": { - "default": 1, - "description": "Number of samples to generate.", - "maximum": 20, - "minimum": 1, - "type": "integer" }, - "num_steps": { - "default": 50, - "description": "Number of sampling steps to use.", - "minimum": 1, - "type": "integer" - }, - "random_seed": { - "anyOf": [ - { - "maximum": 2147483647, - "minimum": 0, - "type": "integer" + "Template": { + "properties": { + "chain_id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Chain(s) of the complex the template applies to." }, - { - "type": "null" - } - ], - "default": null, - "description": "Random seed. Not used yet by this model, so runs are not reproducible." - } - }, - "required": [ - "complexes" - ], - "type": "object" - } - }, - "rotaprot-large-uniref50w/batch/attn": { - "outputs": [ - "attn" - ], - "params": { - "additionalProperties": false, - "properties": { - "chain_linker": { - "default": "GGGGSGGGGSGGGGS", - "description": "Linker joining chains when `chain_mode` is 'linker'.", - "type": "string" - }, - "chain_mode": { - "default": "linker", - "description": "Join a sequence's ':'-delimited chains with `chain_linker`, or embed each chain on its own.", - "enum": [ - "linker", - "independent" - ], - "type": "string" - }, - "sequences": { - "description": "Sequences to run. Use ':' to delimit chains.", - "items": { - "maxLength": 3072, - "type": "string" - }, - "type": "array" - } - }, - "required": [ - "sequences" - ], - "type": "object" - } - }, - "rotaprot-large-uniref50w/batch/embeddings": { - "outputs": [ - "embeddings" - ], - "params": { - "additionalProperties": false, - "properties": { - "assay_id": { - "anyOf": [ - { - "format": "uuid", - "type": "string" + "force": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null }, - { - "type": "null" - } - ], - "default": null, - "description": "ID of an assay whose sequences to run, in place of `sequences`." - }, - "chain_linker": { - "default": "GGGGSGGGGSGGGGS", - "description": "Linker joining chains when `chain_mode` is 'linker'.", - "type": "string" - }, - "chain_mode": { - "default": "linker", - "description": "Join a sequence's ':'-delimited chains with `chain_linker`, or embed each chain on its own.", - "enum": [ - "linker", - "independent" - ], - "type": "string" - }, - "reduction": { - "anyOf": [ - { - "enum": [ - "MEAN", - "SUM" + "index": { + "anyOf": [ + { + "items": { + "type": "integer" + }, + "type": "array" + }, + { + "type": "null" + } ], - "type": "string" + "default": null, + "description": "Complexes the template applies to; all if unset." }, - { - "type": "null" - } - ], - "default": null, - "description": "Pool each sequence's embedding over its residues; null keeps one row per residue." - }, - "sequences": { - "anyOf": [ - { - "items": { - "type": "string" - }, - "type": "array" + "index_intervals": { + "anyOf": [ + { + "items": { + "items": { + "type": "integer" + }, + "type": "array" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Half-open [start, end) ranges of complexes." }, - { - "type": "null" - } - ], - "default": null, - "description": "Sequences to run. Use ':' to delimit chains. Null with `assay_id`." - } - }, - "type": "object" - } - }, - "rotaprot-large-uniref50w/batch/logits": { - "outputs": [ - "logits" - ], - "params": { - "additionalProperties": false, - "properties": { - "chain_linker": { - "default": "GGGGSGGGGSGGGGS", - "description": "Linker joining chains when `chain_mode` is 'linker'.", - "type": "string" - }, - "chain_mode": { - "default": "linker", - "description": "Join a sequence's ':'-delimited chains with `chain_linker`, or embed each chain on its own.", - "enum": [ - "linker", - "independent" - ], - "type": "string" - }, - "sequences": { - "description": "Sequences to run. Use ':' to delimit chains.", - "items": { - "type": "string" - }, - "type": "array" - } - }, - "required": [ - "sequences" - ], - "type": "object" - } - }, - "rotaprot-large-uniref90-ft/batch/attn": { - "outputs": [ - "attn" - ], - "params": { - "additionalProperties": false, - "properties": { - "chain_linker": { - "default": "GGGGSGGGGSGGGGS", - "description": "Linker joining chains when `chain_mode` is 'linker'.", - "type": "string" - }, - "chain_mode": { - "default": "linker", - "description": "Join a sequence's ':'-delimited chains with `chain_linker`, or embed each chain on its own.", - "enum": [ - "linker", - "independent" - ], - "type": "string" - }, - "sequences": { - "description": "Sequences to run. Use ':' to delimit chains.", - "items": { - "maxLength": 3072, - "type": "string" - }, - "type": "array" - } - }, - "required": [ - "sequences" - ], - "type": "object" - } - }, - "rotaprot-large-uniref90-ft/batch/embeddings": { - "outputs": [ - "embeddings" - ], - "params": { - "additionalProperties": false, - "properties": { - "assay_id": { - "anyOf": [ - { + "query_id": { "format": "uuid", "type": "string" }, - { - "type": "null" - } - ], - "default": null, - "description": "ID of an assay whose sequences to run, in place of `sequences`." - }, - "chain_linker": { - "default": "GGGGSGGGGSGGGGS", - "description": "Linker joining chains when `chain_mode` is 'linker'.", - "type": "string" - }, - "chain_mode": { - "default": "linker", - "description": "Join a sequence's ':'-delimited chains with `chain_linker`, or embed each chain on its own.", - "enum": [ - "linker", - "independent" - ], - "type": "string" - }, - "reduction": { - "anyOf": [ - { - "enum": [ - "MEAN", - "SUM" - ], - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Pool each sequence's embedding over its residues; null keeps one row per residue." - }, - "sequences": { - "anyOf": [ - { - "items": { - "type": "string" - }, - "type": "array" + "template_id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Chain(s) of the template structure to use." }, - { - "type": "null" + "threshold": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "default": null } + }, + "required": [ + "query_id" ], - "default": null, - "description": "Sequences to run. Use ':' to delimit chains. Null with `assay_id`." + "type": "object" } }, - "type": "object" - } - }, - "rotaprot-large-uniref90-ft/batch/logits": { - "outputs": [ - "logits" - ], - "params": { "additionalProperties": false, "properties": { - "chain_linker": { - "default": "GGGGSGGGGSGGGGS", - "description": "Linker joining chains when `chain_mode` is 'linker'.", - "type": "string" - }, - "chain_mode": { - "default": "linker", - "description": "Join a sequence's ':'-delimited chains with `chain_linker`, or embed each chain on its own.", - "enum": [ - "linker", - "independent" - ], - "type": "string" + "allow_msa_seed_mismatch": { + "default": false, + "description": "Fold a protein against an MSA built for a different sequence of the same length, such as a point mutant against its wild-type MSA.", + "type": "boolean" }, - "sequences": { - "description": "Sequences to run. Use ':' to delimit chains.", + "complexes": { + "description": "Complexes to fold. Each complex is a list of chain entities.", "items": { - "type": "string" + "items": { + "$ref": "#/$defs/Chain" + }, + "type": "array" }, "type": "array" - } - }, - "required": [ - "sequences" - ], - "type": "object" - } - }, - "solublempnn/batch/embeddings": { - "outputs": [ - "embeddings" - ], - "params": { - "additionalProperties": false, - "properties": { - "ca_only": { - "default": false, - "description": "Use the CA-only model.", - "type": "boolean" }, - "model_name": { - "default": "v_48_020", - "description": "Model weights version.", - "enum": [ - "v_48_002", - "v_48_010", - "v_48_020", - "v_48_030" - ], - "type": "string" + "num_recycles": { + "default": 10, + "description": "Number of recycling steps to use.", + "minimum": 1, + "type": "integer" }, - "query_id": { - "description": "ID of a query (sequence or structure) to condition on.", - "format": "uuid", - "type": "string" + "num_samples": { + "default": 1, + "description": "Number of samples to generate.", + "minimum": 1, + "type": "integer" }, - "reduction": { + "num_steps": { + "default": 200, + "description": "Number of sampling steps to use.", + "minimum": 1, + "type": "integer" + }, + "random_seed": { "anyOf": [ { - "enum": [ - "MEAN", - "SUM" - ], - "type": "string" + "maximum": 2147483647, + "minimum": 0, + "type": "integer" }, { "type": "null" } ], "default": null, - "description": "Pool each sequence's embedding over its residues; null keeps one row per residue." - }, - "sequences": { - "description": "Sequences to embed, one ':'-delimited segment per query chain in chain-id order.", - "items": { - "type": "string" - }, - "minItems": 1, - "type": "array" - }, - "soluble_model": { - "default": false, - "description": "Use the soluble model. Always on for solublempnn.", - "type": "boolean" - } - }, - "required": [ - "query_id", - "sequences" - ], - "type": "object" - } - }, - "solublempnn/batch/loglikelihood": { - "outputs": [ - "loglikelihood" - ], - "params": { - "additionalProperties": false, - "properties": { - "ca_only": { - "default": false, - "description": "Use the CA-only model.", - "type": "boolean" - }, - "decoding_orders": { - "default": 1, - "description": "Random decoding orders to average each score over.", - "maximum": 10, - "minimum": 1, - "type": "integer" + "description": "Random seed; null for a random seed." }, - "model_name": { - "default": "v_48_020", - "description": "Model weights version.", - "enum": [ - "v_48_002", - "v_48_010", - "v_48_020", - "v_48_030" + "templates": { + "anyOf": [ + { + "description": "Optional structural templates for prediction.", + "items": { + "$ref": "#/$defs/Template" + }, + "type": "array" + }, + { + "type": "null" + } ], - "type": "string" - }, - "query_id": { - "description": "ID of a query (sequence or structure) to condition on.", - "format": "uuid", - "type": "string" - }, - "random_seed": { - "default": 1, - "description": "Random seed picking the decoding orders.", - "maximum": 4294967296, - "minimum": 1, - "type": "integer" - }, - "sequences": { - "description": "Sequences to score, one ':'-delimited segment per query chain in chain-id order.", - "items": { - "type": "string" - }, - "minItems": 1, - "type": "array" - }, - "soluble_model": { - "default": false, - "description": "Use the soluble model. Always on for solublempnn.", - "type": "boolean" + "default": null } }, "required": [ - "query_id", - "sequences" + "complexes" ], "type": "object" } }, - "solublempnn/generate/sequences": { + "prott5-xl/batch/embeddings": { "outputs": [ - "sequences", - "loglikelihood" + "embeddings" ], "params": { "additionalProperties": false, "properties": { - "aa_bias_global": { - "anyOf": [ - { - "additionalProperties": { - "type": "number" - }, - "type": "object" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Logit bias per amino acid, at every position." - }, - "aa_bias_per_position": { + "assay_id": { "anyOf": [ { - "additionalProperties": { - "items": { - "items": { - "type": "number" - }, - "type": "array" - }, - "type": "array" - }, - "type": "object" + "format": "uuid", + "type": "string" }, { "type": "null" } ], "default": null, - "description": "Per chain, one 21-element logit bias row per residue." + "description": "ID of an assay whose sequences to run, in place of `sequences`." }, - "backbone_noise": { + "reduction": { "anyOf": [ { - "maximum": 10, - "minimum": 0, - "type": "number" + "enum": [ + "MEAN", + "SUM" + ], + "type": "string" }, { "type": "null" } ], "default": null, - "description": "Gaussian noise (Angstrom) added to backbone atoms." - }, - "ca_only": { - "default": false, - "description": "Use the CA-only model.", - "type": "boolean" + "description": "Pool each sequence's embedding over its residues; null keeps one row per residue." }, - "chains_to_design": { + "sequences": { "anyOf": [ { "items": { @@ -8935,212 +9012,323 @@ } ], "default": null, - "description": "Chains to redesign; others are kept fixed." + "description": "Sequences to run. Use ':' to delimit chains. Null with `assay_id`." + } + }, + "type": "object" + } + }, + "rfdiffusion/generate/structures": { + "outputs": [ + "structures" + ], + "params": { + "additionalProperties": false, + "properties": { + "num_samples": { + "default": 1, + "description": "Number of designs.", + "minimum": 1, + "type": "integer" }, - "design_id": { + "query_id": { + "description": "Input structure. Its masked positions are designed and its resolved positions are kept, so a fully masked chain is designed de novo.", + "format": "uuid", + "type": "string" + }, + "random_seed": { "anyOf": [ { - "format": "uuid", - "type": "string" + "maximum": 4294967296, + "minimum": 0, + "type": "integer" }, { "type": "null" } ], "default": null, - "description": "ID of an RFdiffusion or BoltzGen design job to design for, in place of query_id. Each designed structure is one query, and the job runs once the design has finished." - }, - "fixed_positions": { - "anyOf": [ - { - "items": { - "items": { - "type": "integer" + "description": "Random seed; design i draws with seed + i. Not used yet by this model, so runs are not reproducible." + } + }, + "required": [ + "query_id" + ], + "type": "object" + } + }, + "rosettafold-3/batch/structures": { + "outputs": [ + "structures", + "score", + "metrics" + ], + "params": { + "$defs": { + "Ligand": { + "additionalProperties": false, + "description": "Small-molecule ligand, given as exactly one of SMILES or CCD code.", + "properties": { + "ccd": { + "anyOf": [ + { + "type": "string" }, - "type": "array" - }, - "type": "array" + { + "type": "null" + } + ], + "default": null }, - { - "type": "null" + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "description": "Unique chain identifier(s); a list for identical chains." + }, + "smiles": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null } + }, + "required": [ + "id" ], - "default": null, - "description": "Positions to hold fixed, per designed chain." + "type": "object" }, - "model_name": { - "default": "v_48_020", - "description": "Model weights version.", - "enum": [ - "v_48_002", - "v_48_010", - "v_48_020", - "v_48_030" + "MsaProteinLigandChain": { + "additionalProperties": false, + "description": "A protein (with optional MSA) or ligand chain.", + "properties": { + "ligand": { + "anyOf": [ + { + "$ref": "#/$defs/Ligand" + }, + { + "type": "null" + } + ], + "default": null + }, + "protein": { + "anyOf": [ + { + "$ref": "#/$defs/ProteinWithMSA" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "type": "object" + }, + "ProteinWithMSA": { + "additionalProperties": false, + "description": "Protein chain to fold, with an optional MSA.", + "properties": { + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "description": "Unique chain identifier(s); a list for identical chains." + }, + "msa_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + }, + "sequence": { + "type": "string" + } + }, + "required": [ + "id", + "sequence" ], - "type": "string" + "type": "object" + } + }, + "additionalProperties": false, + "properties": { + "allow_msa_seed_mismatch": { + "default": false, + "description": "Fold a protein against an MSA built for a different sequence of the same length, such as a point mutant against its wild-type MSA.", + "type": "boolean" }, - "num_samples": { - "default": 100, - "description": "Number of sequences per query.", - "maximum": 1000, + "complexes": { + "description": "Protein/ligand complexes to fold; proteins may carry an MSA.", + "items": { + "items": { + "$ref": "#/$defs/MsaProteinLigandChain" + }, + "type": "array" + }, + "type": "array" + }, + "num_recycles": { + "default": 10, + "description": "Number of recycling steps to use.", "minimum": 1, "type": "integer" }, - "omit_aas_global": { - "anyOf": [ - { - "items": { - "type": "string" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Amino acids to exclude from every position." + "num_samples": { + "default": 1, + "description": "Number of samples to generate.", + "maximum": 20, + "minimum": 1, + "type": "integer" }, - "omit_aas_per_chain_position": { + "num_steps": { + "default": 50, + "description": "Number of sampling steps to use.", + "minimum": 1, + "type": "integer" + }, + "random_seed": { "anyOf": [ { - "additionalProperties": { - "items": { - "maxItems": 2, - "minItems": 2, - "prefixItems": [ - { - "items": { - "type": "integer" - }, - "type": "array" - }, - { - "type": "string" - } - ], - "type": "array" - }, - "type": "array" - }, - "type": "object" + "maximum": 2147483647, + "minimum": 1, + "type": "integer" }, { "type": "null" } ], "default": null, - "description": "Per chain, [positions, amino acids] pairs excluding those amino acids at those positions." + "description": "Random seed from 1; null for a random seed." + } + }, + "required": [ + "complexes" + ], + "type": "object" + } + }, + "rotaprot-large-uniref50w/batch/attn": { + "outputs": [ + "attn" + ], + "params": { + "additionalProperties": false, + "properties": { + "chain_linker": { + "default": "GGGGSGGGGSGGGGS", + "description": "Linker joining chains when `chain_mode` is 'linker'.", + "type": "string" }, - "probabilities_output_mode": { - "default": "none", - "description": "Accepted for compatibility; selects no output.", + "chain_mode": { + "default": "linker", + "description": "Join a sequence's ':'-delimited chains with `chain_linker`, or embed each chain on its own.", "enum": [ - "none", - "per_position", - "conditional", - "conditional_backbone", - "unconditional" + "linker", + "independent" ], "type": "string" }, - "pssm": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "maxLength": 3072, + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "rotaprot-large-uniref50w/batch/embeddings": { + "outputs": [ + "embeddings" + ], + "params": { + "additionalProperties": false, + "properties": { + "assay_id": { "anyOf": [ { - "additionalProperties": { - "additionalProperties": { - "items": { - "type": "number" - }, - "type": "array" - }, - "type": "object" - }, - "type": "object" + "format": "uuid", + "type": "string" }, { "type": "null" } ], "default": null, - "description": "Per chain, pssm_coef, pssm_bias and pssm_log_odds arrays over its residues." - }, - "pssm_bias": { - "default": false, - "description": "Apply the PSSM bias.", - "type": "boolean" - }, - "pssm_log_odds": { - "default": false, - "description": "Apply the PSSM log-odds mask.", - "type": "boolean" - }, - "pssm_multi": { - "default": 0.0, - "description": "Weight of the PSSM against the model's own distribution.", - "maximum": 1, - "minimum": 0, - "type": "number" + "description": "ID of an assay whose sequences to run, in place of `sequences`." }, - "pssm_threshold": { - "default": 0.0, - "description": "Log-odds cutoff restricting the allowed residues.", - "type": "number" + "chain_linker": { + "default": "GGGGSGGGGSGGGGS", + "description": "Linker joining chains when `chain_mode` is 'linker'.", + "type": "string" }, - "query_id": { - "anyOf": [ - { - "format": "uuid", - "type": "string" - }, - { - "items": { - "format": "uuid", - "type": "string" - }, - "type": "array" - }, - { - "type": "null" - } + "chain_mode": { + "default": "linker", + "description": "Join a sequence's ':'-delimited chains with `chain_linker`, or embed each chain on its own.", + "enum": [ + "linker", + "independent" ], - "default": null, - "description": "ID of the structure query to design for, or a list of them. A list designs num_samples sequences for each, query by query. Pass this or design_id." + "type": "string" }, - "random_seed": { + "reduction": { "anyOf": [ { - "maximum": 4294967296, - "minimum": 0, - "type": "integer" + "enum": [ + "MEAN", + "SUM" + ], + "type": "string" }, { "type": "null" } ], "default": null, - "description": "Random seed; the sample at overall position p draws with seed + p. Null for a random seed." - }, - "soluble_model": { - "default": false, - "description": "Use the soluble model. Always on for solublempnn.", - "type": "boolean" - }, - "temperature": { - "default": 0.1, - "description": "Sampling temperature; low favours recovery, high favours diversity.", - "maximum": 1000000.0, - "minimum": 1e-06, - "type": "number" + "description": "Pool each sequence's embedding over its residues; null keeps one row per residue." }, - "tie_positions": { + "sequences": { "anyOf": [ { "items": { - "items": { - "type": "integer" - }, - "type": "array" + "type": "string" }, "type": "array" }, @@ -9149,85 +9337,38 @@ } ], "default": null, - "description": "Positions tied to one residue, per designed chain." + "description": "Sequences to run. Use ':' to delimit chains. Null with `assay_id`." } }, "type": "object" } }, - "solublempnn/single-site/scores": { + "rotaprot-large-uniref50w/batch/logits": { "outputs": [ - "score" + "logits" ], "params": { "additionalProperties": false, "properties": { - "base_sequence": { - "description": "Sequence every single substitution is scored against, one ':'-delimited segment per query chain in chain-id order.", - "minLength": 1, + "chain_linker": { + "default": "GGGGSGGGGSGGGGS", + "description": "Linker joining chains when `chain_mode` is 'linker'.", "type": "string" }, - "ca_only": { - "default": false, - "description": "Use the CA-only model.", - "type": "boolean" - }, - "decoding_orders": { - "default": 1, - "description": "Random decoding orders to average each score over.", - "maximum": 10, - "minimum": 1, - "type": "integer" - }, - "model_name": { - "default": "v_48_020", - "description": "Model weights version.", + "chain_mode": { + "default": "linker", + "description": "Join a sequence's ':'-delimited chains with `chain_linker`, or embed each chain on its own.", "enum": [ - "v_48_002", - "v_48_010", - "v_48_020", - "v_48_030" + "linker", + "independent" ], "type": "string" }, - "query_id": { - "description": "ID of a query (sequence or structure) to condition on.", - "format": "uuid", - "type": "string" - }, - "random_seed": { - "default": 1, - "description": "Random seed picking the decoding orders.", - "maximum": 4294967296, - "minimum": 1, - "type": "integer" - }, - "soluble_model": { - "default": false, - "description": "Use the soluble model. Always on for solublempnn.", - "type": "boolean" - } - }, - "required": [ - "query_id", - "base_sequence" - ], - "type": "object" - } - }, - "svd/batch/embeddings": { - "outputs": [ - "embeddings" - ], - "params": { - "additionalProperties": false, - "description": "New sequences to project through a fitted SVD.", - "properties": { "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", "items": { "type": "string" }, - "minItems": 1, "type": "array" } }, @@ -9237,19 +9378,33 @@ "type": "object" } }, - "umap/batch/embeddings": { + "rotaprot-large-uniref90-ft/batch/attn": { "outputs": [ - "embeddings" + "attn" ], "params": { "additionalProperties": false, - "description": "New sequences to project through a fitted SVD.", "properties": { + "chain_linker": { + "default": "GGGGSGGGGSGGGGS", + "description": "Linker joining chains when `chain_mode` is 'linker'.", + "type": "string" + }, + "chain_mode": { + "default": "linker", + "description": "Join a sequence's ':'-delimited chains with `chain_linker`, or embed each chain on its own.", + "enum": [ + "linker", + "independent" + ], + "type": "string" + }, "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", "items": { + "maxLength": 3072, "type": "string" }, - "minItems": 1, "type": "array" } }, @@ -9259,573 +9414,490 @@ "type": "object" } }, - "opendde/batch/structures": { + "rotaprot-large-uniref90-ft/batch/embeddings": { "outputs": [ - "structures" + "embeddings" ], "params": { - "$defs": { - "Chain": { - "additionalProperties": false, - "properties": { - "dna": { - "anyOf": [ - { - "$ref": "#/$defs/DNA" - }, - { - "type": "null" - } - ], - "default": null - }, - "ion": { - "anyOf": [ - { - "$ref": "#/$defs/Ion" - }, - { - "type": "null" - } - ], - "default": null - }, - "ligand": { - "anyOf": [ - { - "$ref": "#/$defs/Ligand" - }, - { - "type": "null" - } - ], - "default": null - }, - "protein": { - "anyOf": [ - { - "$ref": "#/$defs/ProteinWithMSA" - }, - { - "type": "null" - } - ], - "default": null + "additionalProperties": false, + "properties": { + "assay_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" }, - "rna": { - "anyOf": [ - { - "$ref": "#/$defs/RNA" - }, - { - "type": "null" - } - ], - "default": null + { + "type": "null" } - }, - "type": "object" + ], + "default": null, + "description": "ID of an assay whose sequences to run, in place of `sequences`." }, - "DNA": { - "additionalProperties": false, - "description": "DNA chain to fold.", - "properties": { - "id": { - "anyOf": [ - { - "type": "string" - }, - { - "items": { - "type": "string" - }, - "type": "array" - } - ], - "description": "Unique chain identifier(s); a list for identical chains." - }, - "sequence": { - "type": "string" - } - }, - "required": [ - "id", - "sequence" + "chain_linker": { + "default": "GGGGSGGGGSGGGGS", + "description": "Linker joining chains when `chain_mode` is 'linker'.", + "type": "string" + }, + "chain_mode": { + "default": "linker", + "description": "Join a sequence's ':'-delimited chains with `chain_linker`, or embed each chain on its own.", + "enum": [ + "linker", + "independent" ], - "type": "object" + "type": "string" }, - "Ion": { - "additionalProperties": false, - "properties": { - "ccd": { + "reduction": { + "anyOf": [ + { + "enum": [ + "MEAN", + "SUM" + ], "type": "string" }, - "id": { - "anyOf": [ - { - "type": "string" - }, - { - "items": { - "type": "string" - }, - "type": "array" - } - ], - "description": "Unique chain identifier(s); a list for identical chains." + { + "type": "null" } - }, - "required": [ - "id", - "ccd" ], - "type": "object" + "default": null, + "description": "Pool each sequence's embedding over its residues; null keeps one row per residue." }, - "Ligand": { - "additionalProperties": false, - "description": "Small-molecule ligand, given as exactly one of SMILES or CCD code.", - "properties": { - "ccd": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null - }, - "id": { - "anyOf": [ - { - "type": "string" - }, - { - "items": { - "type": "string" - }, - "type": "array" - } - ], - "description": "Unique chain identifier(s); a list for identical chains." + "sequences": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" }, - "smiles": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null + { + "type": "null" } + ], + "default": null, + "description": "Sequences to run. Use ':' to delimit chains. Null with `assay_id`." + } + }, + "type": "object" + } + }, + "rotaprot-large-uniref90-ft/batch/logits": { + "outputs": [ + "logits" + ], + "params": { + "additionalProperties": false, + "properties": { + "chain_linker": { + "default": "GGGGSGGGGSGGGGS", + "description": "Linker joining chains when `chain_mode` is 'linker'.", + "type": "string" + }, + "chain_mode": { + "default": "linker", + "description": "Join a sequence's ':'-delimited chains with `chain_linker`, or embed each chain on its own.", + "enum": [ + "linker", + "independent" + ], + "type": "string" + }, + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" }, - "required": [ - "id" + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "solublempnn/batch/embeddings": { + "outputs": [ + "embeddings" + ], + "params": { + "additionalProperties": false, + "properties": { + "ca_only": { + "default": false, + "description": "Use the CA-only model.", + "type": "boolean" + }, + "model_name": { + "default": "v_48_020", + "description": "Model weights version.", + "enum": [ + "v_48_002", + "v_48_010", + "v_48_020", + "v_48_030" ], - "type": "object" + "type": "string" }, - "ProteinWithMSA": { - "additionalProperties": false, - "description": "Protein chain to fold, with an optional MSA.", - "properties": { - "id": { - "anyOf": [ - { - "type": "string" - }, - { - "items": { - "type": "string" - }, - "type": "array" - } - ], - "description": "Unique chain identifier(s); a list for identical chains." - }, - "msa_id": { - "anyOf": [ - { - "format": "uuid", - "type": "string" - }, - { - "type": "null" - } + "query_id": { + "description": "ID of a query (sequence or structure) to condition on.", + "format": "uuid", + "type": "string" + }, + "reduction": { + "anyOf": [ + { + "enum": [ + "MEAN", + "SUM" ], - "default": null - }, - "sequence": { "type": "string" + }, + { + "type": "null" } - }, - "required": [ - "id", - "sequence" ], - "type": "object" + "default": null, + "description": "Pool each sequence's embedding over its residues; null keeps one row per residue." }, - "RNA": { - "additionalProperties": false, - "properties": { - "id": { - "anyOf": [ - { - "type": "string" - }, - { - "items": { - "type": "string" - }, - "type": "array" - } - ], - "description": "Unique chain identifier(s); a list for identical chains." - }, - "sequence": { - "type": "string" - } + "sequences": { + "description": "Sequences to embed, one ':'-delimited segment per query chain in chain-id order.", + "items": { + "type": "string" }, - "required": [ - "id", - "sequence" - ], - "type": "object" + "minItems": 1, + "type": "array" + }, + "soluble_model": { + "default": false, + "description": "Use the soluble model. Always on for solublempnn.", + "type": "boolean" } }, + "required": [ + "query_id", + "sequences" + ], + "type": "object" + } + }, + "solublempnn/batch/loglikelihood": { + "outputs": [ + "loglikelihood" + ], + "params": { "additionalProperties": false, "properties": { - "allow_msa_seed_mismatch": { + "ca_only": { "default": false, - "description": "Fold a protein against an MSA built for a different sequence of the same length, such as a point mutant against its wild-type MSA.", + "description": "Use the CA-only model.", "type": "boolean" }, - "complexes": { - "description": "Complexes to fold. Each complex is a list of chain entities.", - "items": { - "items": { - "$ref": "#/$defs/Chain" - }, - "type": "array" - }, - "type": "array" - }, - "num_recycles": { - "default": 10, - "description": "Number of recycling steps to use.", + "decoding_orders": { + "default": 1, + "description": "Random decoding orders to average each score over.", + "maximum": 10, "minimum": 1, "type": "integer" }, - "num_samples": { + "model_name": { + "default": "v_48_020", + "description": "Model weights version.", + "enum": [ + "v_48_002", + "v_48_010", + "v_48_020", + "v_48_030" + ], + "type": "string" + }, + "query_id": { + "description": "ID of a query (sequence or structure) to condition on.", + "format": "uuid", + "type": "string" + }, + "random_seed": { "default": 1, - "description": "Number of samples to generate.", + "description": "Random seed picking the decoding orders.", + "maximum": 4294967296, "minimum": 1, "type": "integer" }, - "num_steps": { - "default": 200, - "description": "Number of sampling steps to use.", - "minimum": 1, - "type": "integer" + "sequences": { + "description": "Sequences to score, one ':'-delimited segment per query chain in chain-id order.", + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" }, - "random_seed": { - "anyOf": [ - { - "maximum": 2147483647, - "minimum": 0, - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Random seed; null for a random seed." + "soluble_model": { + "default": false, + "description": "Use the soluble model. Always on for solublempnn.", + "type": "boolean" } }, "required": [ - "complexes" + "query_id", + "sequences" ], "type": "object" } }, - "opendde-abag/batch/structures": { + "solublempnn/generate/sequences": { "outputs": [ - "structures" + "sequences", + "loglikelihood" ], "params": { - "$defs": { - "Chain": { - "additionalProperties": false, - "properties": { - "dna": { - "anyOf": [ - { - "$ref": "#/$defs/DNA" - }, - { - "type": "null" - } - ], - "default": null - }, - "ion": { - "anyOf": [ - { - "$ref": "#/$defs/Ion" - }, - { - "type": "null" - } - ], - "default": null - }, - "ligand": { - "anyOf": [ - { - "$ref": "#/$defs/Ligand" - }, - { - "type": "null" - } - ], - "default": null - }, - "protein": { - "anyOf": [ - { - "$ref": "#/$defs/ProteinWithMSA" - }, - { - "type": "null" - } - ], - "default": null + "additionalProperties": false, + "properties": { + "aa_bias_global": { + "anyOf": [ + { + "additionalProperties": { + "type": "number" + }, + "type": "object" }, - "rna": { - "anyOf": [ - { - "$ref": "#/$defs/RNA" - }, - { - "type": "null" - } - ], - "default": null + { + "type": "null" } - }, - "type": "object" + ], + "default": null, + "description": "Logit bias per amino acid, at every position." }, - "DNA": { - "additionalProperties": false, - "description": "DNA chain to fold.", - "properties": { - "id": { - "anyOf": [ - { - "type": "string" - }, - { + "aa_bias_per_position": { + "anyOf": [ + { + "additionalProperties": { + "items": { "items": { - "type": "string" + "type": "number" }, "type": "array" - } - ], - "description": "Unique chain identifier(s); a list for identical chains." + }, + "type": "array" + }, + "type": "object" }, - "sequence": { - "type": "string" + { + "type": "null" } - }, - "required": [ - "id", - "sequence" ], - "type": "object" + "default": null, + "description": "Per chain, one 21-element logit bias row per residue." }, - "Ion": { - "additionalProperties": false, - "properties": { - "ccd": { + "backbone_noise": { + "anyOf": [ + { + "maximum": 10, + "minimum": 0, + "type": "number" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Gaussian noise (Angstrom) added to backbone atoms." + }, + "ca_only": { + "default": false, + "description": "Use the CA-only model.", + "type": "boolean" + }, + "chains_to_design": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Chains to redesign; others are kept fixed." + }, + "design_id": { + "anyOf": [ + { + "format": "uuid", "type": "string" }, - "id": { - "anyOf": [ - { - "type": "string" - }, - { - "items": { - "type": "string" - }, - "type": "array" - } - ], - "description": "Unique chain identifier(s); a list for identical chains." + { + "type": "null" } - }, - "required": [ - "id", - "ccd" ], - "type": "object" + "default": null, + "description": "ID of an RFdiffusion or BoltzGen design job to design for, in place of query_id. Each designed structure is one query, and the job runs once the design has finished." }, - "Ligand": { - "additionalProperties": false, - "description": "Small-molecule ligand, given as exactly one of SMILES or CCD code.", - "properties": { - "ccd": { - "anyOf": [ - { - "type": "string" + "fixed_positions": { + "anyOf": [ + { + "items": { + "items": { + "type": "integer" }, - { - "type": "null" - } - ], - "default": null + "type": "array" + }, + "type": "array" }, - "id": { - "anyOf": [ - { - "type": "string" - }, - { - "items": { - "type": "string" - }, - "type": "array" - } - ], - "description": "Unique chain identifier(s); a list for identical chains." + { + "type": "null" + } + ], + "default": null, + "description": "Positions to hold fixed, per designed chain." + }, + "model_name": { + "default": "v_48_020", + "description": "Model weights version.", + "enum": [ + "v_48_002", + "v_48_010", + "v_48_020", + "v_48_030" + ], + "type": "string" + }, + "num_samples": { + "default": 100, + "description": "Number of sequences per query.", + "maximum": 1000, + "minimum": 1, + "type": "integer" + }, + "omit_aas_global": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" }, - "smiles": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null + { + "type": "null" } - }, - "required": [ - "id" ], - "type": "object" + "default": null, + "description": "Amino acids to exclude from every position." }, - "ProteinWithMSA": { - "additionalProperties": false, - "description": "Protein chain to fold, with an optional MSA.", - "properties": { - "id": { - "anyOf": [ - { - "type": "string" - }, - { - "items": { - "type": "string" - }, + "omit_aas_per_chain_position": { + "anyOf": [ + { + "additionalProperties": { + "items": { + "maxItems": 2, + "minItems": 2, + "prefixItems": [ + { + "items": { + "type": "integer" + }, + "type": "array" + }, + { + "type": "string" + } + ], "type": "array" - } - ], - "description": "Unique chain identifier(s); a list for identical chains." - }, - "msa_id": { - "anyOf": [ - { - "format": "uuid", - "type": "string" }, - { - "type": "null" - } - ], - "default": null + "type": "array" + }, + "type": "object" }, - "sequence": { - "type": "string" + { + "type": "null" } - }, - "required": [ - "id", - "sequence" ], - "type": "object" + "default": null, + "description": "Per chain, [positions, amino acids] pairs excluding those amino acids at those positions." }, - "RNA": { - "additionalProperties": false, - "properties": { - "id": { - "anyOf": [ - { - "type": "string" - }, - { + "probabilities_output_mode": { + "default": "none", + "description": "Accepted for compatibility; selects no output.", + "enum": [ + "none", + "per_position", + "conditional", + "conditional_backbone", + "unconditional" + ], + "type": "string" + }, + "pssm": { + "anyOf": [ + { + "additionalProperties": { + "additionalProperties": { "items": { - "type": "string" + "type": "number" }, "type": "array" - } - ], - "description": "Unique chain identifier(s); a list for identical chains." + }, + "type": "object" + }, + "type": "object" }, - "sequence": { - "type": "string" + { + "type": "null" } - }, - "required": [ - "id", - "sequence" ], - "type": "object" - } - }, - "additionalProperties": false, - "properties": { - "allow_msa_seed_mismatch": { + "default": null, + "description": "Per chain, pssm_coef, pssm_bias and pssm_log_odds arrays over its residues." + }, + "pssm_bias": { "default": false, - "description": "Fold a protein against an MSA built for a different sequence of the same length, such as a point mutant against its wild-type MSA.", + "description": "Apply the PSSM bias.", "type": "boolean" }, - "complexes": { - "description": "Complexes to fold. Each complex is a list of chain entities.", - "items": { - "items": { - "$ref": "#/$defs/Chain" - }, - "type": "array" - }, - "type": "array" + "pssm_log_odds": { + "default": false, + "description": "Apply the PSSM log-odds mask.", + "type": "boolean" }, - "num_recycles": { - "default": 10, - "description": "Number of recycling steps to use.", - "minimum": 1, - "type": "integer" + "pssm_multi": { + "default": 0.0, + "description": "Weight of the PSSM against the model's own distribution.", + "maximum": 1, + "minimum": 0, + "type": "number" }, - "num_samples": { - "default": 1, - "description": "Number of samples to generate.", - "minimum": 1, - "type": "integer" + "pssm_threshold": { + "default": 0.0, + "description": "Log-odds cutoff restricting the allowed residues.", + "type": "number" }, - "num_steps": { - "default": 200, - "description": "Number of sampling steps to use.", - "minimum": 1, - "type": "integer" + "query_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "items": { + "format": "uuid", + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of the structure query to design for, or a list of them. A list designs num_samples sequences for each, query by query. Pass this or design_id." }, "random_seed": { "anyOf": [ { - "maximum": 2147483647, + "maximum": 4294967296, "minimum": 0, "type": "integer" }, @@ -9834,11 +9906,142 @@ } ], "default": null, - "description": "Random seed; null for a random seed." + "description": "Random seed; the sample at overall position p draws with seed + p. Null for a random seed." + }, + "soluble_model": { + "default": false, + "description": "Use the soluble model. Always on for solublempnn.", + "type": "boolean" + }, + "temperature": { + "default": 0.1, + "description": "Sampling temperature; low favours recovery, high favours diversity.", + "maximum": 1000000.0, + "minimum": 1e-06, + "type": "number" + }, + "tie_positions": { + "anyOf": [ + { + "items": { + "items": { + "type": "integer" + }, + "type": "array" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Positions tied to one residue, per designed chain." + } + }, + "type": "object" + } + }, + "solublempnn/single-site/scores": { + "outputs": [ + "score" + ], + "params": { + "additionalProperties": false, + "properties": { + "base_sequence": { + "description": "Sequence every single substitution is scored against, one ':'-delimited segment per query chain in chain-id order.", + "minLength": 1, + "type": "string" + }, + "ca_only": { + "default": false, + "description": "Use the CA-only model.", + "type": "boolean" + }, + "decoding_orders": { + "default": 1, + "description": "Random decoding orders to average each score over.", + "maximum": 10, + "minimum": 1, + "type": "integer" + }, + "model_name": { + "default": "v_48_020", + "description": "Model weights version.", + "enum": [ + "v_48_002", + "v_48_010", + "v_48_020", + "v_48_030" + ], + "type": "string" + }, + "query_id": { + "description": "ID of a query (sequence or structure) to condition on.", + "format": "uuid", + "type": "string" + }, + "random_seed": { + "default": 1, + "description": "Random seed picking the decoding orders.", + "maximum": 4294967296, + "minimum": 1, + "type": "integer" + }, + "soluble_model": { + "default": false, + "description": "Use the soluble model. Always on for solublempnn.", + "type": "boolean" } }, "required": [ - "complexes" + "query_id", + "base_sequence" + ], + "type": "object" + } + }, + "svd/batch/embeddings": { + "outputs": [ + "embeddings" + ], + "params": { + "additionalProperties": false, + "description": "New sequences to project through a fitted SVD.", + "properties": { + "sequences": { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "umap/batch/embeddings": { + "outputs": [ + "embeddings" + ], + "params": { + "additionalProperties": false, + "description": "New sequences to project through a fitted SVD.", + "properties": { + "sequences": { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + } + }, + "required": [ + "sequences" ], "type": "object" } diff --git a/tests/data/test_assay_resource.py b/tests/data/test_assay_resource.py index db7d22c..33d6c02 100644 --- a/tests/data/test_assay_resource.py +++ b/tests/data/test_assay_resource.py @@ -9,7 +9,7 @@ from openprotein.data import Assay, AssayDataset, DataAPI from openprotein.data.schemas import AssayMetadata -from openprotein.errors import HTTPError +from openprotein.errors import HTTPError, JobFailedException, JobOutputsNotReady from openprotein.jobs.schemas import JobStatus METADATA = { @@ -24,6 +24,23 @@ "sequence_length": 4, } +PAGE = { + "assaymetadata": METADATA, + "page_size": 2, + "page_offset": 0, + "assaydata": [ + {"mut_sequence": "ACDE", "measurement_values": [1.0]}, + {"mut_sequence": "ACDF", "measurement_values": [2.0]}, + ], +} + + +READS = [ + pytest.param(lambda assay: assay.get_slice(0, 2), id="get_slice"), + pytest.param(lambda assay: assay.get_first(), id="get_first"), + pytest.param(lambda assay: assay._get_all(), id="_get_all"), +] + def _response(payload=None, status=200): response = MagicMock(status_code=status) @@ -31,6 +48,10 @@ def _response(payload=None, status=200): return response +def _paths(session: MagicMock) -> list[str]: + return [call.args[0] for call in session.get.call_args_list] + + @pytest.fixture def session() -> MagicMock: return MagicMock() @@ -206,3 +227,84 @@ def test_an_assay_from_session_data_pickles(): restored = pickle.loads(pickle.dumps(assay)) assert isinstance(restored, Assay) assert (restored.id, len(restored), restored.page_size) == ("a1", 100, 10) + + +@pytest.mark.parametrize("status", ["PENDING", "RUNNING"]) +@pytest.mark.parametrize("read", READS) +def test_reading_a_pending_assay_names_its_status_and_requests_no_page( + session, read, status +): + pending = METADATA | {"status": status, "align_job_id": "j1"} + session.get.return_value = _response(pending) + assay = Assay(session, AssayMetadata.model_validate(pending)) + with pytest.raises(JobOutputsNotReady, match=f"Assay a1 is {status}"): + read(assay) + session.get.assert_called_once_with( + "v1/assaydata/metadata", params={"assay_id": "a1"} + ) + + +@pytest.mark.parametrize("read", READS) +def test_reading_a_failed_assay_raises_and_requests_no_page(session, read): + failed = METADATA | {"status": "FAILURE", "align_job_id": "j1"} + session.get.return_value = _response(failed) + assay = Assay(session, AssayMetadata.model_validate(failed)) + with pytest.raises(JobFailedException, match=r"^Job j1 failed$"): + read(assay) + session.get.assert_called_once_with( + "v1/assaydata/metadata", params={"assay_id": "a1"} + ) + + +@pytest.mark.parametrize("read", READS) +def test_reading_a_canceled_assay_raises_and_requests_no_page(session, read): + canceled = METADATA | {"status": "CANCELED", "align_job_id": "j1"} + session.get.return_value = _response(canceled) + assay = Assay(session, AssayMetadata.model_validate(canceled)) + with pytest.raises(JobFailedException, match="Job j1 failed: the job was canceled"): + read(assay) + session.get.assert_called_once_with( + "v1/assaydata/metadata", params={"assay_id": "a1"} + ) + + +@pytest.mark.parametrize("status", ["SUCCESS", None]) +@pytest.mark.parametrize("read", READS) +def test_a_ready_assay_reads_its_rows_without_reading_its_metadata( + session, read, status +): + assay = Assay(session, AssayMetadata.model_validate(METADATA | {"status": status})) + session.get.return_value = _response(PAGE) + assert read(assay)["sequence"].tolist() == ["ACDE", "ACDF"] + assert _paths(session) == ["v1/assaydata/a1"] + + +def test_an_assay_ready_when_its_metadata_is_read_again_returns_its_rows(session): + pending = METADATA | {"status": "RUNNING", "align_job_id": "j1"} + assay = Assay(session, AssayMetadata.model_validate(pending)) + session.get.side_effect = [ + _response(pending | {"status": "SUCCESS"}), + _response(PAGE), + ] + assert assay.get_slice(0, 2)["sequence"].tolist() == ["ACDE", "ACDF"] + assert assay.status is JobStatus.SUCCESS + assert _paths(session) == ["v1/assaydata/metadata", "v1/assaydata/a1"] + + +def test_get_all_raises_the_first_pages_error(assay, session): + session.get.side_effect = HTTPError( + _response({"detail": "assay a1 is RUNNING"}, status=409) + ) + with pytest.raises(HTTPError) as error: + assay._get_all() + assert error.value.status_code == 409 + + +def test_get_all_returns_the_rows_read_before_a_page_fails(assay, session): + assay.page_size = 2 + session.get.side_effect = [ + _response(PAGE), + HTTPError(_response({"detail": "x"}, status=500)), + ] + assert assay._get_all()["sequence"].tolist() == ["ACDE", "ACDF"] + assert len(_paths(session)) == 2 diff --git a/tests/data/test_prompt_resource.py b/tests/data/test_prompt_resource.py index e11b627..f14d5b4 100644 --- a/tests/data/test_prompt_resource.py +++ b/tests/data/test_prompt_resource.py @@ -144,12 +144,12 @@ def test_reading_a_prompt_the_data_routes_do_not_hold_raises_the_404(session): with pytest.raises(HTTPError) as error: list(prompt) assert error.value.status_code == 404 - session.get.assert_called_once_with("v1/data/prompts/s1/download") + session.get.assert_called_once_with("v1/data/prompts/s1/content") def test_iterating_yields_each_replicate(prompt, session): assert list(prompt) == [["ACDE", "AC:DE"], ["MKVL"]] - session.get.assert_called_once_with("v1/data/prompts/p1/download") + session.get.assert_called_once_with("v1/data/prompts/p1/content") def test_len_and_indexing_read_the_replicates(prompt): diff --git a/tests/data/test_prompts_api.py b/tests/data/test_prompts_api.py index fb020e0..4650b4e 100644 --- a/tests/data/test_prompts_api.py +++ b/tests/data/test_prompts_api.py @@ -35,9 +35,7 @@ def sample_record(sample_summary) -> dict: "value": [ { "position": 0, - "value": { - "ref": {"download_url": "https://example.test/uploads/deadbeef"} - }, + "value": {"ref": {"byte_length": 0}}, } ], } @@ -115,7 +113,7 @@ def test_prompts_download_reads_the_zip(mock_session): payload = _zip_of([b">c1\nACDE\n"]) mock_session.get.return_value.content = payload assert prompts_download(mock_session, "prompt123") == payload - assert mock_session.get.call_args[0][0] == "v1/data/prompts/prompt123/download" + assert mock_session.get.call_args[0][0] == "v1/data/prompts/prompt123/content" def _http_error(status_code: int, payload: dict) -> HTTPError: @@ -198,7 +196,7 @@ def test_prompt_wrapper_methods_route_to_its_id(mock_session, sample_record): prompt = Prompt(mock_session, PromptMetadata.model_validate(sample_record)) assert list(prompt) == [["ACDE"], ["MKVL"]] - assert mock_session.get.call_args[0][0] == "v1/data/prompts/prompt123/download" + assert mock_session.get.call_args[0][0] == "v1/data/prompts/prompt123/content" prompt.update(description="d") assert mock_session.patch.call_args.kwargs["json"] == {"description": "d"} diff --git a/tests/data/test_prompts_sample.py b/tests/data/test_prompts_sample.py index 53ab71e..c1d466c 100644 --- a/tests/data/test_prompts_sample.py +++ b/tests/data/test_prompts_sample.py @@ -219,7 +219,7 @@ def test_a_sampled_prompt_reads_only_the_data_routes(mock_session): assert excinfo.value.status_code == 404 assert [call.args[0] for call in mock_session.get.call_args_list] == [ - f"v1/data/prompts/{PROMPT_ID}/download" + f"v1/data/prompts/{PROMPT_ID}/content" ] diff --git a/tests/e2e/models/test_estimators_e2e.py b/tests/e2e/models/test_estimators_e2e.py index 459f1c3..4057383 100644 --- a/tests/e2e/models/test_estimators_e2e.py +++ b/tests/e2e/models/test_estimators_e2e.py @@ -28,7 +28,7 @@ def test_an_svd_then_a_gp_on_an_embedded_assay(session: OpenProtein, mutated_seq description="estimators e2e", ) - embeddings = session.models.esm2_t6_8M_UR50D.embed(dataset) + embeddings = session.models.esm2_t6_8M_UR50D.embed(dataset, reduction="MEAN") projected = session.models.SVD(2).fit_transform(embeddings) trained = ( session.models.GP(kernel="rbf") diff --git a/tests/embeddings/test_embeddings_api.py b/tests/embeddings/test_embeddings_api.py index 471743e..563f936 100644 --- a/tests/embeddings/test_embeddings_api.py +++ b/tests/embeddings/test_embeddings_api.py @@ -150,6 +150,39 @@ def test_request_generate_post_with_query_id_list(mock_session: MagicMock): assert kwargs["json"]["use_query_structure_in_decoder"] is False +@pytest.mark.parametrize("model_id", ["poet", "poet-2"]) +def test_request_generate_post_sends_top_k_and_top_p( + mock_session: MagicMock, model_id: str +): + mock_session.post.return_value.json.return_value = { + "job_id": "job-123", + "status": JobStatus.PENDING, + "job_type": JobType.poet_generate, + "created_date": "2023-01-01T00:00:00", + } + + api.request_generate_post( + session=mock_session, + model_id=model_id, + num_samples=4, + top_k=5, + top_p=0.9, + random_seed=7, + prompt_id="prompt-1", + ) + + _, kwargs = mock_session.post.call_args + assert kwargs["json"] == { + "n_sequences": 4, + "temperature": 1.0, + "maxlen": 1000, + "top_k": 5, + "top_p": 0.9, + "seed": 7, + "prompt_id": "prompt-1", + } + + def test_request_generate_post_rejects_query_id_list_for_poet(mock_session: MagicMock): """poet v1 does not support query_id in generation (including list form).""" with pytest.raises( @@ -160,3 +193,29 @@ def test_request_generate_post_rejects_query_id_list_for_poet(mock_session: Magi model_id="poet", query_id=["q-1"], ) + + +def test_request_generate_post_takes_topk_and_topp_as_top_k_and_top_p( + mock_session: MagicMock, +): + mock_session.post.return_value.json.return_value = { + "job_id": "job-123", + "status": JobStatus.PENDING, + "job_type": JobType.poet_generate, + "created_date": "2023-01-01T00:00:00", + } + with pytest.warns(FutureWarning, match=r"topk=.*0\.19\.0.*0\.20\.0") as record: + api.request_generate_post( + session=mock_session, model_id="poet", topk=5, topp=0.9 + ) + assert {w.filename for w in record} == {__file__} + _, kwargs = mock_session.post.call_args + assert (kwargs["json"]["top_k"], kwargs["json"]["top_p"]) == (5, 0.9) + assert not {"topk", "topp"} & set(kwargs["json"]) + + +def test_request_generate_post_rejects_both_top_p_and_topp(mock_session: MagicMock): + with pytest.warns(FutureWarning), pytest.raises(TypeError, match="not both"): + api.request_generate_post( + session=mock_session, model_id="poet", top_p=0.9, topp=0.8 + ) diff --git a/tests/embeddings/test_embeddings_models.py b/tests/embeddings/test_embeddings_models.py index 00d2ddb..f5671d0 100644 --- a/tests/embeddings/test_embeddings_models.py +++ b/tests/embeddings/test_embeddings_models.py @@ -265,3 +265,62 @@ def test_a_poet_model_sends_the_id_of_a_stored_prompt_that_is_not_ready( model.embed(sequences=[b"ACGT"], prompt=prompt) assert post.call_args.kwargs["prompt_id"] == "prompt-9" + + +def _poet_model(cls, model_id): + from openprotein.prompt import PromptAPI + + session = MagicMock() + session.prompt = MagicMock(spec=PromptAPI) + with patch("openprotein.embeddings.api.get_model", return_value=MagicMock()): + return cls(session=session, model_id=model_id) + + +@pytest.mark.parametrize( + ("cls", "model_id"), [(PoETModel, "poet"), (PoET2Model, "poet-2")] +) +def test_poet_generate_takes_topk_and_topp_as_top_k_and_top_p(cls, model_id): + model = _poet_model(cls, model_id) + with ( + patch( + "openprotein.embeddings.poet.api.request_generate_post", + return_value=MagicMock(), + ) as mock_request_post, + patch( + "openprotein.embeddings.poet.EmbeddingsGenerateFuture.create", + return_value=MagicMock(), + ), + pytest.warns( + FutureWarning, match=rf"{cls.__name__}\.generate\(topk=.*0\.20\.0" + ) as record, + ): + model.generate(prompt="prompt-1", topk=5, topp=0.9) + assert len(record) == 2 + assert {w.filename for w in record} == {__file__} + _, kwargs = mock_request_post.call_args + assert (kwargs["top_k"], kwargs["top_p"]) == (5, 0.9) + assert not {"topk", "topp"} & set(kwargs) + + +@pytest.mark.parametrize( + ("cls", "model_id"), [(PoETModel, "poet"), (PoET2Model, "poet-2")] +) +def test_poet_generate_passes_top_k_and_top_p_without_warning(cls, model_id): + import warnings + + model = _poet_model(cls, model_id) + with ( + patch( + "openprotein.embeddings.poet.api.request_generate_post", + return_value=MagicMock(), + ) as mock_request_post, + patch( + "openprotein.embeddings.poet.EmbeddingsGenerateFuture.create", + return_value=MagicMock(), + ), + warnings.catch_warnings(), + ): + warnings.simplefilter("error", FutureWarning) + model.generate(prompt="prompt-1", top_k=5, top_p=0.9) + _, kwargs = mock_request_post.call_args + assert (kwargs["top_k"], kwargs["top_p"]) == (5, 0.9) diff --git a/tests/jobs/test_job_outputs.py b/tests/jobs/test_job_outputs.py index 73b33ad..90b4d40 100644 --- a/tests/jobs/test_job_outputs.py +++ b/tests/jobs/test_job_outputs.py @@ -1,18 +1,21 @@ import hashlib -import io import threading import time -from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from unittest.mock import MagicMock, patch import pytest import requests import openprotein.jobs as jobs_package -from openprotein.errors import APIError, JobFailedException, JobOutputsNotReady -from openprotein.jobs import Future, JobStatus +from openprotein.errors import ( + APIError, + HTTPError, + JobFailedException, + JobOutputsNotReady, +) +from openprotein.jobs import Future, Job, JobStatus from openprotein.jobs import _api as jobs_wire -from openprotein.jobs._storage import DirectArtifactStorage, verified_artifact +from openprotein.jobs._storage import ContentStorage, verified_artifact from openprotein.jobs.jobs import JobsAPI, _JobOutput from openprotein.jobs.schemas import _UnitRecord @@ -36,12 +39,6 @@ def test_a_future_has_no_iter_outputs(): assert not hasattr(Future, "iter_outputs") -def _jobs(session, storage): - jobs = JobsAPI(session) - jobs._storage = storage - return jobs - - def _page(entries, next_cursor=None): response = MagicMock(status_code=200) response.json.return_value = {"values": entries, "next_cursor": next_cursor} @@ -54,10 +51,8 @@ def _entry(position, unit_id, value): def _reference(payload, codec=None): return { - "uri": "s3://private/object", "byte_length": len(payload), "sha256": hashlib.sha256(payload).hexdigest(), - "s3_checksum": "checksum", "codec": codec, } @@ -82,17 +77,16 @@ def test_output_page_forwards_cursor_and_limit(): ) -def test_inline_outputs_are_lazy_ordered_and_do_not_touch_storage(): +def test_inline_outputs_are_lazy_ordered_and_make_no_content_request(): session = MagicMock() session.get.side_effect = [ _page([_entry(0, "same", {"inline": 1})], "next"), _page([_entry(1, "same", {"inline": 2})]), ] - storage = MemoryStorage(b"") - iterator = _jobs(session, storage)._iter_job_outputs("job", "score") + iterator = JobsAPI(session)._iter_job_outputs("job", "score") session.get.assert_not_called() assert list(iterator) == [_JobOutput(0, "same", 1), _JobOutput(1, "same", 2)] - assert storage.reads == 0 + assert session.get.call_count == 2 assert session.get.call_args_list[1].kwargs["params"] == {"cursor": "next"} @@ -104,15 +98,114 @@ def test_inline_values_come_back_as_stored(inline): assert output.value == inline -def test_artifact_reads_directly_and_verifies_full_content(): +def _content(*chunks): + response = MagicMock(status_code=200) + response.__enter__.return_value = response + response.iter_content.return_value = iter(chunks) + return response + + +def _session_serving(page, content): + """A session answering the page read, then every content read with `content`.""" + session = MagicMock() + session.get.side_effect = lambda path, **kwargs: ( + content() if path.endswith("/content") else page + ) + return session + + +def test_ref_bytes_are_read_from_the_content_route_and_verified(): payload = b">query\nACGT\n" + page = _page([_entry(3, "u3", {"ref": _reference(payload)})]) + session = _session_serving(page, lambda: _content(payload[:5], payload[5:])) + (entry,) = JobsAPI(session)._iter_job_outputs("job", "msa") + assert entry.value == payload + assert [c.args[0] for c in session.get.call_args_list] == [ + "v1/data/results/job/msa", + "v1/data/results/job/msa/3/content", + ] + assert session.get.call_args_list[1].kwargs == {"stream": True} + + +def test_a_position_read_reads_the_content_route_of_that_position(): + payload = b"bytes" session = MagicMock() - session.get.return_value = _page([_entry(3, "u3", {"ref": _reference(payload)})]) - storage = MemoryStorage(payload) - (entry,) = _jobs(session, storage)._iter_job_outputs("job", "msa") + entry = _entry(2, "u2", {"ref": _reference(payload)}) + session.get.side_effect = lambda path, **kwargs: ( + _content(payload) + if path.endswith("/content") + else MagicMock(status_code=200, json=lambda: entry) + ) + assert JobsAPI(session)._get_job_output("job", 2, "out").value == payload + assert session.get.call_args_list[-1].args == ("v1/data/results/job/out/2/content",) + + +def test_default_output_reads_use_the_output_the_page_names(): + payload = b"bytes" + page = _page([_entry(0, "u0", {"ref": _reference(payload)})]) + page.json.return_value["output"] = "embeddings" + session = _session_serving(page, lambda: _content(payload)) + (entry,) = JobsAPI(session)._iter_job_outputs("job", None) assert entry.value == payload - assert storage.reads == 1 - session.get.assert_called_once_with("v1/data/results/job/msa") + assert session.get.call_args_list[-1].args == ( + "v1/data/results/job/embeddings/0/content", + ) + + +def test_a_ref_in_a_page_that_names_no_output_is_rejected(): + page = _page([_entry(0, "u0", {"ref": _reference(b"x")})]) + session = _session_serving(page, lambda: _content(b"x")) + with pytest.raises(ValueError, match="do not name their output"): + list(JobsAPI(session)._iter_job_outputs("job", None)) + + +@pytest.mark.parametrize("served", [b"short", b"much longer than declared", b"wrong!!"]) +def test_content_that_differs_from_its_ref_is_rejected(served): + declared = b"exact!!" + page = _page([_entry(0, "u0", {"ref": _reference(declared)})]) + session = _session_serving(page, lambda: _content(served)) + with pytest.raises(ValueError, match="does not match"): + list(JobsAPI(session)._iter_job_outputs("job", "out")) + + +@pytest.mark.parametrize("status_code", [404, 409]) +def test_a_failed_content_request_raises_the_sessions_http_error(status_code): + payload = b"bytes" + page = _page([_entry(0, "u0", {"ref": _reference(payload)})]) + failed = HTTPError(MagicMock(status_code=status_code, text="no", url="u")) + + def get(path, **kwargs): + if path.endswith("/content"): + raise failed + return page + + session = MagicMock() + session.get.side_effect = get + with pytest.raises(HTTPError) as error: + list(JobsAPI(session)._iter_job_outputs("job", "out")) + assert error.value.status_code == status_code + + +def test_content_longer_than_its_ref_aborts_and_closes_the_stream(): + declared = b"exact" + page = _page([_entry(0, "u0", {"ref": _reference(declared)})]) + response = _content(declared, b"extra", b"never read") + session = _session_serving(page, lambda: response) + with pytest.raises(ValueError, match="does not match"): + list(JobsAPI(session)._iter_job_outputs("job", "out")) + response.__exit__.assert_called_once() + + +def test_content_storage_uses_the_given_session_and_closes_the_stream(): + session = MagicMock() + response = session.get.return_value + response.__enter__.return_value = response + response.iter_content.return_value = iter([b"con", b"tents"]) + storage = ContentStorage(session, "v1/x/content", chunk_size=3) + assert b"".join(storage.iter_bytes({})) == b"contents" + session.get.assert_called_once_with("v1/x/content", stream=True) + response.iter_content.assert_called_once_with(chunk_size=3) + response.__exit__.assert_called_once() @pytest.mark.parametrize( @@ -144,6 +237,62 @@ def test_incomplete_output_fails_without_polling(): session.get.assert_called_once_with("v1/data/results/job/embeddings") +def _read_error(status, content): + response = requests.Response() + response.status_code = status + response.url = "v1/data/results/job/embeddings/0" + response._content = content + return HTTPError(response) + + +@pytest.mark.parametrize( + ("content", "message"), + [ + (b'{"detail": "unit 0 of job job is FAILURE"}', "unit 0 of job job is FAILURE"), + (b"conflict", "unit 0 of job job is not complete yet"), + (b'{"detail": null}', "unit 0 of job job is not complete yet"), + (b'{"detail": ""}', "unit 0 of job job is not complete yet"), + ], + ids=["detail", "non-json", "null-detail", "empty-detail"], +) +def test_a_refused_unit_output_read_raises_not_ready(content, message): + session = MagicMock() + session.get.side_effect = _read_error(409, content) + with pytest.raises(JobOutputsNotReady) as raised: + jobs_wire.job_output_get(session, "job", "embeddings", 0) + assert str(raised.value) == message + assert isinstance(raised.value.__cause__, HTTPError) + session.get.assert_called_once_with("v1/data/results/job/embeddings/0") + + +@pytest.mark.parametrize("status", [404, 500]) +def test_a_unit_output_read_preserves_non_conflict_errors(status): + session = MagicMock() + error = _read_error(status, b"read failed") + session.get.side_effect = error + with pytest.raises(HTTPError) as raised: + jobs_wire.job_output_get(session, "job", "embeddings", 0) + assert raised.value is error + + +def test_a_position_read_of_a_failed_unit_raises_not_ready_without_refresh(): + session = MagicMock() + session.get.side_effect = _read_error( + 409, b'{"detail": "unit 0 of job job is FAILURE"}' + ) + job = Job.model_validate( + { + "job_id": "job", + "job_type": "/models/esm2_t33_650M_UR50D/batch/embeddings", + "status": "RUNNING", + "created_date": "2026-09-05T08:00:00Z", + } + ) + with pytest.raises(JobOutputsNotReady, match="^unit 0 of job job is FAILURE$"): + Future(session, job).get_item(0, output="embeddings") + session.get.assert_called_once_with("v1/data/results/job/embeddings/0") + + def _unit_record(position, state="SUCCESS"): return { "position": position, @@ -175,53 +324,8 @@ def test_iter_job_units_yields_unit_records_paginated_by_position(): session.get.assert_any_call("v1/jobs/job/units", params={"after_position": 5}) -def test_storage_reads_the_ref_uri_and_closes_stream(): - client = MagicMock() - client.get_object.return_value = {"Body": io.BytesIO(b"contents")} - reference = _reference(b"contents") - assert ( - b"".join(DirectArtifactStorage(client, chunk_size=3).iter_bytes(reference)) - == b"contents" - ) - client.get_object.assert_called_once_with(Bucket="private", Key="object") - assert client.get_object.return_value["Body"].closed - - -def test_signed_download_does_not_use_platform_session_or_headers(): - assert "Authorization" not in DirectArtifactStorage().http.headers - http = MagicMock() - response = http.get.return_value - response.__enter__.return_value = response - response.iter_content.return_value = iter([b"data"]) - storage = DirectArtifactStorage(http=http) - reference = {"download_url": "https://storage.example/signed"} - assert b"".join(storage.iter_bytes(reference)) == b"data" - http.get.assert_called_once_with( - "https://storage.example/signed", stream=True, timeout=180 - ) - - -def test_ref_download_url_is_used_with_no_aws_client(): - payload = b">query\nACGT\n" - response = MagicMock() - response.__enter__.return_value = response - response.iter_content.return_value = iter( - [payload[start : start + 4] for start in range(0, len(payload), 4)] - ) - reference = _reference(payload) | {"download_url": "https://storage.example/signed"} - del reference["uri"] - session = MagicMock() - session.get.return_value = _page([_entry(0, "u0", {"ref": reference})]) - with patch.object(requests.Session, "get", return_value=response) as get: - (entry,) = JobsAPI(session)._iter_job_outputs("job", "msa") - assert entry.value == payload - get.assert_called_once_with( - "https://storage.example/signed", stream=True, timeout=180 - ) - - -class SlowStorage: - """Serves each reference's payload, slower for earlier positions.""" +class _SlowContent: + """Serves each content read slower for earlier positions.""" def __init__(self, delays): self.delays = delays @@ -229,60 +333,35 @@ def __init__(self, delays): self.most = 0 self.lock = threading.Lock() - def iter_bytes(self, reference): + def get(self, path, **kwargs): + position = int(path.split("/")[-2]) with self.lock: self.running += 1 self.most = max(self.most, self.running) - time.sleep(self.delays[reference["uri"]]) + time.sleep(self.delays[position]) with self.lock: self.running -= 1 - yield reference["uri"].encode() + return _content(str(position).encode()) def test_ref_outputs_download_concurrently_and_arrive_in_position_order(): count = 40 - uris = [f"s3://private/{position}" for position in range(count)] entries = [ - _entry( - position, f"u{position}", {"ref": _reference(uri.encode()) | {"uri": uri}} - ) - for position, uri in enumerate(uris) + _entry(position, f"u{position}", {"ref": _reference(str(position).encode())}) + for position in range(count) ] + pages = iter([_page(entries[:25], "next"), _page(entries[25:])]) + slow = _SlowContent([0.02 * (count - i) / count for i in range(count)]) session = MagicMock() - session.get.side_effect = [_page(entries[:25], "next"), _page(entries[25:])] - storage = SlowStorage( - {uri: 0.02 * (count - i) / count for i, uri in enumerate(uris)} + session.get.side_effect = lambda path, **kwargs: ( + slow.get(path) if path.endswith("/content") else next(pages) ) - outputs = list(_jobs(session, storage)._iter_job_outputs("job", "embeddings")) + outputs = list(JobsAPI(session)._iter_job_outputs("job", "embeddings")) assert [output.position for output in outputs] == list(range(count)) - assert [output.value for output in outputs] == [uri.encode() for uri in uris] - assert storage.most > 1 - - -def test_signed_download_retries_object_storage_5xx(): - requests_seen = [] - - class Flaky(BaseHTTPRequestHandler): - def do_GET(self): - requests_seen.append(self.path) - status, body = (500, b"") if len(requests_seen) == 1 else (200, b"data") - self.send_response(status) - self.send_header("Content-Length", str(len(body))) - self.end_headers() - self.wfile.write(body) - - def log_message(self, *args): - pass - - server = ThreadingHTTPServer(("127.0.0.1", 0), Flaky) - threading.Thread(target=server.serve_forever, daemon=True).start() - try: - url = f"http://127.0.0.1:{server.server_port}/signed" - data = b"".join(DirectArtifactStorage().iter_bytes({"download_url": url})) - finally: - server.shutdown() - assert data == b"data" - assert requests_seen == ["/signed", "/signed"] + assert [output.value for output in outputs] == [ + str(position).encode() for position in range(count) + ] + assert slow.most > 1 def _emitted_page(entries, next_cursor, complete=False): @@ -348,7 +427,9 @@ def test_a_failed_emitted_item_raises_with_its_error(): def test_an_invalid_output_position_is_a_value_error(position): with pytest.raises(ValueError, match="nonnegative integer"): JobsAPI(MagicMock())._decode_job_output( - "job", {"position": position, "unit_id": "u", "value": {"inline": 1}} + "job", + "out", + {"position": position, "unit_id": "u", "value": {"inline": 1}}, ) diff --git a/tests/jobs/test_model_result_contracts.py b/tests/jobs/test_model_result_contracts.py index 629ee27..fb5a936 100644 --- a/tests/jobs/test_model_result_contracts.py +++ b/tests/jobs/test_model_result_contracts.py @@ -15,7 +15,6 @@ from openprotein.predictor.api import decode_predict API = "https://api.example/" -ARTIFACT = "https://storage.example/signed" PREDICTION_DATA = ( Path(__file__).resolve().parents[1] / "data" / "model_result_contracts" ) @@ -80,11 +79,9 @@ def test_affinity_json_ref_decodes_for_item_and_page(jobs, monkeypatch): "state": "SUCCESS", "value": { "ref": { - "uri": "s3://content/affinity", "byte_length": len(payload), "sha256": hashlib.sha256(payload).hexdigest(), "codec": "json-utf8-v1", - "download_url": ARTIFACT, } }, } @@ -92,11 +89,10 @@ def test_affinity_json_ref_decodes_for_item_and_page(jobs, monkeypatch): def request(session, method, url, **kwargs): assert method == "GET" - if url == ARTIFACT: + if url == API + "v1/data/results/job/affinity/0/content": downloads.append(url) - assert session.auth is None - assert "Authorization" not in session.headers - assert "Authorization" not in kwargs.get("headers", {}) + assert session.auth is not None + assert kwargs["stream"] is True return response(200, url, payload) if url == API + "v1/data/results/job/affinity/0": body = entry @@ -110,7 +106,7 @@ def request(session, method, url, **kwargs): assert [output.value for output in jobs._iter_job_outputs("job", "affinity")] == [ expected ] - assert downloads == [ARTIFACT, ARTIFACT] + assert downloads == [API + "v1/data/results/job/affinity/0/content"] * 2 def test_prediction_inline_values_preserve_quoted_property(jobs, monkeypatch): diff --git a/tests/jobs/test_results_by_codec.py b/tests/jobs/test_results_by_codec.py index 18d1752..f16d25a 100644 --- a/tests/jobs/test_results_by_codec.py +++ b/tests/jobs/test_results_by_codec.py @@ -25,41 +25,32 @@ from openprotein.jobs.jobs import JobsAPI -def _jobs(session, storage): - jobs = JobsAPI(session) - jobs._storage = storage - return jobs - - -class MemoryStorage: - def __init__(self, payload: bytes): - self.payload = payload - - def iter_bytes(self, reference): - yield self.payload - - def _read(payload: bytes, codec: str | None): """Read position 0 of a mocked `/data/results/job/out/0` holding `payload`.""" - session = MagicMock() - session.get.return_value.json.return_value = { + entry = { "position": 0, "unit_id": "unit", "state": "SUCCESS", "value": { "ref": { - "uri": "s3://content/abc", "byte_length": len(payload), "sha256": hashlib.sha256(payload).hexdigest(), - "s3_checksum": "checksum", "codec": codec, - "download_url": "https://storage.example/signed", } }, } - jobs = _jobs(session, MemoryStorage(payload)) - output = jobs._get_job_output("job", 0, "out") - session.get.assert_called_once_with("v1/data/results/job/out/0") + content = MagicMock() + content.__enter__.return_value = content + content.iter_content.return_value = iter([payload]) + session = MagicMock() + session.get.side_effect = lambda path, **kwargs: ( + content if path.endswith("/content") else MagicMock(json=lambda: entry) + ) + output = JobsAPI(session)._get_job_output("job", 0, "out") + assert [c.args[0] for c in session.get.call_args_list] == [ + "v1/data/results/job/out/0", + "v1/data/results/job/out/0/content", + ] return output.value @@ -153,27 +144,32 @@ def test_registered_codec_decodes_its_refs(): def test_ref_bytes_are_verified_before_decoding(): - session = MagicMock() - session.get.return_value.json.return_value = { + entry = { "position": 0, "unit_id": "unit", "state": "SUCCESS", "value": { "ref": { - "uri": "s3://content/abc", "byte_length": 3, "sha256": "0" * 64, "codec": "fasta-utf8-v1", } }, } + content = MagicMock() + content.__enter__.return_value = content + content.iter_content.return_value = iter([b"abc"]) + session = MagicMock() + session.get.side_effect = lambda path, **kwargs: ( + content if path.endswith("/content") else MagicMock(json=lambda: entry) + ) with pytest.raises(ValueError, match="digest"): - _jobs(session, MemoryStorage(b"abc"))._get_job_output("job", 0, "out") + JobsAPI(session)._get_job_output("job", 0, "out") @pytest.mark.parametrize("value", [{"inline": 1, "ref": {}}, {}, {"ref": "uri"}]) def test_malformed_values_are_rejected(value): with pytest.raises((ValueError, TypeError)): JobsAPI(MagicMock())._decode_job_output( - "job", {"position": 0, "unit_id": "u", "value": value} + "job", "out", {"position": 0, "unit_id": "u", "value": value} ) diff --git a/tests/models/conftest.py b/tests/models/conftest.py index d604ea9..d384d97 100644 --- a/tests/models/conftest.py +++ b/tests/models/conftest.py @@ -8,21 +8,14 @@ from openprotein.align import AlignAPI from openprotein.jobs import Future, Job, JobsAPI, JobStatus from openprotein.jobs import _api as jobs_api -from openprotein.jobs._storage import DirectArtifactStorage from openprotein.models.schemas import MethodDescriptor from openprotein.molecules import Complex from tests.models.support import ModelsSession, card @pytest.fixture -def models_session(monkeypatch) -> ModelsSession: - session = ModelsSession() - monkeypatch.setattr( - DirectArtifactStorage, - "iter_bytes", - lambda self, reference: iter([session.blobs[reference["uri"]]]), - ) - return session +def models_session() -> ModelsSession: + return ModelsSession() @pytest.fixture diff --git a/tests/models/support.py b/tests/models/support.py index cb43cd2..99bdd8e 100644 --- a/tests/models/support.py +++ b/tests/models/support.py @@ -170,11 +170,9 @@ def _value(self, job_id: str, output: str, position: int) -> dict[str, Any]: value = self.outputs[(job_id, output)][position] if not isinstance(value, Stored): return {"inline": value} - uri = f"s3://results/{job_id}/{output}/{position}" - self.blobs[uri] = value.data + self.blobs[f"v1/data/results/{job_id}/{output}/{position}/content"] = value.data return { "ref": { - "uri": uri, "byte_length": len(value.data), "sha256": hashlib.sha256(value.data).hexdigest(), "codec": value.codec, @@ -195,7 +193,16 @@ def _results(self, job_id: str, output: str) -> dict[str, Any]: "next_cursor": None, } + def _content(self, data: bytes) -> MagicMock: + response = MagicMock(status_code=200) + response.__enter__.return_value = response + response.iter_content.side_effect = lambda chunk_size: iter([data]) + return response + def _get(self, path: str, **kwargs: Any) -> MagicMock: + if path.endswith("/content"): + assert kwargs.get("stream") is True + return self._content(self.blobs[path]) if path in self.get_routes: return self._response(self.get_routes[path]) if path.startswith("v1/data/results/"): diff --git a/tests/models/test_deprecated_names.py b/tests/models/test_deprecated_names.py index cac5ecb..23fe90c 100644 --- a/tests/models/test_deprecated_names.py +++ b/tests/models/test_deprecated_names.py @@ -1,10 +1,13 @@ import importlib +import pkgutil +import subprocess +import sys import pytest import openprotein.models.models as models_module from openprotein import models -from openprotein.models import ModelsAPI +from openprotein.models import ModelsAPI, fold, foundation MOVED = [ *( @@ -37,9 +40,15 @@ ] -def _message(name: str, use: str) -> str: +def _message( + name: str, + use: str, + since: str = "0.18.0", + removed_in: str = "0.19.0", +) -> str: return ( - f"`{name}` is deprecated since 0.18.0 and will be removed in 0.19.0. Use {use}." + f"`{name}` is deprecated since {since} and will be removed in {removed_in}. " + f"Use {use}." ) @@ -117,8 +126,9 @@ def test_inverse_folding_generate_takes_seed_as_random_seed(models_session, mode handle = getattr(ModelsAPI(models_session.session), model) with pytest.warns( FutureWarning, match=r"generate\(seed=\.\.\.\).*0\.18\.0.*0\.19\.0" - ): + ) as record: handle.generate(query=QUERY_UUID, seed=7) + assert record[0].filename == __file__ assert models_session.submitted[1]["random_seed"] == 7 assert "seed" not in models_session.submitted[1] @@ -128,8 +138,9 @@ def test_inverse_folding_single_site_takes_sequence_as_base_sequence( models_session, model ): handle = getattr(ModelsAPI(models_session.session), model) - with pytest.warns(FutureWarning, match=r"single_site\(sequence=\.\.\.\)"): + with pytest.warns(FutureWarning, match=r"single_site\(sequence=\.\.\.\)") as record: handle.single_site(sequence="MKT", query=QUERY_UUID) + assert record[0].filename == __file__ assert models_session.submitted[1]["base_sequence"] == "MKT" @@ -145,3 +156,163 @@ def test_inverse_folding_refuses_both_keyword_forms(models_session, call): with pytest.warns(FutureWarning), pytest.raises(TypeError, match="not both"): call(ModelsAPI(models_session.session)) models_session.session.post.assert_not_called() + + +ALIASES = [ + ("openprotein.models.folding", fold, ("base", "boltz2")), + ("openprotein.models.foundational", foundation, ("base", "poet")), +] + + +def _alias_names(): + return [(old, new, name) for old, new, _ in ALIASES for name in new.__all__] + + +@pytest.mark.parametrize(("old", "new", "name"), _alias_names()) +def test_alias_names_resolve_to_the_new_package_objects_and_warn(old, new, name): + alias = importlib.import_module(old) + with pytest.warns(FutureWarning) as record: + resolved = getattr(alias, name) + assert resolved is getattr(new, name) + assert [str(w.message) for w in record] == [ + _message( + f"{old}.{name}", + f"`{new.__name__}.{name}`", + since="0.19.0", + removed_in="0.20.0", + ) + ] + assert record[0].filename == __file__ + + +@pytest.mark.parametrize( + ("old", "new", "submodule"), + [(old, new, sub) for old, new, subs in ALIASES for sub in subs], +) +def test_alias_submodules_are_the_new_package_submodules(old, new, submodule): + assert importlib.import_module(f"{old}.{submodule}") is importlib.import_module( + f"{new.__name__}.{submodule}" + ) + + +@pytest.mark.parametrize(("old", "new", "_"), ALIASES) +def test_alias_unknown_name_raises_attribute_error(old, new, _): + alias = importlib.import_module(old) + with pytest.raises(AttributeError, match="has no attribute 'Nope'"): + getattr(alias, "Nope") # noqa: B009 + + +def _submodules(new): + return sorted(m.name for m in pkgutil.iter_modules(new.__path__)) + + +@pytest.mark.parametrize( + ("old", "new", "submodule"), + [(old, new, sub) for old, new, _ in ALIASES for sub in _submodules(new)], +) +def test_alias_submodule_attributes_are_the_new_package_submodules_and_warn( + old, new, submodule +): + alias = importlib.import_module(old) + with pytest.warns(FutureWarning) as record: + resolved = getattr(alias, submodule) + assert resolved is getattr(new, submodule) + assert [str(w.message) for w in record] == [ + _message( + f"{old}.{submodule}", + f"`{new.__name__}.{submodule}`", + since="0.19.0", + removed_in="0.20.0", + ) + ] + assert record[0].filename == __file__ + + +@pytest.mark.parametrize(("old", "new", "_"), ALIASES) +def test_alias_star_import_binds_every_new_package_name(old, new, _): + namespace: dict = {} + with pytest.warns(FutureWarning): + exec(f"from {old} import *", namespace) # noqa: S102 + for name in new.__all__: + assert namespace[name] is getattr(new, name) + + +def _run(*args: str) -> subprocess.CompletedProcess: + return subprocess.run( + [sys.executable, *args], capture_output=True, text=True, check=False + ) + + +def test_alias_is_reachable_from_the_sdk_and_warns_in_a_fresh_interpreter(): + script = ( + "import warnings\n" + "warnings.simplefilter('always')\n" + "import openprotein\n" + "openprotein.models.folding.ESMFold\n" + ) + result = _run("-c", script) + assert result.returncode == 0, result.stderr + assert ( + "`openprotein.models.folding.ESMFold` is deprecated since 0.19.0" + in result.stderr + ) + + +@pytest.mark.parametrize( + ("statement", "package"), + [ + ( + "from openprotein.models.folding.boltz2 import Boltz2", + "openprotein.models.folding", + ), + ( + "import openprotein.models.foundational.poet", + "openprotein.models.foundational", + ), + ( + "from openprotein.models.foundational import poet", + "openprotein.models.foundational", + ), + ], +) +def test_importing_an_alias_submodule_warns(statement, package): + result = _run("-W", "error::FutureWarning", "-c", statement) + assert result.returncode != 0 + assert f"`{package}` is deprecated since 0.19.0" in result.stderr + + +@pytest.mark.parametrize( + "package", ["openprotein.models.folding", "openprotein.models.foundational"] +) +@pytest.mark.parametrize( + "statement", + [ + "import {package}", + "from openprotein.models import {name}", + "import openprotein; openprotein.models.{name}", + ], +) +def test_alias_import_warning_points_at_the_importing_line(package, statement): + name = package.rpartition(".")[2] + script = ( + "import warnings\n" + "with warnings.catch_warnings(record=True) as record:\n" + " warnings.simplefilter('always')\n" + f" {statement.format(package=package, name=name)}\n" + f"print([w.filename for w in record if '`{package}`' in str(w.message)])" + ) + result = _run("-c", script) + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == "['']" + + +def test_importing_the_sdk_raises_no_future_warning_and_loads_no_alias(): + script = ( + "import sys, openprotein, openprotein.models\n" + "aliases = ('openprotein.models.folding', 'openprotein.models.foundational')\n" + "assert not any(name in sys.modules for name in aliases)" + ) + subprocess.run( + [sys.executable, "-W", "error::FutureWarning", "-c", script], + check=True, + ) diff --git a/tests/models/test_ensemble_models.py b/tests/models/test_ensemble_models.py index 2967270..995f203 100644 --- a/tests/models/test_ensemble_models.py +++ b/tests/models/test_ensemble_models.py @@ -102,7 +102,10 @@ def test_unset_controls_send_the_card_defaults(models_session, model_id): path, body = models_session.submitted assert path == f"v1/models/{model_id}/batch/structures" expected = CARD_DEFAULTS[HANDLES[model_id]] - assert {name: body[name] for name in expected} == expected + sent = {name: value for name, value in expected.items() if value is not None} + unset = [name for name, value in expected.items() if value is None] + assert {name: body[name] for name in sent} == sent + assert not set(unset) & set(body) def test_bioemu_sends_one_protein_per_input(models_session): @@ -223,7 +226,7 @@ def test_flow_references_are_given_for_every_input_or_none( models_session.session.post.assert_not_called() -@pytest.mark.parametrize("seed", [None, 0, 7]) +@pytest.mark.parametrize("seed", [0, 7]) def test_explicit_seed_value_is_sent(models_session, seed): ModelsAPI(models_session.session).bioemu_v1_1.sample( [BioEmuInput("MKT", msa=None)], random_seed=seed @@ -231,6 +234,13 @@ def test_explicit_seed_value_is_sent(models_session, seed): assert models_session.submitted[1]["random_seed"] == seed +def test_a_none_seed_is_not_sent(models_session): + ModelsAPI(models_session.session).bioemu_v1_1.sample( + [BioEmuInput("MKT", msa=None)], random_seed=None + ) + assert "random_seed" not in models_session.submitted[1] + + @pytest.mark.parametrize( ("model_id", "name", "value"), [ diff --git a/tests/models/test_estimators.py b/tests/models/test_estimators.py index 4651ac8..6c5ffdc 100644 --- a/tests/models/test_estimators.py +++ b/tests/models/test_estimators.py @@ -6,9 +6,10 @@ import pandas as pd import pytest -from openprotein.data import AssayDataset, DataAPI +from openprotein.data import Assay, AssayDataset, DataAPI +from openprotein.data.schemas import AssayMetadata from openprotein.embeddings.future import EmbeddingsResultFuture -from openprotein.errors import HTTPError, JobFailedException +from openprotein.errors import HTTPError, JobFailedException, JobOutputsNotReady from openprotein.jobs import Future, Job from openprotein.jobs import futures as results from openprotein.jobs.futures import ( @@ -65,7 +66,7 @@ def test_it_is_named_by_id_and_stays_on_the_future(self, models, models_session) future = models.esm2.embed(assay) - body = {"assay_id": ASSAY, "reduction": "MEAN"} + body = {"assay_id": ASSAY} assert models_session.submitted == ( f"v1/models/{ESM2}/batch/embeddings", body, @@ -84,12 +85,42 @@ def test_a_projection_sends_its_sequences(self, models, models_session): assert isinstance(future, results.EmbeddingFuture) assert future.dataset is assay + def test_an_unset_reduction_is_left_to_the_server(self, models, models_session): + models.esm2.embed(SEQUENCES) + + assert "reduction" not in models_session.submitted[1] + + def test_a_pending_assay_is_refused_before_anything_is_submitted( + self, models, models_session + ): + pending = { + "assay_name": "copy", + "assay_description": "", + "assay_id": ASSAY, + "original_filename": "data.csv", + "created_date": "2026-11-25T00:00:00Z", + "num_rows": 4, + "num_entries": 4, + "measurement_names": ["fitness"], + "status": "RUNNING", + "align_job_id": "j1", + } + models_session.get_routes["v1/assaydata/metadata"] = pending + assay = Assay(models_session.session, AssayMetadata.model_validate(pending)) + + with pytest.raises(JobOutputsNotReady, match=f"Assay {ASSAY} is RUNNING"): + models.get_model("svd/s-1").transform(assay) + + assert models_session.submissions == [] + paths = [call.args[0] for call in models_session.session.get.call_args_list] + assert f"v1/assaydata/{ASSAY}" not in paths + def test_sequences_leave_no_dataset(self, models): future = models.esm2.embed(SEQUENCES, reduction=None) assert future.dataset is None assert future._submission == _Submission( - ESM2, "batch/embeddings", {"sequences": SEQUENCES, "reduction": None} + ESM2, "batch/embeddings", {"sequences": SEQUENCES} ) diff --git a/tests/models/test_future_results.py b/tests/models/test_future_results.py index a8e3478..91a3342 100644 --- a/tests/models/test_future_results.py +++ b/tests/models/test_future_results.py @@ -264,13 +264,12 @@ def test_stream_decodes_canonical_references_in_position_order( ): job_id = JOB["job_id"] payloads = [_vector_bytes([1.0]), _vector_bytes([2.0])] - from openprotein.jobs._storage import DirectArtifactStorage - monkeypatch.setattr( - DirectArtifactStorage, - "iter_bytes", - lambda self, ref: iter([payloads[int(ref["uri"].rsplit("/", 1)[1])]]), - ) + def content(data): + response = MagicMock(status_code=200) + response.__enter__.return_value = response + response.iter_content.return_value = iter([data]) + return response def handler(path, **kwargs): response = MagicMock(status_code=200) @@ -290,7 +289,6 @@ def handler(path, **kwargs): "unit_id": f"u{position}", "value": { "ref": { - "uri": f"s3://content/{position}", "byte_length": len(payload), "sha256": hashlib.sha256(payload).hexdigest(), "codec": "ndarray-v1", @@ -301,6 +299,10 @@ def handler(path, **kwargs): ], "next_cursor": None, } + elif path.startswith(f"v1/data/results/{job_id}/embeddings/"): + position = int(path.split("/")[-2]) + assert path.endswith("/content") and kwargs == {"stream": True} + return content(payloads[position]) else: raise AssertionError(f"unexpected GET {path}") return response diff --git a/tests/models/test_future_unit.py b/tests/models/test_future_unit.py index 8994b79..b71a030 100644 --- a/tests/models/test_future_unit.py +++ b/tests/models/test_future_unit.py @@ -1,6 +1,8 @@ """One unit of a models job, handled on its own.""" import inspect +import json +from collections.abc import Callable from typing import Any from unittest.mock import MagicMock @@ -9,7 +11,13 @@ from requests import Response import openprotein.jobs as jobs_package -from openprotein.errors import APIError, HTTPError, JobFailedException, TimeoutException +from openprotein.errors import ( + APIError, + HTTPError, + JobFailedException, + JobOutputsNotReady, + TimeoutException, +) from openprotein.jobs import Job, JobStatus from openprotein.jobs.futures import ( EmbeddingFuture, @@ -257,88 +265,171 @@ def test_inline_values_come_back_as_stored(self, future): assert future.unit(0, output="annotations").get() == "some text" -def _not_found(path: str) -> HTTPError: +DETAIL = {404: "no output is stored", 409: "unit 0 of job job-1 is FAILURE"} + + +def _read_error(path: str, code: int) -> HTTPError: response = Response() - response.status_code = 404 + response.status_code = code response.url = path - response._content = b'{"detail": "no output is stored"}' + response._content = json.dumps({"detail": DETAIL[code]}).encode() return HTTPError(response) +def _future_whose_reads_fail( + mock_session, serve: Callable[..., MagicMock], code: int +) -> Future: + """A future whose output reads answer ``code``, and ``serve`` the rest.""" + + def handler(path: str, **kwargs: Any) -> MagicMock: + if "/results" in path: + raise _read_error(path, code) + return serve(path, **kwargs) + + mock_session.get.side_effect = handler + return Future(mock_session, Job.model_validate(JOB)) + + +UNREADABLE = pytest.mark.parametrize("code", [404, 409]) + + +def _record_read_errors(monkeypatch, future: Future) -> list[Exception]: + """Collect every error ``future.get_item`` raises, as raised.""" + errors: list[Exception] = [] + get_item = future.get_item + + def recording(*args: Any, **kwargs: Any) -> Any: + try: + return get_item(*args, **kwargs) + except Exception as error: + errors.append(error) + raise + + monkeypatch.setattr(future, "get_item", recording) + return errors + + class TestFailedUnitRead: def test_get_raises_for_a_snapshot_that_is_failed(self, mock_session): - future = _future_in(mock_session, "FAILED", error={"message": "boom"}) + future = _future_in(mock_session, "FAILURE", error={"message": "boom"}) unit = future.units[0] + mock_session.get.reset_mock() with pytest.raises(JobFailedException) as raised: unit.get() assert raised.value.failure_message == "unit 0 failed: boom" + mock_session.get.assert_not_called() def test_get_raises_for_a_snapshot_that_is_canceled(self, mock_session): unit = _future_in(mock_session, "CANCELED").units[0] + mock_session.get.reset_mock() with pytest.raises(JobFailedException) as raised: unit.get() assert raised.value.failure_message == "unit 0 was canceled" + mock_session.get.assert_not_called() - def test_a_missing_output_refreshes_and_raises_for_a_failed_unit( - self, mock_session + @pytest.mark.parametrize( + ("state", "error", "message", "code"), + [ + ("FAILURE", {"message": "boom"}, "unit 0 failed: boom", 404), + ("FAILURE", {"message": "boom"}, "unit 0 failed: boom", 409), + ("CANCELED", None, "unit 0 was canceled", 404), + ("CANCELED", None, "unit 0 was canceled", 409), + pytest.param( + "FAILED", + {"message": "boom"}, + "unit 0 failed: boom", + 404, + id="failed-record-404", + ), + ], + ) + def test_an_unreadable_output_of_a_failed_or_canceled_unit_raises_job_failed( + self, mock_session, code, state, error, message ): - recorder = _Recorder(state="FAILED", error={"message": "boom"}) - - def handler(path: str, **kwargs: Any) -> MagicMock: - if "/results" in path: - raise _not_found(path) - return recorder(path, **kwargs) - - mock_session.get.side_effect = handler - unit = Future(mock_session, Job.model_validate(JOB)).unit( + recorder = _Recorder(state=state, error=error) + unit = _future_whose_reads_fail(mock_session, recorder, code).unit( 0, output="embeddings" ) with pytest.raises(JobFailedException) as raised: unit.get() - assert raised.value.failure_message == "unit 0 failed: boom" + assert raised.value.failure_message == message assert recorder.unit_reads(0) == 1 - def test_a_missing_output_of_a_live_unit_raises_the_not_found(self, mock_session): - recorder = _Recorder(state="RUNNING") - - def handler(path: str, **kwargs: Any) -> MagicMock: - if "/results" in path: - raise _not_found(path) - return recorder(path, **kwargs) - - mock_session.get.side_effect = handler - unit = Future(mock_session, Job.model_validate(JOB)).unit( + @UNREADABLE + @pytest.mark.parametrize("state", ["PENDING", "RUNNING"]) + def test_an_unreadable_output_of_an_unfinished_unit_raises_not_ready( + self, mock_session, code, state + ): + recorder = _Recorder(state=state) + unit = _future_whose_reads_fail(mock_session, recorder, code).unit( 0, output="embeddings" ) + with pytest.raises(JobOutputsNotReady) as raised: + unit.get() + + assert str(raised.value) == f"unit 0 of job job-1 is {state}" + assert recorder.unit_reads(0) == 1 + + def test_a_missing_output_of_a_succeeded_unit_raises_the_not_found( + self, mock_session, monkeypatch + ): + recorder = _Recorder(state="SUCCESS") + future = _future_whose_reads_fail(mock_session, recorder, 404) + read_errors = _record_read_errors(monkeypatch, future) + unit = future.unit(0, output="embeddings") + with pytest.raises(HTTPError) as raised: unit.get() + assert raised.value is read_errors[0] assert raised.value.status_code == 404 assert recorder.unit_reads(0) == 1 - def test_a_failing_refresh_keeps_the_not_found_as_the_error(self, mock_session): - def handler(path: str, **kwargs: Any) -> MagicMock: - if "/results" in path: - raise _not_found(path) - raise ConnectionError("refresh failed") + def test_a_refused_read_of_a_unit_that_has_since_succeeded_raises_not_ready( + self, mock_session, monkeypatch + ): + recorder = _Recorder(state="SUCCESS") + future = _future_whose_reads_fail(mock_session, recorder, 409) + read_errors = _record_read_errors(monkeypatch, future) + unit = future.unit(0, output="embeddings") - mock_session.get.side_effect = handler - unit = Future(mock_session, Job.model_validate(JOB)).unit( - 0, output="embeddings" - ) + with pytest.raises(JobOutputsNotReady) as raised: + unit.get() - with pytest.raises(HTTPError) as raised: + assert raised.value is read_errors[0] + assert str(raised.value) == DETAIL[409] + assert recorder.unit_reads(0) == 1 + + @UNREADABLE + def test_a_failing_refresh_keeps_the_read_error( + self, mock_session, monkeypatch, code + ): + refresh_error = ConnectionError("refresh failed") + + def refresh_fails(path: str, **kwargs: Any) -> MagicMock: + raise refresh_error + + future = _future_whose_reads_fail(mock_session, refresh_fails, code) + read_errors = _record_read_errors(monkeypatch, future) + unit = future.unit(0, output="embeddings") + + expected_error = HTTPError if code == 404 else JobOutputsNotReady + with pytest.raises(expected_error) as raised: unit.get() - assert raised.value.status_code == 404 - assert isinstance(raised.value.__cause__, ConnectionError) + assert raised.value is read_errors[0] + if code == 404: + assert isinstance(raised.value, HTTPError) + assert raised.value.status_code == 404 + assert DETAIL[code] in str(raised.value) + assert raised.value.__cause__ is refresh_error def test_a_successful_read_requests_no_unit_status(self, future, recorder): future.unit(0, output="embeddings").get() @@ -401,7 +492,7 @@ def test_wait_times_out_on_an_unfinished_unit(self, mock_session): future.unit(0).wait(timeout=0) def test_a_failed_unit_raises_job_failed_with_its_error_message(self, mock_session): - future = _future_in(mock_session, "FAILED", error={"message": "out of memory"}) + future = _future_in(mock_session, "FAILURE", error={"message": "out of memory"}) with pytest.raises(JobFailedException) as raised: future.unit(0).wait() @@ -410,7 +501,7 @@ def test_a_failed_unit_raises_job_failed_with_its_error_message(self, mock_sessi assert raised.value.failure_message == "unit 0 failed: out of memory" def test_a_failed_unit_without_a_message_raises_job_failed(self, mock_session): - future = _future_in(mock_session, "FAILED") + future = _future_in(mock_session, "FAILURE") with pytest.raises(JobFailedException) as raised: future.unit(1).wait() diff --git a/tests/models/test_handles.py b/tests/models/test_handles.py index c1967cd..36a57ea 100644 --- a/tests/models/test_handles.py +++ b/tests/models/test_handles.py @@ -1,7 +1,6 @@ """Family handles convert SDK objects to card params.""" import copy -import inspect from typing import Any from unittest.mock import MagicMock @@ -110,12 +109,22 @@ def post(path, **kwargs): assert first == second assert "random_seed" not in first[1] - def test_a_scoring_seed_with_a_card_default_is_left_to_the_card( - self, models, models_session - ): + def test_a_scoring_seed_defaults_to_the_card_default(self, models, models_session): models.proteinmpnn.score(["MKT"], query=QUERY_UUID) - assert "random_seed" not in models_session.submitted[1] + assert models_session.submitted[1]["random_seed"] == 1 + + +class TestUnsetParams: + def test_a_none_param_is_not_sent(self, models, models_session): + models.esmfold.fold("MKT", num_recycles=None) + + assert "num_recycles" not in models_session.submitted[1] + + def test_a_given_param_is_sent(self, models, models_session): + models.esmfold.fold("MKT", num_recycles=4) + + assert models_session.submitted[1]["num_recycles"] == 4 class TestPrompt: @@ -213,7 +222,14 @@ def test_a_design_is_sent_as_its_id_whatever_its_status( assert models_session.submitted == ( "v1/models/proteinmpnn/generate/sequences", - {"design_id": DESIGN_UUID, "random_seed": 1}, + { + "design_id": DESIGN_UUID, + "random_seed": 1, + "num_samples": 100, + "temperature": 0.1, + **MPNN_WEIGHTS, + **MPNN_PSSM, + }, ) assert models_session.queries == [] @@ -222,7 +238,7 @@ def test_a_design_id_is_sent_as_it_is(self, models, models_session): assert models_session.submitted == ( "v1/models/esm-if1/generate/sequences", - {"design_id": DESIGN_UUID}, + {"design_id": DESIGN_UUID, "num_samples": 100, "temperature": 1.0}, ) def test_a_legacy_structure_generation_future_sends_its_id( @@ -241,6 +257,8 @@ def test_a_legacy_structure_generation_future_sends_its_id( assert models_session.submitted[1] == { "design_id": DESIGN_UUID, "random_seed": 1, + "num_samples": 100, + "temperature": 1.0, } @pytest.mark.parametrize( @@ -434,22 +452,28 @@ def test_esm2_and_esmc_score_single_site_mutants( ) @pytest.mark.parametrize("alias", ["prot_seq", "ablang2", "prott5_xl", "poet"]) - def test_embed_pools_by_mean_by_default(self, models, models_session, alias): + def test_embed_leaves_an_unset_reduction_to_the_server( + self, models, models_session, alias + ): getattr(models, alias).embed(["MKT"]) - assert models_session.submitted[1]["reduction"] == "MEAN" + assert "reduction" not in models_session.submitted[1] def test_embed_none_is_per_residue(self, models, models_session): models.prot_seq.embed(["MKT"], reduction=None) - assert models_session.submitted[1]["reduction"] is None + assert "reduction" not in models_session.submitted[1] def test_logits_pass_chain_params(self, models, models_session): models.prot_seq.logits(["MKT:AC"], chain_mode="independent") assert models_session.submitted == ( "v1/models/prot-seq/batch/logits", - {"sequences": ["MKT:AC"], "chain_mode": "independent"}, + { + "sequences": ["MKT:AC"], + "chain_mode": "independent", + "chain_linker": "GGGGSGGGGSGGGGS", + }, ) def test_fit_svd_submits_the_fit(self, models, models_session): @@ -593,7 +617,17 @@ def test_single_site_forwards_include_gaps( assert models_session.submitted == ( f"v1/models/{model_id}/single-site/scores", - {"base_sequence": "A-:C-", "prompt_id": "prompt-1", **params}, + { + "base_sequence": "A-:C-", + "include_gaps": False, + **( + {"use_query_structure_in_decoder": True} + if handle == "poet2" + else {} + ), + "prompt_id": "prompt-1", + **params, + }, ) def test_single_site_takes_the_prompt_and_query(self, models, models_session): @@ -601,10 +635,25 @@ def test_single_site_takes_the_prompt_and_query(self, models, models_session): assert models_session.submitted == ( "v1/models/poet-2/single-site/scores", - {"base_sequence": "MKT", "prompt_id": "prompt-1", "query_id": QUERY_UUID}, + { + "base_sequence": "MKT", + "include_gaps": False, + "use_query_structure_in_decoder": True, + "prompt_id": "prompt-1", + "query_id": QUERY_UUID, + }, ) +MPNN_WEIGHTS = {"model_name": "v_48_020", "ca_only": False, "soluble_model": False} +MPNN_PSSM = { + "pssm_multi": 0.0, + "pssm_threshold": 0.0, + "pssm_bias": False, + "pssm_log_odds": False, +} + + class TestInverseFolding: @pytest.mark.parametrize("alias", ["proteinmpnn", "solublempnn", "esmif1"]) def test_scoring_sends_the_query(self, models, models_session, alias): @@ -612,19 +661,23 @@ def test_scoring_sends_the_query(self, models, models_session, alias): model.score(["MKT"], query=QUERY_UUID) model.single_site("MKT", query=QUERY_UUID) + weights = {} if alias == "esmif1" else {**MPNN_WEIGHTS, "decoding_orders": 1} + seed = {} if alias == "esmif1" else {"random_seed": 1} assert [body for _, body in models_session.submissions] == [ - {"sequences": ["MKT"], "query_id": QUERY_UUID}, - {"base_sequence": "MKT", "query_id": QUERY_UUID}, + {"sequences": ["MKT"], "query_id": QUERY_UUID, **weights, **seed}, + {"base_sequence": "MKT", "query_id": QUERY_UUID, **weights, **seed}, ] @pytest.mark.parametrize("alias", ["proteinmpnn", "solublempnn"]) - def test_embed_pools_by_mean_by_default(self, models, models_session, alias): + def test_embed_leaves_an_unset_reduction_to_the_server( + self, models, models_session, alias + ): getattr(models, alias).embed(["MKT"], query=QUERY_UUID) getattr(models, alias).embed(["MKT"], query=QUERY_UUID, reduction=None) assert [body for _, body in models_session.submissions] == [ - {"sequences": ["MKT"], "query_id": QUERY_UUID, "reduction": "MEAN"}, - {"sequences": ["MKT"], "query_id": QUERY_UUID, "reduction": None}, + {"sequences": ["MKT"], "query_id": QUERY_UUID, **MPNN_WEIGHTS}, + {"sequences": ["MKT"], "query_id": QUERY_UUID, **MPNN_WEIGHTS}, ] @@ -642,13 +695,6 @@ def test_rfdiffusion_sends_the_query_and_its_params(self, models, models_session "random_seed": 3, } - def test_rfdiffusion_generate_takes_a_query_and_params(self): - assert list(inspect.signature(RFdiffusion.generate).parameters) == [ - "self", - "query", - "params", - ] - def test_boltzgen_sends_the_query_and_its_params(self, models, models_session): models.boltzgen.generate( query=Complex({"A": Protein(sequence="MKT")}), @@ -666,20 +712,17 @@ def test_boltzgen_sends_the_query_and_its_params(self, models, models_session): "random_seed": 5, } - def test_boltzgen_generate_takes_a_query_and_params(self): - assert list(inspect.signature(BoltzGen.generate).parameters) == [ - "self", - "query", - "params", - ] - @pytest.mark.parametrize("model_id", ["boltzgen", "rfdiffusion"]) def test_a_design_model_takes_the_catalog_query_id( self, models, models_session, model_id ): getattr(models, model_id).generate(query_id=QUERY_UUID, random_seed=7) - assert models_session.submitted[1] == {"query_id": QUERY_UUID, "random_seed": 7} + assert models_session.submitted[1] == { + "query_id": QUERY_UUID, + "num_samples": 1, + "random_seed": 7, + } @pytest.mark.parametrize("model_id", ["boltzgen", "rfdiffusion"]) def test_a_design_model_refuses_a_query_with_query_id( @@ -792,5 +835,6 @@ def test_a_design_model_sends_a_param_it_does_not_name_as_given( assert caught.value.status_code == 422 assert models_session.session.post.call_args.kwargs["json"] == { "query_id": QUERY_UUID, + "num_samples": 1, param: value, } diff --git a/tests/models/test_input_checks.py b/tests/models/test_input_checks.py index 698e2db..1362efc 100644 --- a/tests/models/test_input_checks.py +++ b/tests/models/test_input_checks.py @@ -130,6 +130,7 @@ def test_a_valid_batch_uploads_every_query(self, models, models_session): def test_a_method_the_card_lacks_is_refused_before_the_query_upload( self, models, models_session ): + _without(models_session, "poet-2", "batch/attn") with pytest.raises(ValueError, match="has no attn"): models.poet2.attn(["AC"], query="AC") _nothing_sent(models_session) diff --git a/tests/models/test_model_taxonomy.py b/tests/models/test_model_taxonomy.py index 2d5c2e2..a8555a9 100644 --- a/tests/models/test_model_taxonomy.py +++ b/tests/models/test_model_taxonomy.py @@ -11,15 +11,15 @@ StructureGenerativeModel, StructurePredictionModel, ensemble, - folding, - foundational, + fold, + foundation, generative, ) -from openprotein.models.foundational._inverse_folding import _InverseFoldingModel +from openprotein.models.foundation._inverse_folding import _InverseFoldingModel BASES = [ - (foundational, (ProteinLanguageModel, _InverseFoldingModel)), - (folding, (StructurePredictionModel,)), + (foundation, (ProteinLanguageModel, _InverseFoldingModel)), + (fold, (StructurePredictionModel,)), (ensemble, (StructureEnsemblePredictionModel,)), (generative, (StructureGenerativeModel,)), ] @@ -56,5 +56,3 @@ def test_poet2_extends_poet(): def test_design_handles_share_query_submission(): assert issubclass(RFdiffusion, StructureGenerativeModel) assert issubclass(BoltzGen, StructureGenerativeModel) - assert RFdiffusion.generate is StructureGenerativeModel.generate - assert BoltzGen.generate is StructureGenerativeModel.generate diff --git a/tests/models/test_models_api.py b/tests/models/test_models_api.py index f8ac901..51ffe75 100644 --- a/tests/models/test_models_api.py +++ b/tests/models/test_models_api.py @@ -278,16 +278,15 @@ def test_esm_alias_embed_submits_to_models_route(self, mock_session): ) assert mock_session.post.call_args.kwargs["json"] == { "sequences": ["MKTAYIAK"], - "reduction": "MEAN", } - def test_esm_embed_preserves_explicit_unpooled_reduction(self, mock_session): + def test_esm_embed_leaves_an_unpooled_reduction_to_the_server(self, mock_session): _respond(mock_session.get, METADATA) _respond(mock_session.post, JOB) ModelsAPI(mock_session).esm2.embed(sequences=["MKTAYIAK"], reduction=None) - assert mock_session.post.call_args.kwargs["json"]["reduction"] is None + assert "reduction" not in mock_session.post.call_args.kwargs["json"] def test_esm_logits_and_attn_submit_to_model_methods(self, mock_session): attn = { @@ -328,8 +327,8 @@ def test_poet2_embed_submits_to_models_route(self, mock_session): ) assert mock_session.post.call_args.kwargs["json"] == { "sequences": ["MKTAYIAK"], + "use_query_structure_in_decoder": True, "prompt_id": "prompt-1", - "reduction": "MEAN", } def test_a_card_without_the_method_submits_nothing(self, mock_session): @@ -477,12 +476,12 @@ def test_a_verb_forwards_prompt_id_from_a_stored_or_a_sampled_prompt( assert calls[0].kwargs["json"]["prompt_id"] == "prompt-1" assert calls[1].kwargs["json"]["prompt_id"] == "sample-job-1" - def test_a_verb_sends_its_params_as_given(self, model, mock_session): + def test_a_verb_leaves_a_none_param_out(self, model, mock_session): _respond(mock_session.post, JOB) model.embed(["MKTAYIAK"], seed=None) - assert mock_session.post.call_args.kwargs["json"]["seed"] is None + assert "seed" not in mock_session.post.call_args.kwargs["json"] def test_a_verb_keeps_a_given_seed(self, model, mock_session): _respond(mock_session.post, JOB) diff --git a/tests/models/test_param_signatures.py b/tests/models/test_param_signatures.py new file mode 100644 index 0000000..d9134d9 --- /dev/null +++ b/tests/models/test_param_signatures.py @@ -0,0 +1,173 @@ +"""Handle verbs name, default, document and send the params their methods take.""" + +import inspect +import re +from typing import Any, Literal, get_args, get_origin +from unittest.mock import MagicMock + +import pytest + +from openprotein.models import ModelsAPI, PoET, StructureGenerativeModel +from openprotein.models.ensemble.base import StructureEnsemblePredictionModel +from openprotein.models.foundation._inverse_folding import _InverseFoldingModel +from tests.models import support +from tests.models.support import FITTED_FAMILIES, PARAMS + +QUERY = "c0ffee00-0000-4000-8000-000000000001" + +#: wire params a verb takes as SDK objects, such as ``query`` for ``query_id`` +INPUTS = { + "sequences", + "assay_id", + "base_sequence", + "complexes", + "reference_structures", + "prompt_id", + "query_id", + "design_id", +} +#: wire params left to ``**params``: single-valued or selecting nothing +UNEXPOSED = { + ("PoET2", "batch/loglikelihood", "decoder_type"), + ("PoET2", "single-site/scores", "decoder_type"), + ("PoET2", "indel/scores", "decoder_type"), + ("ProteinMPNN", "generate/sequences", "probabilities_output_mode"), +} +#: verb arguments that are SDK inputs rather than wire params +SDK_ARGS = { + "self", + "sequences", + "base_sequence", + "complexes", + "inputs", + "prompt", + "query", + "design", + "sequence", +} +#: params a verb converts before sending +CONVERTED = {"templates"} +VERBS = { + "batch/embeddings": "embed", + "batch/logits": "logits", + "batch/attn": "attn", + "batch/loglikelihood": "score", + "single-site/scores": "single_site", + "indel/scores": "indel", + "generate/sequences": "generate", + "generate/structures": "generate", + "batch/structures": "fold", +} + + +def _verb(handle: Any, path: str) -> str: + if isinstance(handle, StructureEnsemblePredictionModel): + return "sample" + return VERBS[path] + + +def _cases(): + for key, method in sorted(PARAMS["methods"].items()): + model_id, path = key.split("/", 1) + if model_id in FITTED_FAMILIES: + continue + handle = ModelsAPI(MagicMock())._accessor(model_id) + assert handle is not None, f"no handle for {model_id}" + yield pytest.param(model_id, path, method["params"], id=f"{model_id}:{path}") + + +CASES = list(_cases()) + + +def _exposed(handle: Any, path: str, schema: dict[str, Any]) -> set[str]: + name = type(handle).__name__ + return { + param + for param in schema["properties"] + if param not in INPUTS and (name, path, param) not in UNEXPOSED + } + + +def _literals(annotation: Any) -> set[Any]: + if get_origin(annotation) is Literal: + return set(get_args(annotation)) + return set().union(*(_literals(arg) for arg in get_args(annotation))) + + +def _enum(prop: dict[str, Any]) -> set[Any]: + for arm in [prop, *prop.get("anyOf", [])]: + if "enum" in arm: + return set(arm["enum"]) + return set() + + +@pytest.mark.parametrize(("model_id", "path", "schema"), CASES) +def test_a_verb_names_defaults_and_documents_its_params(model_id, path, schema): + handle = ModelsAPI(MagicMock())._accessor(model_id) + verb = getattr(type(handle), _verb(handle, path)) + signature = inspect.signature(verb, eval_str=True) + named = { + name: param + for name, param in signature.parameters.items() + if param.kind not in (param.VAR_KEYWORD, param.VAR_POSITIONAL) + } + props = schema["properties"] + exposed = _exposed(handle, path, schema) + + assert exposed <= set(named), f"missing {sorted(exposed - set(named))}" + extra = set(named) - SDK_ARGS - set(props) + assert not extra, f"{model_id} {path} takes no {sorted(extra)}" + assert {n: named[n].default for n in exposed} == { + n: props[n].get("default") for n in exposed + } + assert {n: _literals(named[n].annotation) for n in exposed if _enum(props[n])} == { + n: _enum(props[n]) for n in exposed if _enum(props[n]) + } + doc = inspect.cleandoc(verb.__doc__ or "") + section = doc.partition("Parameters\n----------")[2].partition("\n\n\n")[0] + section = re.split( + r"^(?:Returns|Raises|Examples)\n-+", section, flags=re.MULTILINE + )[0] + documented = set( + re.findall(r"^([a-z_][a-z0-9_]*)\s*:", section, flags=re.MULTILINE) + ) + assert exposed <= documented, f"undocumented {sorted(exposed - documented)}" + + +def _call_inputs(handle: Any, verb: str) -> tuple[tuple[Any, ...], dict[str, Any]]: + if verb == "fold": + return ("MKT",), {} + if verb == "generate": + if isinstance(handle, PoET): + return (), {"prompt": "prompt-1"} + if isinstance(handle, StructureGenerativeModel): + return (), {"query_id": QUERY} + return (), {"query": QUERY} + args = ("MKT",) if verb in ("single_site", "indel") else (["MKT"],) + kwargs: dict[str, Any] = {} + if isinstance(handle, PoET): + kwargs["prompt"] = "prompt-1" + if isinstance(handle, _InverseFoldingModel): + kwargs["query"] = QUERY + return args, kwargs + + +@pytest.mark.parametrize(("model_id", "path", "schema"), CASES) +def test_every_named_param_reaches_the_body( + model_id, path, schema, models_session, monkeypatch +): + monkeypatch.setattr(support, "check_body", lambda path, body: None) + models = ModelsAPI(models_session.session) + handle = models._accessor(model_id) + if isinstance(handle, StructureEnsemblePredictionModel): + pytest.skip("ensemble inputs are covered by the ensemble tests") + verb = _verb(handle, path) + args, kwargs = _call_inputs(handle, verb) + given = { + param: f"<{param}>" for param in _exposed(handle, path, schema) - CONVERTED + } + + getattr(handle, verb)(*args, **kwargs, **given) + + body = models_session.submitted[1] + assert {param: body.get(param) for param in given} == given diff --git a/tests/models/test_parity.py b/tests/models/test_parity.py index 485f6b5..10226c1 100644 --- a/tests/models/test_parity.py +++ b/tests/models/test_parity.py @@ -50,6 +50,13 @@ Q = "c0ffee00-0000-4000-8000-000000000001" Q2 = "c0ffee00-0000-4000-8000-000000000002" SEQ = ["MKT"] +MPNN_WEIGHTS = {"model_name": "v_48_020", "ca_only": False, "soluble_model": False} +MPNN_PSSM = { + "pssm_multi": 0.0, + "pssm_threshold": 0.0, + "pssm_bias": False, + "pssm_log_odds": False, +} PROTEIN = {"protein": {"id": "A", "sequence": "MKT"}} PROTEIN_MSA = {"protein": {"id": "A", "sequence": "MKT", "msa_id": None}} LIGAND = {"ligand": {"id": "L", "ccd": "ATP"}} @@ -119,9 +126,10 @@ def _gp(models: ModelsAPI) -> GPModel: def _embedded(model: str, reduction: Any = "MEAN", **params) -> tuple[str, dict]: + body = {"sequences": SEQ, "reduction": reduction, **params} return ( f"v1/models/{model}/batch/embeddings", - {"sequences": SEQ, "reduction": reduction, **params}, + {name: value for name, value in body.items() if value is not None}, ) @@ -135,20 +143,32 @@ def _embedded(model: str, reduction: Any = "MEAN", **params) -> tuple[str, dict] reads=[("GET", "v1/models/poet-2")], ), "embedding.prot_seq.embed": Case( - lambda m, s: m.prot_seq.embed(SEQ), posts=[_embedded("prot-seq")] + lambda m, s: m.prot_seq.embed(SEQ, reduction="MEAN"), + posts=[ + _embedded("prot-seq", chain_mode="linker", chain_linker="GGGGSGGGGSGGGGS") + ], ), "embedding.rotaprot.embed(reduction=None)": Case( lambda m, s: m.rotaprot_large_uniref50w.embed(SEQ, reduction=None), - posts=[_embedded("rotaprot-large-uniref50w", None)], + posts=[ + _embedded( + "rotaprot-large-uniref50w", + None, + chain_mode="linker", + chain_linker="GGGGSGGGGSGGGGS", + ) + ], ), "embedding.ablang2.embed": Case( - lambda m, s: m.ablang2.embed(SEQ), posts=[_embedded("ablang2")] + lambda m, s: m.ablang2.embed(SEQ, reduction="MEAN"), + posts=[_embedded("ablang2")], ), "embedding.esm2.embed": Case( - lambda m, s: m.esm2.embed(SEQ), posts=[_embedded("esm2_t33_650M_UR50D")] + lambda m, s: m.esm2.embed(SEQ, reduction="MEAN"), + posts=[_embedded("esm2_t33_650M_UR50D")], ), "embedding.poet.embed(prompt)": Case( - lambda m, s: m.poet.embed(SEQ, prompt="prompt-1"), + lambda m, s: m.poet.embed(SEQ, prompt="prompt-1", reduction="MEAN"), posts=[_embedded("poet", prompt_id="prompt-1")], ), "embedding.poet2.embed(prompt, query, decoder)": Case( @@ -173,7 +193,16 @@ def _embedded(model: str, reduction: Any = "MEAN", **params) -> tuple[str, dict] ), "embedding.prot_seq.logits": Case( lambda m, s: m.prot_seq.logits(SEQ), - posts=[("v1/models/prot-seq/batch/logits", {"sequences": SEQ})], + posts=[ + ( + "v1/models/prot-seq/batch/logits", + { + "sequences": SEQ, + "chain_mode": "linker", + "chain_linker": "GGGGSGGGGSGGGGS", + }, + ) + ], ), "embedding.poet2.logits(prompt, query, decoder)": Case( lambda m, s: m.poet2.logits( @@ -184,6 +213,7 @@ def _embedded(model: str, reduction: Any = "MEAN", **params) -> tuple[str, dict] "v1/models/poet-2/batch/logits", { "sequences": SEQ, + "use_query_structure_in_decoder": True, "prompt_id": "prompt-1", "query_id": Q, "decoder_type": "clm", @@ -193,7 +223,16 @@ def _embedded(model: str, reduction: Any = "MEAN", **params) -> tuple[str, dict] ), "embedding.prot_seq.attn": Case( lambda m, s: m.prot_seq.attn(SEQ), - posts=[("v1/models/prot-seq/batch/attn", {"sequences": SEQ})], + posts=[ + ( + "v1/models/prot-seq/batch/attn", + { + "sequences": SEQ, + "chain_mode": "linker", + "chain_linker": "GGGGSGGGGSGGGGS", + }, + ) + ], ), "embedding.poet.score(prompt)": Case( lambda m, s: m.poet.score(SEQ, prompt="prompt-1"), @@ -255,7 +294,11 @@ def _embedded(model: str, reduction: Any = "MEAN", **params) -> tuple[str, dict] posts=[ ( "v1/models/poet/single-site/scores", - {"base_sequence": "MKT", "prompt_id": "prompt-1"}, + { + "base_sequence": "MKT", + "include_gaps": False, + "prompt_id": "prompt-1", + }, ) ], ), @@ -272,6 +315,7 @@ def _embedded(model: str, reduction: Any = "MEAN", **params) -> tuple[str, dict] "v1/models/poet-2/single-site/scores", { "base_sequence": "MKT", + "include_gaps": False, "prompt_id": "prompt-1", "query_id": Q, "use_query_structure_in_decoder": True, @@ -329,6 +373,10 @@ def _embedded(model: str, reduction: Any = "MEAN", **params) -> tuple[str, dict] "ensemble_weights": [1.0, 2.0], "ensemble_method": "arithmetic", "num_samples": 10, + "temperature": 1.0, + "top_k": 20, + "top_p": 1.0, + "max_length": 1000, "random_seed": 7, }, ) @@ -339,7 +387,16 @@ def _embedded(model: str, reduction: Any = "MEAN", **params) -> tuple[str, dict] posts=[ ( "v1/models/poet-2/generate/sequences", - {"design_id": DESIGN_ID, "random_seed": 7}, + { + "design_id": DESIGN_ID, + "num_samples": 100, + "temperature": 1.0, + "top_k": 20, + "top_p": 1.0, + "max_length": 1000, + "use_query_structure_in_decoder": True, + "random_seed": 7, + }, ) ], ), @@ -456,6 +513,7 @@ def _embedded(model: str, reduction: Any = "MEAN", **params) -> tuple[str, dict] "num_recycles": 3, "num_steps": 100, "random_seed": 7, + "allow_msa_seed_mismatch": False, }, ) ], @@ -473,6 +531,7 @@ def _embedded(model: str, reduction: Any = "MEAN", **params) -> tuple[str, dict] "num_recycles": 3, "num_steps": 100, "random_seed": 7, + "allow_msa_seed_mismatch": False, }, ) ], @@ -494,7 +553,6 @@ def _embedded(model: str, reduction: Any = "MEAN", **params) -> tuple[str, dict] { "complexes": [[PROTEIN_MSA]], "num_models": 1, - "num_recycles": None, "num_relax": 0, }, ) @@ -521,6 +579,7 @@ def _embedded(model: str, reduction: Any = "MEAN", **params) -> tuple[str, dict] "step_scale": 1.638, "use_potentials": True, "random_seed": 7, + "allow_msa_seed_mismatch": False, }, ) ], @@ -530,7 +589,15 @@ def _embedded(model: str, reduction: Any = "MEAN", **params) -> tuple[str, dict] posts=[ ( "v1/models/boltz-1x/batch/structures", - {"complexes": [[PROTEIN_MSA]], "num_samples": 2, "random_seed": 7}, + { + "complexes": [[PROTEIN_MSA]], + "num_samples": 2, + "num_steps": 200, + "num_recycles": 3, + "step_scale": 1.638, + "random_seed": 7, + "allow_msa_seed_mismatch": False, + }, ) ], ), @@ -553,6 +620,11 @@ def _embedded(model: str, reduction: Any = "MEAN", **params) -> tuple[str, dict] "properties": [{"affinity": {"binder": "L"}}], "method": "X-RAY DIFFRACTION", "random_seed": 7, + "num_samples": 1, + "num_steps": 200, + "num_recycles": 3, + "step_scale": 1.638, + "allow_msa_seed_mismatch": False, }, ) ], @@ -570,6 +642,7 @@ def _embedded(model: str, reduction: Any = "MEAN", **params) -> tuple[str, dict] "num_recycles": 10, "num_steps": 200, "random_seed": 7, + "allow_msa_seed_mismatch": False, }, ) ], @@ -579,7 +652,14 @@ def _embedded(model: str, reduction: Any = "MEAN", **params) -> tuple[str, dict] posts=[ ( "v1/models/protenix-v2/batch/structures", - {"complexes": [[PROTEIN_MSA]], "random_seed": 7}, + { + "complexes": [[PROTEIN_MSA]], + "random_seed": 7, + "num_samples": 1, + "num_steps": 200, + "num_recycles": 10, + "allow_msa_seed_mismatch": False, + }, ) ], ), @@ -596,6 +676,7 @@ def _embedded(model: str, reduction: Any = "MEAN", **params) -> tuple[str, dict] "num_recycles": 10, "num_steps": 50, "random_seed": 7, + "allow_msa_seed_mismatch": False, }, ) ], @@ -615,7 +696,7 @@ def _embedded(model: str, reduction: Any = "MEAN", **params) -> tuple[str, dict] posts=[ ( "v1/models/proteinmpnn/batch/embeddings", - {"sequences": SEQ, "reduction": "MEAN", "query_id": Q}, + {"sequences": SEQ, "query_id": Q, **MPNN_WEIGHTS}, ) ], ), @@ -631,6 +712,7 @@ def _embedded(model: str, reduction: Any = "MEAN", **params) -> tuple[str, dict] "query_id": Q, "decoding_orders": 1, "random_seed": 1, + **MPNN_WEIGHTS, }, ) ], @@ -640,7 +722,13 @@ def _embedded(model: str, reduction: Any = "MEAN", **params) -> tuple[str, dict] posts=[ ( "v1/models/proteinmpnn/single-site/scores", - {"base_sequence": "MKT", "query_id": Q, "random_seed": 1}, + { + "base_sequence": "MKT", + "query_id": Q, + "random_seed": 1, + "decoding_orders": 1, + **MPNN_WEIGHTS, + }, ) ], ), @@ -659,6 +747,8 @@ def _embedded(model: str, reduction: Any = "MEAN", **params) -> tuple[str, dict] "num_samples": 100, "temperature": 0.1, "random_seed": 7, + **MPNN_WEIGHTS, + **MPNN_PSSM, }, ) ], @@ -668,7 +758,14 @@ def _embedded(model: str, reduction: Any = "MEAN", **params) -> tuple[str, dict] posts=[ ( "v1/models/solublempnn/generate/sequences", - {"query_id": Q, "num_samples": 10, "random_seed": 7}, + { + "query_id": Q, + "num_samples": 10, + "temperature": 0.1, + "random_seed": 7, + **MPNN_WEIGHTS, + **MPNN_PSSM, + }, ) ], ), @@ -972,7 +1069,7 @@ def test_the_contract_check_refuses_a_body_main_refuses(path, body): "call", [ lambda m: m.prot_seq.single_site("MKT"), - lambda m: m.esm1b.single_site("MKT"), + lambda m: m.esm1b.indel("MKT", insert="A"), lambda m: m.ablang2.attn(SEQ), lambda m: m.proteinmpnn.indel("MKT", insert="A"), lambda m: m.esmfold.generate(), diff --git a/tests/models/test_public_names.py b/tests/models/test_public_names.py index 3449e28..7f212b9 100644 --- a/tests/models/test_public_names.py +++ b/tests/models/test_public_names.py @@ -11,11 +11,11 @@ ("check_inputs", "query_ids", "takes_list", "with_param"), ), ( - "foundational.poet", + "foundation.poet", ("check_inputs", "prompt_id", "query_ids", "takes_list", "with_param"), ), ( - "foundational.poet2", + "foundation.poet2", ("check_inputs", "prompt_id", "query_ids", "takes_list", "with_param"), ), ("estimators", ("as_dataset", "assay_id", "model_id")), @@ -42,7 +42,7 @@ def test_deprecation_shims_export_no_helper_names_from_the_models_package(): def test_download_workers_is_not_bound_in_the_jobs_module(): import openprotein.jobs.jobs - assert "DOWNLOAD_WORKERS" not in vars(openprotein.jobs.jobs) + assert "_DOWNLOAD_WORKERS" not in vars(openprotein.jobs.jobs) def test_prompt_content_read_is_not_bound_in_the_stored_prompts_module(): diff --git a/tests/models/test_static_accessors.py b/tests/models/test_static_accessors.py index d34cf1f..4d96ae1 100644 --- a/tests/models/test_static_accessors.py +++ b/tests/models/test_static_accessors.py @@ -15,6 +15,7 @@ AlphaFold2, BioEmu, Boltz1, + Boltz1x, Boltz2, BoltzGen, ESMFlow, @@ -64,7 +65,7 @@ "prott5-xl": ProtT5, "alphafold2": AlphaFold2, "boltz-1": Boltz1, - "boltz-1x": Boltz1, + "boltz-1x": Boltz1x, "boltz-2": Boltz2, "esmfold": ESMFold, "esmfold2": ESMFold2, diff --git a/tests/models/test_structure_prediction_model.py b/tests/models/test_structure_prediction_model.py index 5a822bc..cd25483 100644 --- a/tests/models/test_structure_prediction_model.py +++ b/tests/models/test_structure_prediction_model.py @@ -111,11 +111,11 @@ def test_an_msa_future_folds_its_seed_as_one_complex(models, models_session): with ( patch( - "openprotein.models.folding.base.msa_future_to_complex", + "openprotein.models.fold.base.msa_future_to_complex", return_value=complex, ) as to_complex, patch( - "openprotein.models.folding.base.serialize_input", + "openprotein.models.fold.base.serialize_input", return_value=serialized, ) as serialize, ): @@ -215,7 +215,8 @@ def test_boltz2_properties_are_sent_as_given(models, models_session): assert models_session.submitted[1]["properties"] == properties -def test_boltz2_templates_become_template_queries(models, models_session): +@pytest.mark.parametrize("handle", ["boltz2", "protenix", "protenix_v2"]) +def test_templates_become_template_queries(handle, models, models_session): protein = Protein(sequence="ARNDCQ") protein.msa = Protein.single_sequence_mode template = Protein(sequence="ARNDCQ") @@ -223,7 +224,7 @@ def test_boltz2_templates_become_template_queries(models, models_session): np.zeros(template.coordinates.shape, dtype=np.float32) ) - models.boltz2.fold(protein, templates=[template], random_seed=1) + getattr(models, handle).fold(protein, templates=[template], random_seed=1) assert models_session.submitted[1]["templates"] == [{"query_id": created_query(1)}] assert [name for name, _ in models_session.queries] == ["query.cif"] diff --git a/tests/models/test_typecheck_coverage.py b/tests/models/test_typecheck_coverage.py index e7f03b6..5d17c4f 100644 --- a/tests/models/test_typecheck_coverage.py +++ b/tests/models/test_typecheck_coverage.py @@ -19,9 +19,25 @@ ("UMAP", "fit_transform"): "UMAPFitFuture", ("GPModel", "crossvalidate"): "CrossvalidateFuture", ("GPModel", "single_site"): "SingleSitePredictionFuture", + ("BoltzGen", "generate"): "StructureDesignFuture", + ("RFdiffusion", "generate"): "StructureDesignFuture", + ("AlphaFold2", "fold"): "StructurePredictionFuture", + ("Boltz1", "fold"): "StructurePredictionFuture", + ("Boltz1x", "fold"): "StructurePredictionFuture", + ("Boltz2", "fold"): "StructurePredictionFuture", + ("ESMFold", "fold"): "StructurePredictionFuture", + ("ESMFold2", "fold"): "StructurePredictionFuture", + ("MiniFold", "fold"): "StructurePredictionFuture", + ("OpenDDE", "fold"): "StructurePredictionFuture", + ("Protenix", "fold"): "StructurePredictionFuture", + ("ProtenixV2", "fold"): "StructurePredictionFuture", + ("RosettaFold3", "fold"): "StructurePredictionFuture", ("AlphaFlow", "sample"): "StructurePredictionFuture", ("BioEmu", "sample"): "StructurePredictionFuture", ("ESMFlow", "sample"): "StructurePredictionFuture", + ("_ChainedLanguageModel", "embed"): "EmbeddingFuture", + ("_ChainedLanguageModel", "logits"): "LogitsFuture", + ("_ChainedLanguageModel", "attn"): "AttentionFuture", ("Model", "attn"): "AttentionFuture", ("Model", "embed"): "EmbeddingFuture", ("Model", "fold"): "StructurePredictionFuture", @@ -60,14 +76,17 @@ ("ProteinLanguageModel", "fit_svd"): "SVDFitFuture", ("ProteinLanguageModel", "fit_umap"): "UMAPFitFuture", ("ProteinLanguageModel", "single_site"): "SingleSiteScoreFuture", + ("ESMIF1", "generate"): "SequenceGenerationFuture", ("ProteinMPNN", "embed"): "EmbeddingFuture", + ("ProteinMPNN", "generate"): "SequenceGenerationFuture", + ("ProteinMPNN", "score"): "LogLikelihoodFuture", + ("ProteinMPNN", "single_site"): "SingleSiteScoreFuture", ("SVDModel", "fit_gp"): "GPFitFuture", ("SVDModel", "fit_umap"): "UMAPFitFuture", ("SVDModel", "transform"): "EmbeddingFuture", ("StructureGenerativeModel", "generate"): "StructureDesignFuture", ("StructurePredictionModel", "fold"): "StructurePredictionFuture", ("UMAPModel", "transform"): "EmbeddingFuture", - ("_InverseFoldingModel", "generate"): "SequenceGenerationFuture", ("_InverseFoldingModel", "score"): "LogLikelihoodFuture", ("_InverseFoldingModel", "single_site"): "SingleSiteScoreFuture", } diff --git a/tests/models/typecheck_task_futures.py b/tests/models/typecheck_task_futures.py index 9678017..3692016 100644 --- a/tests/models/typecheck_task_futures.py +++ b/tests/models/typecheck_task_futures.py @@ -32,15 +32,28 @@ SVD, UMAP, AlphaFlow, + AlphaFold2, BioEmu, + Boltz1, + Boltz1x, + Boltz2, + BoltzGen, ESMFlow, + ESMFold, + ESMFold2, GPModel, + MiniFold, Model, + OpenDDE, PoET, PoET2, ProteinLanguageModel, ProteinMPNN, + Protenix, + ProtenixV2, + ProtSeq, RFdiffusion, + RosettaFold3, StructureGenerativeModel, StructurePredictionModel, SVDModel, @@ -104,6 +117,32 @@ def submission_types( assert_type(gp.single_site("MKT"), SingleSitePredictionFuture) +def structure_prediction_handle_types( + af2: AlphaFold2, + boltz1: Boltz1, + boltz1x: Boltz1x, + boltz2: Boltz2, + esmfold: ESMFold, + esmfold2: ESMFold2, + minifold: MiniFold, + opendde: OpenDDE, + protenix: Protenix, + protenix_v2: ProtenixV2, + rf3: RosettaFold3, +) -> None: + assert_type(af2.fold("MKT", num_models=2), StructurePredictionFuture) + assert_type(boltz1.fold("MKT", use_potentials=True), StructurePredictionFuture) + assert_type(boltz1x.fold("MKT", num_samples=2), StructurePredictionFuture) + assert_type(boltz2.fold("MKT", method="AFDB"), StructurePredictionFuture) + assert_type(esmfold.fold("MKT", num_recycles=4), StructurePredictionFuture) + assert_type(esmfold2.fold("MKT", num_steps=50), StructurePredictionFuture) + assert_type(minifold.fold("MKT", num_recycles=4), StructurePredictionFuture) + assert_type(opendde.fold("MKT", num_samples=2), StructurePredictionFuture) + assert_type(protenix.fold("MKT", templates=None), StructurePredictionFuture) + assert_type(protenix_v2.fold("MKT", num_steps=50), StructurePredictionFuture) + assert_type(rf3.fold("MKT", random_seed=1), StructurePredictionFuture) + + def estimator_types(svd: SVD, umap: UMAP, gp: GP) -> None: assert_type(svd.fit(), SVDFitFuture) assert_type(svd.fit_transform(), SVDFitFuture) @@ -141,6 +180,9 @@ def poet_types(poet: PoET) -> None: assert_type(poet.fit_svd(["MKT"]), SVDFitFuture) assert_type(poet.fit_umap(["MKT"]), UMAPFitFuture) assert_type(poet.generate(), SequenceGenerationFuture) + assert_type( + poet.generate("prompt-1", num_samples=5, top_k=10), SequenceGenerationFuture + ) assert_type(poet.indel("MKT"), IndelScoreFuture) assert_type(poet.logits(["MKT"]), LogitsFuture) assert_type(poet.score(["MKT"]), LogLikelihoodFuture) @@ -150,6 +192,7 @@ def poet_types(poet: PoET) -> None: def poet2_types(poet2: PoET2) -> None: assert_type(poet2.attn(["MKT"], query="MKT"), AttentionFuture) assert_type(poet2.embed(["MKT"], query="MKT"), EmbeddingFuture) + assert_type(poet2.embed(["MKT"], decoder_type="mlm"), EmbeddingFuture) assert_type( poet2.fit_gp("assay-id", ["fitness"], reduction="MEAN", query="MKT"), GPFitFuture, @@ -167,6 +210,12 @@ def inverse_folding_types(inverse: ESMIF1, proteinmpnn: ProteinMPNN) -> None: assert_type(inverse.score(["MKT"]), LogLikelihoodFuture) assert_type(inverse.single_site("MKT"), SingleSiteScoreFuture) assert_type(proteinmpnn.embed(["MKT"]), EmbeddingFuture) + assert_type(proteinmpnn.score(["MKT"], query="MKT"), LogLikelihoodFuture) + assert_type(proteinmpnn.single_site("MKT", query="MKT"), SingleSiteScoreFuture) + assert_type( + proteinmpnn.generate(query="MKT", num_samples=5, temperature=0.2), + SequenceGenerationFuture, + ) def structure_model_types( @@ -186,6 +235,19 @@ def structure_model_types( assert_type(generative.generate(), StructureDesignFuture) +def structure_generation_handle_types( + boltzgen: BoltzGen, rfdiffusion: RFdiffusion +) -> None: + assert_type(boltzgen.generate("MKT", num_samples=2), StructureDesignFuture) + assert_type(rfdiffusion.generate("MKT", num_samples=2), StructureDesignFuture) + + +def chained_language_model_types(protseq: ProtSeq) -> None: + assert_type(protseq.embed(["MKT"], chain_mode="independent"), EmbeddingFuture) + assert_type(protseq.logits(["MKT"], chain_linker="GGGGS"), LogitsFuture) + assert_type(protseq.attn(["MKT"]), AttentionFuture) + + def fitted_model_types(gp: GPModel, svd: SVDModel, umap: UMAPModel) -> None: assert_type(gp.crossvalidate(), CrossvalidateFuture) assert_type(svd.fit_gp("assay-id", ["fitness"]), GPFitFuture) diff --git a/tests/molecules/test_structure.py b/tests/molecules/test_structure.py index c12ebf6..69bd66e 100644 --- a/tests/molecules/test_structure.py +++ b/tests/molecules/test_structure.py @@ -243,3 +243,204 @@ def test_serde_multiple_models(): new_structure = Structure.from_string(structure.to_string(), format="cif") assert structure[0].get_protein(chain_id="A").msa is None assert structure[1].get_protein(chain_id="A").msa is None + + +def hemoglobin_proteins() -> Complex: + return Complex(Complex.from_filepath("tests/data/1A3N.cif").get_proteins()) + + +def noisy_hemoglobin_models(n_models: int, sigma: float) -> Structure: + rng = np.random.default_rng(0) + models = [] + for _ in range(n_models): + model = hemoglobin_proteins() + for protein in model.get_proteins().values(): + noise = rng.normal(0.0, sigma, protein.coordinates.shape) + protein._set_coordinates(protein.coordinates + noise.astype(np.float32)) + models.append(model) + return Structure(models) + + +def test_rmsf_of_rigidly_moved_copies_is_zero(): + rng = np.random.default_rng(0) + models = [] + for _ in range(3): + rotation, _ = np.linalg.qr(rng.normal(size=(3, 3))) + if np.linalg.det(rotation) < 0: + rotation[:, 0] *= -1 + models.append( + hemoglobin_proteins().transform(R=rotation, t=rng.normal(size=3) * 10) + ) + rmsf = Structure(models).rmsf() + assert np.allclose(rmsf[~np.isnan(rmsf)], 0.0, atol=1e-3) + + +def test_rmsf_matches_the_noise_of_the_models(): + sigma, n_models = 0.5, 200 + rmsf = noisy_hemoglobin_models(n_models, sigma).rmsf() + expected = sigma * np.sqrt(3 * (1 - 1 / n_models)) + assert np.nanmean(rmsf) == pytest.approx(expected, rel=0.05) + + +def test_rmsf_has_a_value_for_each_residue_of_all_protein_chains(): + complex = hemoglobin_proteins() + assert list(complex.get_proteins().keys()) == ["A", "B", "C", "D"] + n_residues = sum(len(protein) for protein in complex.get_proteins().values()) + assert Structure([complex, complex.copy()]).rmsf().shape == (n_residues,) + + +def test_rmsf_is_nan_for_a_residue_without_an_alpha_carbon(): + models = [hemoglobin_proteins() for _ in range(3)] + expected_nan = np.isnan(Structure(models).rmsf()) + # residue 5 of chain B comes after the 141 residues of chain A + models[1].get_protein("B").mask_structure_at([5]) + position = len(models[0].get_protein("A")) + 4 + expected_nan[position] = True + assert (np.isnan(Structure(models).rmsf()) == expected_nan).all() + + +def test_rmsf_is_only_supported_for_protein_chains(): + complex = Complex.from_filepath("tests/data/1A3N.cif") + assert len(complex.get_ligands()) > 0 + with pytest.raises(AssertionError, match="non-protein"): + Structure([complex, complex.copy()]).rmsf() + + +def test_rmsf_needs_two_models(): + with pytest.raises(ValueError, match="two models"): + Structure([hemoglobin_proteins()]).rmsf() + + +def test_rmsf_needs_models_with_the_same_chains(): + complex = hemoglobin_proteins() + chains_a_and_b = Complex( + {k: v for k, v in complex.get_proteins().items() if k in "AB"} + ) + with pytest.raises(ValueError, match="same protein chains"): + Structure([complex, chains_a_and_b]).rmsf() + + +def reference_rmsf(structure: Structure, passes: int) -> np.ndarray: + """Computes the RMSF with plain numpy, to compare with Structure.rmsf.""" + alpha_carbons = np.array( + [ + np.concatenate( + [p.coordinates[:, 1] for p in complex.get_proteins().values()] + ) + for complex in (structure[i] for i in range(len(structure))) + ], + dtype=np.float64, + ) + present = ~np.isnan(alpha_carbons).any(axis=(0, 2)) + + def superpose(frames, target): + target = target - target.mean(0) + out = [] + for frame in frames: + frame = frame - frame.mean(0) + u, _, vt = np.linalg.svd(frame.T @ target) + sign = np.sign(np.linalg.det(u @ vt)) + out.append(frame @ u @ np.diag([1, 1, sign]) @ vt) + return np.array(out) + + frames = alpha_carbons[:, present] + frames = superpose(frames, frames[0]) + for _ in range(passes): + frames = superpose(frames, frames.mean(0)) + rmsf = np.full(present.shape, np.nan) + rmsf[present] = np.sqrt(((frames - frames.mean(0)) ** 2).sum(-1).mean(0)) + return rmsf + + +@pytest.mark.parametrize("passes", [1, 2, 3]) +def test_rmsf_with_several_passes_matches_plain_numpy(passes): + structure = noisy_hemoglobin_models(10, 1.0) + assert np.allclose( + structure.rmsf(passes=passes), + reference_rmsf(structure, passes), + atol=1e-4, + equal_nan=True, + ) + + +def test_rmsf_needs_at_least_one_pass(): + with pytest.raises(ValueError, match="passes"): + noisy_hemoglobin_models(3, 1.0).rmsf(passes=0) + + +def test_phi_psi_matches_gemmi_dihedrals(): + protein = hemoglobin_proteins().get_protein("A") + angles = Structure([Complex({"A": protein})]).phi_psi()[0] + n, ca, c = (protein.coordinates[:, i].astype(np.float64) for i in range(3)) + + def dihedral(*atoms): + positions = (gemmi.Position(*atom) for atom in atoms) + return np.degrees(gemmi.calculate_dihedral(*positions)) + + compared = 0 + for i in range(1, len(protein) - 1): + atoms = [c[i - 1], n[i], ca[i], c[i], n[i + 1]] + if not np.isnan(atoms).any(): + assert angles[i, 0] == pytest.approx(dihedral(*atoms[:4]), abs=0.01) + assert angles[i, 1] == pytest.approx(dihedral(*atoms[1:]), abs=0.01) + compared += 1 + assert compared > 100 + + +def test_phi_psi_of_hemoglobin_is_helical(): + angles = Structure([hemoglobin_proteins()]).phi_psi()[0] + assert -80 < np.nanmedian(angles[:, 0]) < -50 + assert -60 < np.nanmedian(angles[:, 1]) < -20 + + +def test_phi_psi_has_one_row_for_each_residue_and_no_angle_across_chains(): + complex = hemoglobin_proteins() + lengths = [len(protein) for protein in complex.get_proteins().values()] + angles = Structure([complex, complex.copy()]).phi_psi() + assert angles.shape == (2, sum(lengths), 2) + first = np.cumsum([0] + lengths[:-1]) + last = np.cumsum(lengths) - 1 + assert np.isnan(angles[:, first, 0]).all(), ( + "no phi for the first residue of a chain" + ) + assert np.isnan(angles[:, last, 1]).all(), "no psi for the last residue of a chain" + + +def test_phi_psi_is_nan_where_the_next_residue_is_too_far(): + unmoved = hemoglobin_proteins() + expected = Structure([unmoved]).phi_psi() + moved = hemoglobin_proteins() + protein = moved.get_protein("A") + coordinates = protein.coordinates.copy() + coordinates[50:, :, 0] += 10.0 + protein._set_coordinates(coordinates) + angles = Structure([moved]).phi_psi() + # the bond between residues 50 and 51 is the only one that is broken + expected[0, 49, 1] = np.nan + expected[0, 50, 0] = np.nan + assert np.allclose(angles, expected, atol=0.01, equal_nan=True) + + +def test_phi_psi_is_nan_for_a_masked_residue_and_its_neighbours(): + expected = Structure([hemoglobin_proteins()]).phi_psi() + masked = hemoglobin_proteins() + masked.get_protein("A").mask_structure_at([21]) + angles = Structure([masked]).phi_psi() + # residue 21 has index 20; phi of residue 22 and psi of residue 20 need its atoms + expected[0, 20, :] = np.nan + expected[0, 21, 0] = np.nan + expected[0, 19, 1] = np.nan + assert np.allclose(angles, expected, equal_nan=True) + + +def test_phi_psi_works_for_a_single_model(): + complex = hemoglobin_proteins() + n_residues = sum(len(protein) for protein in complex.get_proteins().values()) + assert Structure([complex]).phi_psi().shape == (1, n_residues, 2) + + +def test_phi_psi_is_only_supported_for_protein_chains(): + complex = Complex.from_filepath("tests/data/1A3N.cif") + assert len(complex.get_ligands()) > 0 + with pytest.raises(AssertionError, match="non-protein"): + Structure([complex]).phi_psi() diff --git a/tests/molecules/test_structure_xtc.py b/tests/molecules/test_structure_xtc.py new file mode 100644 index 0000000..ac23c8f --- /dev/null +++ b/tests/molecules/test_structure_xtc.py @@ -0,0 +1,173 @@ +import subprocess +import sys +import textwrap +from pathlib import Path + +import gemmi +import numpy as np +import pytest + +from openprotein.molecules import Complex, Structure + +SHIFTS = [0.0, 0.5, 1.0] + + +@pytest.fixture +def xtc_file_class(): + """The XTCTrajectoryFile class of mdtraj. The test is skipped if mdtraj is missing.""" + return pytest.importorskip("mdtraj.formats").XTCTrajectoryFile + + +def _file_order_positions(topology: str) -> np.ndarray: + """Returns the coordinates of the atoms of a structure file in the order of the file, which is the order of a trajectory.""" + structure = gemmi.read_structure(topology) + atoms = [cra.atom for cra in structure[0].all()] + return np.array([a.pos.tolist() for a in sorted(atoms, key=lambda a: a.serial)]) + + +def _write_trajectory(xtc_file_class, path: Path, topology: str, shifts=SHIFTS) -> Path: + """Writes an XTC file with the atoms of a structure file, moved along x by each shift in Å.""" + positions = _file_order_positions(topology) + frames = [positions + np.array([shift, 0.0, 0.0]) for shift in shifts] + with xtc_file_class(str(path), "w") as file: + file.write((np.array(frames) / 10.0).astype(np.float32)) + return path + + +def _assert_proteins_moved(structure: Structure, topology: str, shifts=SHIFTS): + """Checks that each model has the protein coordinates of the topology, moved by its shift.""" + reference = Structure.from_filepath(topology, verbose=False)[0] + assert len(structure) == len(shifts) + for index, shift in enumerate(shifts): + model = structure[index] + assert list(model.get_proteins()) == list(reference.get_proteins()) + for chain_id, protein in reference.get_proteins().items(): + np.testing.assert_allclose( + model.get_protein(chain_id).coordinates, + protein.coordinates + np.array([shift, 0.0, 0.0], np.float32), + atol=0.01, + ) + + +def test_can_read_xtc_of_hemoglobin_cif(tmp_path, xtc_file_class): + # 4 protein chains and 4 ligands + topology = "tests/data/1A3N.cif" + xtc = _write_trajectory(xtc_file_class, tmp_path / "md.xtc", topology) + + structure = Structure.from_xtc(xtc, topology, verbose=False) + + _assert_proteins_moved(structure, topology) + for model in structure: + assert list(model.get_proteins().keys()) == ["A", "B", "C", "D"] + assert list(model.get_dnas().keys()) == [] + assert list(model.get_rnas().keys()) == [] + assert list(model.get_ligands().keys()) == ["E", "F", "G", "H"] + + +def test_can_read_xtc_of_protein_dna_rna_cif(tmp_path, xtc_file_class): + topology = "tests/data/1MSW.cif" + xtc = _write_trajectory(xtc_file_class, tmp_path / "md.xtc", topology) + + structure = Structure.from_xtc(xtc, topology, verbose=False) + + _assert_proteins_moved(structure, topology) + for model in structure: + assert list(model.get_proteins().keys()) == ["D"] + assert list(model.get_dnas().keys()) == ["A", "B"] + assert list(model.get_rnas().keys()) == ["C"] + assert list(model.get_ligands().keys()) == [] + + +def test_can_read_xtc_of_protein_pdb(tmp_path, xtc_file_class): + topology = "tests/data/1GCM.pdb" + xtc = _write_trajectory(xtc_file_class, tmp_path / "md.xtc", topology) + + structure = Structure.from_xtc(xtc, topology, verbose=False) + + _assert_proteins_moved(structure, topology) + for model in structure: + assert list(model.get_chains().keys()) == ["A", "B", "C"] + + +def test_can_read_xtc_of_pdb_with_blank_chain_id(tmp_path, xtc_file_class): + # GROMACS leaves the chain id blank + protein = Structure.from_filepath("tests/data/1GCM.pdb", verbose=False)[0] + named = Structure([Complex({"A": protein.get_protein("A")})]).to_string("pdb") + topology = tmp_path / "blank.pdb" + topology.write_text( + "\n".join( + line[:21] + " " + line[22:] if line.startswith(("ATOM", "TER")) else line + for line in named.splitlines() + ) + + "\n" + ) + xtc = _write_trajectory(xtc_file_class, tmp_path / "md.xtc", str(topology)) + + structure = Structure.from_xtc(xtc, topology, verbose=False) + + assert len(structure) == len(SHIFTS) + for model in structure: + assert list(model.get_chains().keys()) == ["A"] + + +def test_from_xtc_names_the_structure_after_the_trajectory(tmp_path, xtc_file_class): + topology = "tests/data/1GCM.pdb" + xtc = _write_trajectory(xtc_file_class, tmp_path / "run_3.xtc", topology) + + assert Structure.from_xtc(xtc, topology, verbose=False).name == "run_3" + + +def test_from_xtc_rejects_a_trajectory_with_other_atoms_than_the_topology( + tmp_path, xtc_file_class +): + xtc = _write_trajectory(xtc_file_class, tmp_path / "md.xtc", "tests/data/1GCM.pdb") + + with pytest.raises(ValueError, match="atoms"): + Structure.from_xtc(xtc, "tests/data/1A3N.cif", verbose=False) + + +def test_from_xtc_agrees_with_mdtraj_on_alpha_carbon_rmsd(tmp_path, xtc_file_class): + mdtraj = pytest.importorskip("mdtraj") + protein = Structure.from_filepath("tests/data/1GCM.pdb", verbose=False)[0] + topology = tmp_path / "chain_a.pdb" + topology.write_text( + Structure([Complex({"A": protein.get_protein("A")})]).to_string("pdb") + ) + positions = _file_order_positions(str(topology)) + frames = positions + np.random.default_rng(0).normal( + 0.0, 0.8, size=(8, *positions.shape) + ) + xtc = tmp_path / "md.xtc" + with xtc_file_class(str(xtc), "w") as file: + file.write((frames / 10.0).astype(np.float32)) + + structure = Structure.from_xtc(xtc, topology, verbose=False) + + trajectory = mdtraj.load(str(xtc), top=str(topology)) + alpha_carbons = trajectory.atom_slice(trajectory.topology.select("name CA")) + for i, j in [(0, 1), (2, 7), (4, 5)]: + expected = float(mdtraj.rmsd(alpha_carbons[j], alpha_carbons[i])[0]) * 10.0 + rmsd = ( + structure[i] + .get_protein("A") + .rmsd(structure[j].get_protein("A"), backbone_only="CA") + ) + assert rmsd == pytest.approx(expected, abs=1e-3) + + +def test_from_xtc_without_mdtraj_names_the_extra(): + script = textwrap.dedent( + """ + import sys + sys.modules["mdtraj"] = None + sys.modules["mdtraj.formats"] = None + from openprotein.molecules import Structure + try: + Structure.from_xtc("missing.xtc", "missing.pdb") + except ImportError as exc: + assert "openprotein-python[xtc]" in str(exc), exc + else: + raise AssertionError("expected ImportError") + """ + ) + subprocess.run([sys.executable, "-c", script], check=True) diff --git a/tests/test_auth.py b/tests/test_auth.py index d2edd2e..d289364 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -3,13 +3,15 @@ import stat import threading import time +from concurrent.futures import ThreadPoolExecutor from unittest.mock import MagicMock, patch import pytest import requests +from openprotein import base from openprotein.auth_store import TokenRecord, TokenStore -from openprotein.base import APISession, BearerAuth +from openprotein.base import APISession, BearerAuth, CloudFrontError from openprotein.errors import AuthError, HTTPError @@ -142,6 +144,20 @@ def test_login_uses_new_endpoint_with_delivery_header(isolated_store): assert session._legacy_mode is False +def test_a_backend_without_a_trailing_slash_keeps_its_path(isolated_store): + login_resp = _resp( + json_body={"access_token": "a", "refresh_token": "r", "expires_in": 900} + ) + with patch.object(APISession, "post", return_value=login_resp) as post: + session = APISession("user@x.com", "pw", backend="https://test-backend/api") + + assert session.backend == "https://test-backend/api/" + assert post.call_args.args == ("https://test-backend/api/v1/auth/login",) + assert session._identity == TokenStore().identity( + "https://test-backend/api/", "user@x.com" + ) + + def test_login_persists_refresh_token_to_store(isolated_store): from openprotein.auth_store import TokenStore @@ -495,6 +511,157 @@ def test_legacy_mode_does_not_refresh_on_401(isolated_store): session.request("GET", "v1/some/endpoint") +def test_a_rejected_response_is_closed_before_the_refresh(isolated_store): + session = _logged_in_session(isolated_store) + session._expires_at = time.time() + 10_000 + first = _resp(status=401) + closed_at_refresh = [] + + with ( + patch.object( + APISession, + "_refresh", + side_effect=lambda *_: closed_at_refresh.append(first.close.called), + ), + patch.object( + requests.Session, "request", side_effect=[first, _resp(status=200)] + ), + ): + session.request("GET", "v1/some/endpoint", stream=True) + + assert closed_at_refresh == [True] + + +@pytest.mark.parametrize( + ("status", "server", "error"), + [ + (502, "CloudFront", CloudFrontError), + (504, "CloudFront", base.TimeoutError), + (404, "", HTTPError), + ], +) +def test_a_response_raised_as_an_error_is_closed(isolated_store, status, server, error): + session = _logged_in_session(isolated_store) + session._expires_at = time.time() + 10_000 + failed = _resp(status=status) + failed.headers = {"Server": server} + + with ( + patch.object(requests.Session, "request", return_value=failed), + pytest.raises(error), + ): + session.request("GET", "v1/some/endpoint", stream=True) + + failed.close.assert_called_once() + + +def _refreshing_backend(rejected_until_refresh: bool): + """Fake transport: one refresh rotates to ``access-2``, a GET with the + first token gets 401 when ``rejected_until_refresh``.""" + refreshes = [] + + def request(method, url, **kwargs): + if url.endswith("v1/auth/refresh"): + refreshes.append(url) + return _resp( + json_body={ + "access_token": "access-2", + "refresh_token": f"refresh-{len(refreshes) + 1}", + "expires_in": 900, + } + ) + if rejected_until_refresh and not refreshes: + return _resp(status=401) + return _resp(status=200) + + return request, refreshes + + +def test_concurrent_rejections_of_one_token_refresh_once(isolated_store): + session = _logged_in_session(isolated_store) + session._expires_at = time.time() + 10_000 + send, refreshes = _refreshing_backend(rejected_until_refresh=True) + both_sent = threading.Barrier(2) + + def rejected_after_both_sent(method, url, **kwargs): + response = send(method, url, **kwargs) + if response.status_code == 401: + both_sent.wait(timeout=5) + return response + + with ( + patch.object(requests.Session, "request", side_effect=rejected_after_both_sent), + ThreadPoolExecutor(2) as pool, + ): + statuses = list( + pool.map( + lambda n: session.request("GET", f"v1/item/{n}").status_code, (0, 1) + ) + ) + + assert statuses == [200, 200] + assert len(refreshes) == 1 + assert session.auth._token == "access-2" + + +def test_concurrent_rejections_after_a_failed_relogin_raise_auth_errors( + isolated_store, +): + session = _logged_in_session(isolated_store) + session._expires_at = time.time() + 10_000 + both_sent = threading.Barrier(2) + sent = set() + + def everything_rejected(method, url, **kwargs): + if not url.startswith(f"{BACKEND}v1/auth/") and url not in sent: + sent.add(url) + both_sent.wait(timeout=5) + return _resp(status=401) + + def read(n): + try: + session.request("GET", f"v1/item/{n}") + except Exception as e: + return type(e) + + with ( + patch.object(requests.Session, "request", side_effect=everything_rejected), + ThreadPoolExecutor(2) as pool, + ): + errors = list(pool.map(read, (0, 1))) + + assert errors == [AuthError, AuthError] + + +def test_concurrent_proactive_refreshes_of_one_token_refresh_once(isolated_store): + session = _logged_in_session(isolated_store, expires_in=5) + send, refreshes = _refreshing_backend(rejected_until_refresh=False) + both_due = threading.Barrier(2) + due = session._should_refresh_proactively + + def due_after_both_checked(): + result = due() + if result: + both_due.wait(timeout=5) + return result + + with ( + patch.object( + session, "_should_refresh_proactively", side_effect=due_after_both_checked + ), + patch.object(requests.Session, "request", side_effect=send), + ThreadPoolExecutor(2) as pool, + ): + statuses = list( + pool.map( + lambda n: session.request("GET", f"v1/item/{n}").status_code, (0, 1) + ) + ) + + assert statuses == [200, 200] + assert len(refreshes) == 1 + + def test_refreshing_guard_is_thread_local(isolated_store): # The recursion guard must not leak across threads: while one thread is # mid-refresh, OTHER threads sharing the session (e.g. via stream_parallel) diff --git a/tests/test_submission_transport.py b/tests/test_submission_transport.py index 9d85093..9645f99 100644 --- a/tests/test_submission_transport.py +++ b/tests/test_submission_transport.py @@ -13,7 +13,7 @@ from requests.packages.urllib3.util.retry import Retry # type: ignore from openprotein import auth_store -from openprotein.base import APISession +from openprotein.base import _DOWNLOAD_WORKERS, APISession class _Server: @@ -241,3 +241,10 @@ def test_a_submission_get_is_still_retried_after_a_502(serve, make_session): assert response.status_code == 200 assert len(server.requests) == 2 + + +def test_results_content_pools_one_connection_per_concurrent_download(make_session): + session = make_session("https://test.invalid/") + adapter = session.get_adapter("https://test.invalid/v1/data/results/j/o/0/content") + + assert adapter._pool_maxsize >= _DOWNLOAD_WORKERS