From ad2d4fee18c3e693a8f86bd52e70e08904319138 Mon Sep 17 00:00:00 2001 From: "openprotein-bot[bot]" Date: Tue, 24 Nov 2026 11:18:19 +0000 Subject: [PATCH] Release v0.18.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 102 +- README.md | 12 +- openprotein/__init__.py | 29 +- openprotein/_deprecation.py | 38 + openprotein/_version.py | 2 - openprotein/align/__init__.py | 2 + openprotein/align/_files.py | 61 + openprotein/align/align.py | 270 +- openprotein/align/api.py | 530 +- openprotein/align/future.py | 18 +- openprotein/align/msa.py | 28 +- openprotein/align/schemas.py | 49 +- openprotein/auth_store.py | 5 +- openprotein/base.py | 232 +- openprotein/chains.py | 12 - openprotein/clustering/__init__.py | 10 + openprotein/clustering/api.py | 33 +- openprotein/clustering/clustering.py | 23 +- openprotein/clustering/models.py | 18 +- openprotein/clustering/schemas.py | 13 +- openprotein/codecs/__init__.py | 55 + openprotein/codecs/_text.py | 32 + openprotein/codecs/codec.py | 22 + openprotein/codecs/msa.py | 193 + openprotein/codecs/ndarray.py | 34 + openprotein/codecs/prompt.py | 226 + openprotein/common/__init__.py | 10 + openprotein/common/features.py | 5 +- openprotein/common/model_metadata.py | 2 + openprotein/common/reduction.py | 4 +- ...sidue_contants.py => residue_constants.py} | 3 + openprotein/config.py | 11 + openprotein/csv.py | 31 +- openprotein/data/__init__.py | 19 +- openprotein/data/_reads.py | 24 + openprotein/data/_resource.py | 307 + openprotein/data/api.py | 41 +- openprotein/data/assaydataset.py | 240 +- openprotein/data/data.py | 135 +- openprotein/data/msa/__init__.py | 14 + openprotein/data/msa/_api.py | 193 + openprotein/data/msa/msa.py | 352 + openprotein/data/msa/schemas.py | 38 + openprotein/data/prompts/__init__.py | 10 + openprotein/data/prompts/_api.py | 151 + openprotein/data/prompts/_replicates.py | 28 + openprotein/data/prompts/prompts.py | 250 + openprotein/data/prompts/schemas.py | 43 + openprotein/data/schemas.py | 15 +- openprotein/design/__init__.py | 11 + openprotein/design/api.py | 45 +- openprotein/design/design.py | 5 +- openprotein/design/future.py | 11 +- openprotein/design/schemas.py | 68 +- openprotein/embeddings/__init__.py | 22 + openprotein/embeddings/ablang.py | 38 + openprotein/embeddings/api.py | 73 +- openprotein/embeddings/embeddings.py | 69 +- openprotein/embeddings/esm.py | 36 +- openprotein/embeddings/future.py | 36 +- openprotein/embeddings/models.py | 23 +- openprotein/embeddings/openprotein.py | 4 +- openprotein/embeddings/poet.py | 21 +- openprotein/embeddings/poet2.py | 54 +- openprotein/embeddings/schemas.py | 18 +- openprotein/errors.py | 57 +- openprotein/fasta.py | 4 +- openprotein/fold/__init__.py | 21 +- openprotein/fold/_request.py | 181 + openprotein/fold/alphafold2.py | 15 +- openprotein/fold/api.py | 53 +- openprotein/fold/boltz.py | 79 +- openprotein/fold/common.py | 169 +- openprotein/fold/complex.py | 7 +- openprotein/fold/esmfold.py | 19 +- openprotein/fold/esmfold2.py | 21 +- openprotein/fold/fold.py | 15 +- openprotein/fold/future.py | 79 +- openprotein/fold/minifold.py | 12 +- openprotein/fold/models.py | 69 +- openprotein/fold/opendde.py | 169 + openprotein/fold/protenix.py | 18 +- openprotein/fold/rosettafold3.py | 21 +- openprotein/fold/schemas.py | 129 +- openprotein/jobs/__init__.py | 59 +- openprotein/jobs/_api.py | 125 + openprotein/jobs/_decode.py | 29 + openprotein/jobs/_dispatch.py | 126 + openprotein/jobs/_storage.py | 150 + openprotein/jobs/_submission.py | 42 + openprotein/jobs/api.py | 41 +- openprotein/jobs/futures.py | 1418 ++- openprotein/jobs/jobs.py | 174 +- openprotein/jobs/schemas.py | 117 +- openprotein/models/__init__.py | 198 +- openprotein/models/_api.py | 131 + openprotein/models/_folds.py | 55 + openprotein/models/_inputs.py | 247 + openprotein/models/base.py | 63 - openprotein/models/ensemble/__init__.py | 16 + openprotein/models/ensemble/_inputs.py | 163 + openprotein/models/ensemble/alphaflow.py | 148 + openprotein/models/ensemble/base.py | 25 + openprotein/models/ensemble/bioemu.py | 109 + openprotein/models/ensemble/esmflow.py | 122 + openprotein/models/estimators.py | 400 + openprotein/models/folding/__init__.py | 27 + openprotein/models/folding/alphafold2.py | 14 + openprotein/models/folding/base.py | 188 + 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/boltzgen.py | 298 - .../models/foundation/boltzgen_schema.py | 389 - openprotein/models/foundation/esmif1.py | 213 - openprotein/models/foundation/proteinmpnn.py | 193 - openprotein/models/foundation/rfdiffusion.py | 288 - openprotein/models/foundation/solublempnn.py | 25 - openprotein/models/foundational/__init__.py | 29 + .../models/foundational/_inverse_folding.py | 127 + openprotein/models/foundational/ablang2.py | 14 + openprotein/models/foundational/base.py | 122 + openprotein/models/foundational/esm1.py | 16 + openprotein/models/foundational/esm2.py | 16 + openprotein/models/foundational/esmc.py | 15 + openprotein/models/foundational/esmif1.py | 15 + openprotein/models/foundational/poet.py | 196 + openprotein/models/foundational/poet2.py | 212 + .../models/foundational/proteinmpnn.py | 44 + openprotein/models/foundational/protseq.py | 15 + openprotein/models/foundational/prott5.py | 14 + openprotein/models/foundational/rotaprot.py | 15 + openprotein/models/generative/__init__.py | 7 + openprotein/models/generative/base.py | 48 + openprotein/models/generative/boltzgen.py | 15 + openprotein/models/generative/rfdiffusion.py | 15 + openprotein/models/gp.py | 270 + openprotein/models/kernels.py | 159 + openprotein/models/model.py | 261 + openprotein/models/models.py | 474 +- openprotein/models/schemas.py | 178 + openprotein/models/structure_generation.py | 65 +- openprotein/models/svd.py | 256 + openprotein/models/umap.py | 118 + openprotein/molecules/__init__.py | 11 + openprotein/molecules/chains.py | 42 +- openprotein/molecules/complex.py | 85 +- openprotein/molecules/protein.py | 142 +- openprotein/molecules/structure.py | 16 +- openprotein/molecules/template.py | 14 +- openprotein/predictor/__init__.py | 78 +- openprotein/predictor/api.py | 100 +- openprotein/predictor/models.py | 108 +- openprotein/predictor/prediction.py | 16 +- openprotein/predictor/predictor.py | 25 +- openprotein/predictor/schemas.py | 21 +- openprotein/predictor/validate.py | 30 +- openprotein/prompt/__init__.py | 10 + openprotein/prompt/api.py | 136 +- openprotein/prompt/models.py | 37 +- openprotein/prompt/prompt.py | 34 +- openprotein/prompt/schemas.py | 16 +- openprotein/protein.py | 12 - openprotein/scaffolds.py | 8 - openprotein/svd/__init__.py | 9 + openprotein/svd/api.py | 32 +- openprotein/svd/models.py | 30 +- openprotein/svd/schemas.py | 2 + openprotein/svd/svd.py | 8 +- openprotein/umap/__init__.py | 9 + openprotein/umap/api.py | 44 +- openprotein/umap/models.py | 2 + openprotein/umap/schemas.py | 2 + openprotein/umap/umap.py | 14 +- openprotein/utils/__init__.py | 1 + openprotein/utils/chain_id.py | 5 +- openprotein/utils/cif.py | 10 +- openprotein/utils/numpy.py | 3 + openprotein/utils/sequence.py | 16 +- openprotein/utils/uuid.py | 35 +- pyproject.toml | 8 +- scripts/probe_dtypes.py | 7 +- tests/align/test_align.py | 172 +- tests/align/test_align_api.py | 352 +- tests/align/test_align_msa.py | 71 +- tests/align/test_align_schemas.py | 35 +- tests/align/test_input_deprecations.py | 151 + tests/align/test_msa_read.py | 136 + tests/align/test_server_warnings.py | 150 + tests/clustering/test_clustering.py | 1 - tests/clustering/test_clustering_schemas.py | 15 +- .../msa_multichain_chain_copies.parquet | Bin 0 -> 1234 bytes .../msa_single_chain_annotated.parquet | Bin 0 -> 2178 bytes .../codecs/fixtures/prompt_sequences_only.npz | Bin 0 -> 451 bytes .../fixtures/prompt_with_coordinates.npz | Bin 0 -> 1070 bytes tests/codecs/test_codec_fixtures.py | 129 + tests/codecs/test_codecs.py | 250 + tests/conftest.py | 2 +- tests/context.py | 2 - tests/data/ensemble_cards.json | 67 + .../quoted_predictions.csv | 2 + .../quoted_predictions.json | 8 + .../model_result_contracts/replicate_none.npy | Bin 0 -> 132 bytes .../model_result_contracts/replicate_one.npy | Bin 0 -> 132 bytes .../replicate_selected.npy | Bin 0 -> 132 bytes .../model_result_contracts/replicate_two.npy | Bin 0 -> 136 bytes tests/data/models_params.json | 9847 +++++++++++++++++ tests/data/test_accessors.py | 26 + tests/data/test_assay_resource.py | 208 + tests/data/test_data.py | 184 +- tests/data/test_data_api.py | 70 +- tests/data/test_data_deprecations.py | 82 + tests/data/test_data_schemas.py | 53 +- tests/data/test_internal_assay_loads.py | 64 + tests/data/test_msa_api.py | 292 + tests/data/test_msa_resource.py | 261 + tests/data/test_prompt_resource.py | 191 + tests/data/test_prompts_api.py | 289 + tests/data/test_prompts_replicates.py | 36 + tests/data/test_prompts_sample.py | 231 + tests/data/test_reads.py | 64 + tests/data/test_resource.py | 193 + tests/data/test_resource_jobs.py | 268 + tests/data/test_session_classes.py | 75 + tests/design/test_design.py | 5 +- tests/design/test_design_api.py | 4 +- tests/design/test_design_future.py | 4 - tests/design/test_design_schemas.py | 32 +- tests/e2e/README.md | 63 +- tests/e2e/config.py | 1 - tests/e2e/conftest.py | 35 +- tests/e2e/correctness/README.md | 49 +- tests/e2e/correctness/__init__.py | 2 +- tests/e2e/correctness/baselines.py | 61 +- tests/e2e/correctness/conftest.py | 2 +- tests/e2e/correctness/metrics.py | 4 +- tests/e2e/correctness/support.py | 8 +- .../e2e/correctness/test_attn_correctness.py | 26 +- tests/e2e/correctness/test_baselines_unit.py | 23 +- .../e2e/correctness/test_dtype_correctness.py | 19 +- .../test_embeddings_correctness.py | 47 +- .../correctness/test_generate_correctness.py | 49 +- .../correctness/test_logits_correctness.py | 28 +- tests/e2e/correctness/test_metrics_unit.py | 8 +- .../correctness/test_predictor_correctness.py | 21 +- .../correctness/test_scoring_correctness.py | 12 +- .../test_token_contract_correctness.py | 33 +- tests/e2e/models/__init__.py | 0 tests/e2e/models/test_estimators_e2e.py | 64 + tests/e2e/models/test_models_svd_e2e.py | 71 + .../e2e/models/test_structure_ensemble_e2e.py | 128 + .../models/test_structure_prediction_e2e.py | 456 + tests/e2e/test_align_e2e.py | 84 +- tests/e2e/test_assaydata_e2e.py | 136 +- tests/e2e/test_clustering_e2e.py | 10 +- tests/e2e/test_data_resources_e2e.py | 86 + tests/e2e/test_design_e2e.py | 7 +- tests/e2e/test_embeddings_e2e.py | 179 +- tests/e2e/test_fold_e2e.py | 71 +- tests/e2e/test_msa_prompt_poet_e2e.py | 44 + tests/e2e/test_multichain_e2e.py | 135 +- tests/e2e/test_predictor_e2e.py | 138 +- tests/e2e/test_predictor_trained_e2e.py | 327 + tests/e2e/test_prompt_e2e.py | 2 - tests/e2e/test_structgen_e2e.py | 180 +- tests/e2e/test_svd_e2e.py | 62 +- tests/e2e/test_umap_e2e.py | 91 +- tests/embeddings/test_embeddings.py | 163 +- tests/embeddings/test_embeddings_api.py | 10 +- tests/embeddings/test_embeddings_future.py | 9 - tests/embeddings/test_embeddings_models.py | 100 +- tests/embeddings/test_embeddings_poet2.py | 29 + tests/embeddings/test_embeddings_schemas.py | 5 - tests/embeddings/typecheck_stored_prompt.py | 14 + tests/fold/test_common.py | 148 +- tests/fold/test_fold.py | 4 - tests/fold/test_fold_api.py | 15 +- tests/fold/test_fold_common.py | 2 +- tests/fold/test_fold_confidence.py | 230 + tests/fold/test_fold_models.py | 415 +- tests/fold/test_fold_namespace.py | 37 + tests/fold/test_fold_schemas.py | 4 - tests/fold/test_request.py | 159 + tests/jobs/test_crossvalidate_rows.py | 85 + tests/jobs/test_future_base.py | 327 + tests/jobs/test_future_wait.py | 56 + tests/jobs/test_job_outputs.py | 362 + tests/jobs/test_jobs.py | 205 +- tests/jobs/test_jobs_api.py | 91 +- tests/jobs/test_jobs_schemas.py | 49 +- tests/jobs/test_model_result_contracts.py | 145 + tests/jobs/test_outputs_listing.py | 90 + tests/jobs/test_public_homes.py | 293 + tests/jobs/test_results_by_codec.py | 179 + tests/jobs/test_submission.py | 82 + tests/jobs/test_unknown_job.py | 135 + tests/jobs/test_wait_timeout.py | 80 + tests/models/conftest.py | 124 + .../foundational/test_boltzgen_schema.py | 314 - tests/models/foundational/test_esmif1.py | 243 - tests/models/foundational/test_proteinmpnn.py | 113 - .../foundational/test_structure_generation.py | 56 - tests/models/support.py | 222 + tests/models/test_deprecated_names.py | 147 + tests/models/test_empty_sources.py | 35 + tests/models/test_ensemble_contracts.py | 79 + tests/models/test_ensemble_examples.py | 49 + tests/models/test_ensemble_inputs.py | 184 + tests/models/test_ensemble_models.py | 295 + tests/models/test_ensemble_results.py | 198 + tests/models/test_estimators.py | 1185 ++ tests/models/test_folds.py | 86 + tests/models/test_future_outputs.py | 134 + tests/models/test_future_results.py | 420 + tests/models/test_future_unit.py | 548 + tests/models/test_handles.py | 796 ++ tests/models/test_input_checks.py | 206 + tests/models/test_inputs.py | 73 + tests/models/test_kernels.py | 71 + tests/models/test_local_validation.py | 83 + tests/models/test_model_taxonomy.py | 60 + tests/models/test_models_api.py | 659 ++ tests/models/test_models_gp.py | 315 + tests/models/test_models_svd.py | 422 + tests/models/test_models_umap.py | 140 + tests/models/test_parity.py | 1149 ++ tests/models/test_public_names.py | 51 + tests/models/test_reference_docstrings.py | 109 + tests/models/test_reload_contracts.py | 211 + tests/models/test_static_accessors.py | 251 + tests/models/test_structure_generation.py | 100 + .../models/test_structure_prediction_model.py | 449 + tests/models/test_task_dispatch.py | 281 + tests/models/test_task_futures.py | 405 + tests/models/test_typecheck_coverage.py | 190 + tests/models/test_units_record.py | 81 + tests/models/typecheck_ensemble_models.py | 50 + tests/models/typecheck_task_futures.py | 194 + tests/molecules/test_complex_mapping.py | 8 +- tests/molecules/test_model_numbering.py | 138 + tests/molecules/test_protein.py | 58 +- tests/molecules/test_structure.py | 6 +- tests/predictor/test_predictor.py | 29 +- tests/predictor/test_predictor_api.py | 45 +- tests/predictor/test_predictor_futures.py | 40 +- tests/predictor/test_predictor_models.py | 216 +- tests/predictor/test_predictor_schemas.py | 35 +- tests/prompt/test_prompt.py | 26 +- tests/prompt/test_prompt_api.py | 146 +- tests/prompt/test_prompt_models.py | 112 +- tests/prompt/test_prompt_schemas.py | 20 +- tests/svd/test_svd.py | 38 +- tests/svd/test_svd_api.py | 8 - tests/svd/test_svd_models.py | 6 - tests/svd/test_svd_schemas.py | 5 +- tests/test_auth.py | 31 +- tests/test_base.py | 231 +- tests/test_deprecation.py | 35 + tests/test_errors.py | 14 + tests/test_private_names.py | 31 + tests/test_public_names.py | 53 + tests/test_session_namespaces.py | 40 + tests/test_submission_transport.py | 243 + tests/test_uuid.py | 62 + tests/umap/test_umap.py | 7 - tests/umap/test_umap_api.py | 6 - tests/umap/test_umap_models.py | 23 +- tests/umap/test_umap_schemas.py | 5 +- tests/utils/sequences.py | 152 +- tests/utils/strings.py | 2 - tests/utils/svd.py | 6 - uv.lock | 71 +- 379 files changed, 43394 insertions(+), 4907 deletions(-) create mode 100644 openprotein/_deprecation.py create mode 100644 openprotein/align/_files.py delete mode 100644 openprotein/chains.py create mode 100644 openprotein/codecs/__init__.py create mode 100644 openprotein/codecs/_text.py create mode 100644 openprotein/codecs/codec.py create mode 100644 openprotein/codecs/msa.py create mode 100644 openprotein/codecs/ndarray.py create mode 100644 openprotein/codecs/prompt.py rename openprotein/common/{residue_contants.py => residue_constants.py} (97%) create mode 100644 openprotein/data/_reads.py create mode 100644 openprotein/data/_resource.py create mode 100644 openprotein/data/msa/__init__.py create mode 100644 openprotein/data/msa/_api.py create mode 100644 openprotein/data/msa/msa.py create mode 100644 openprotein/data/msa/schemas.py create mode 100644 openprotein/data/prompts/__init__.py create mode 100644 openprotein/data/prompts/_api.py create mode 100644 openprotein/data/prompts/_replicates.py create mode 100644 openprotein/data/prompts/prompts.py create mode 100644 openprotein/data/prompts/schemas.py create mode 100644 openprotein/fold/_request.py create mode 100644 openprotein/fold/opendde.py create mode 100644 openprotein/jobs/_api.py create mode 100644 openprotein/jobs/_decode.py create mode 100644 openprotein/jobs/_dispatch.py create mode 100644 openprotein/jobs/_storage.py create mode 100644 openprotein/jobs/_submission.py create mode 100644 openprotein/models/_api.py create mode 100644 openprotein/models/_folds.py create mode 100644 openprotein/models/_inputs.py delete mode 100644 openprotein/models/base.py create mode 100644 openprotein/models/ensemble/__init__.py create mode 100644 openprotein/models/ensemble/_inputs.py create mode 100644 openprotein/models/ensemble/alphaflow.py create mode 100644 openprotein/models/ensemble/base.py create mode 100644 openprotein/models/ensemble/bioemu.py create mode 100644 openprotein/models/ensemble/esmflow.py create mode 100644 openprotein/models/estimators.py create mode 100644 openprotein/models/folding/__init__.py create mode 100644 openprotein/models/folding/alphafold2.py create mode 100644 openprotein/models/folding/base.py create mode 100644 openprotein/models/folding/boltz1.py create mode 100644 openprotein/models/folding/boltz2.py create mode 100644 openprotein/models/folding/esmfold.py create mode 100644 openprotein/models/folding/esmfold2.py create mode 100644 openprotein/models/folding/minifold.py create mode 100644 openprotein/models/folding/opendde.py create mode 100644 openprotein/models/folding/protenix.py create mode 100644 openprotein/models/folding/protenix_v2.py create mode 100644 openprotein/models/folding/rosettafold3.py delete mode 100644 openprotein/models/foundation/boltzgen.py delete mode 100644 openprotein/models/foundation/boltzgen_schema.py delete mode 100644 openprotein/models/foundation/esmif1.py delete mode 100644 openprotein/models/foundation/proteinmpnn.py delete mode 100644 openprotein/models/foundation/rfdiffusion.py delete mode 100644 openprotein/models/foundation/solublempnn.py create mode 100644 openprotein/models/foundational/__init__.py create mode 100644 openprotein/models/foundational/_inverse_folding.py create mode 100644 openprotein/models/foundational/ablang2.py create mode 100644 openprotein/models/foundational/base.py create mode 100644 openprotein/models/foundational/esm1.py create mode 100644 openprotein/models/foundational/esm2.py create mode 100644 openprotein/models/foundational/esmc.py create mode 100644 openprotein/models/foundational/esmif1.py create mode 100644 openprotein/models/foundational/poet.py create mode 100644 openprotein/models/foundational/poet2.py create mode 100644 openprotein/models/foundational/proteinmpnn.py create mode 100644 openprotein/models/foundational/protseq.py create mode 100644 openprotein/models/foundational/prott5.py create mode 100644 openprotein/models/foundational/rotaprot.py create mode 100644 openprotein/models/generative/__init__.py create mode 100644 openprotein/models/generative/base.py create mode 100644 openprotein/models/generative/boltzgen.py create mode 100644 openprotein/models/generative/rfdiffusion.py create mode 100644 openprotein/models/gp.py create mode 100644 openprotein/models/kernels.py create mode 100644 openprotein/models/model.py create mode 100644 openprotein/models/schemas.py create mode 100644 openprotein/models/svd.py create mode 100644 openprotein/models/umap.py delete mode 100644 openprotein/protein.py delete mode 100644 openprotein/scaffolds.py create mode 100644 tests/align/test_input_deprecations.py create mode 100644 tests/align/test_msa_read.py create mode 100644 tests/align/test_server_warnings.py create mode 100644 tests/codecs/fixtures/msa_multichain_chain_copies.parquet create mode 100644 tests/codecs/fixtures/msa_single_chain_annotated.parquet create mode 100644 tests/codecs/fixtures/prompt_sequences_only.npz create mode 100644 tests/codecs/fixtures/prompt_with_coordinates.npz create mode 100644 tests/codecs/test_codec_fixtures.py create mode 100644 tests/codecs/test_codecs.py create mode 100644 tests/data/ensemble_cards.json create mode 100644 tests/data/model_result_contracts/quoted_predictions.csv create mode 100644 tests/data/model_result_contracts/quoted_predictions.json create mode 100644 tests/data/model_result_contracts/replicate_none.npy create mode 100644 tests/data/model_result_contracts/replicate_one.npy create mode 100644 tests/data/model_result_contracts/replicate_selected.npy create mode 100644 tests/data/model_result_contracts/replicate_two.npy create mode 100644 tests/data/models_params.json create mode 100644 tests/data/test_accessors.py create mode 100644 tests/data/test_assay_resource.py create mode 100644 tests/data/test_data_deprecations.py create mode 100644 tests/data/test_internal_assay_loads.py create mode 100644 tests/data/test_msa_api.py create mode 100644 tests/data/test_msa_resource.py create mode 100644 tests/data/test_prompt_resource.py create mode 100644 tests/data/test_prompts_api.py create mode 100644 tests/data/test_prompts_replicates.py create mode 100644 tests/data/test_prompts_sample.py create mode 100644 tests/data/test_reads.py create mode 100644 tests/data/test_resource.py create mode 100644 tests/data/test_resource_jobs.py create mode 100644 tests/data/test_session_classes.py create mode 100644 tests/e2e/models/__init__.py create mode 100644 tests/e2e/models/test_estimators_e2e.py create mode 100644 tests/e2e/models/test_models_svd_e2e.py create mode 100644 tests/e2e/models/test_structure_ensemble_e2e.py create mode 100644 tests/e2e/models/test_structure_prediction_e2e.py create mode 100644 tests/e2e/test_data_resources_e2e.py create mode 100644 tests/e2e/test_msa_prompt_poet_e2e.py create mode 100644 tests/e2e/test_predictor_trained_e2e.py create mode 100644 tests/embeddings/test_embeddings_poet2.py create mode 100644 tests/embeddings/typecheck_stored_prompt.py create mode 100644 tests/fold/test_fold_confidence.py create mode 100644 tests/fold/test_fold_namespace.py create mode 100644 tests/fold/test_request.py create mode 100644 tests/jobs/test_crossvalidate_rows.py create mode 100644 tests/jobs/test_future_base.py create mode 100644 tests/jobs/test_future_wait.py create mode 100644 tests/jobs/test_job_outputs.py create mode 100644 tests/jobs/test_model_result_contracts.py create mode 100644 tests/jobs/test_outputs_listing.py create mode 100644 tests/jobs/test_public_homes.py create mode 100644 tests/jobs/test_results_by_codec.py create mode 100644 tests/jobs/test_submission.py create mode 100644 tests/jobs/test_unknown_job.py create mode 100644 tests/jobs/test_wait_timeout.py create mode 100644 tests/models/conftest.py delete mode 100644 tests/models/foundational/test_boltzgen_schema.py delete mode 100644 tests/models/foundational/test_esmif1.py delete mode 100644 tests/models/foundational/test_proteinmpnn.py delete mode 100644 tests/models/foundational/test_structure_generation.py create mode 100644 tests/models/support.py create mode 100644 tests/models/test_deprecated_names.py create mode 100644 tests/models/test_empty_sources.py create mode 100644 tests/models/test_ensemble_contracts.py create mode 100644 tests/models/test_ensemble_examples.py create mode 100644 tests/models/test_ensemble_inputs.py create mode 100644 tests/models/test_ensemble_models.py create mode 100644 tests/models/test_ensemble_results.py create mode 100644 tests/models/test_estimators.py create mode 100644 tests/models/test_folds.py create mode 100644 tests/models/test_future_outputs.py create mode 100644 tests/models/test_future_results.py create mode 100644 tests/models/test_future_unit.py create mode 100644 tests/models/test_handles.py create mode 100644 tests/models/test_input_checks.py create mode 100644 tests/models/test_inputs.py create mode 100644 tests/models/test_kernels.py create mode 100644 tests/models/test_local_validation.py create mode 100644 tests/models/test_model_taxonomy.py create mode 100644 tests/models/test_models_api.py create mode 100644 tests/models/test_models_gp.py create mode 100644 tests/models/test_models_svd.py create mode 100644 tests/models/test_models_umap.py create mode 100644 tests/models/test_parity.py create mode 100644 tests/models/test_public_names.py create mode 100644 tests/models/test_reference_docstrings.py create mode 100644 tests/models/test_reload_contracts.py create mode 100644 tests/models/test_static_accessors.py create mode 100644 tests/models/test_structure_generation.py create mode 100644 tests/models/test_structure_prediction_model.py create mode 100644 tests/models/test_task_dispatch.py create mode 100644 tests/models/test_task_futures.py create mode 100644 tests/models/test_typecheck_coverage.py create mode 100644 tests/models/test_units_record.py create mode 100644 tests/models/typecheck_ensemble_models.py create mode 100644 tests/models/typecheck_task_futures.py create mode 100644 tests/molecules/test_model_numbering.py create mode 100644 tests/test_deprecation.py create mode 100644 tests/test_errors.py create mode 100644 tests/test_private_names.py create mode 100644 tests/test_public_names.py create mode 100644 tests/test_session_namespaces.py create mode 100644 tests/test_submission_transport.py create mode 100644 tests/test_uuid.py diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 7b51ca0..5e39b94 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "0.17.0" + ".": "0.18.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index f319fab..5bb5561 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,102 @@ # Changelog +## 0.18.0 (2026-11-24) + + +### ⚠ BREAKING CHANGES + +* **models:** the five `session.models` handles from v0.17.0 (`rfdiffusion`, `proteinmpnn`, `solublempnn`, `boltzgen`, `esmif1`) submit through the models API. `get_metadata()` is removed, and `metadata` now returns the model's card, `openprotein.models.ModelMetadata`: `model_id` replaces `id`, `methods` lists what the model runs, and `output_types`, `input_tokens`, `output_tokens` and `token_descriptions` are gone. `single_site` and `indel` take `base_sequence`. ESM-IF1, ProteinMPNN and SolubleMPNN `generate` takes `query`, `design` and the model's parameters by keyword and returns a `SequenceGenerationFuture`. RFdiffusion and BoltzGen `generate` returns a `StructureDesignFuture`. `get()` and `wait()` on a `SequenceGenerationFuture` return the generated sequences as strings, where v0.17.0 returned rows with `sequence` and `score`. Read the scores with `get(output="loglikelihood")`. +* **models:** on `session.models.esmif1`, `score` returns a `LogLikelihoodFuture` and `single_site` a `SingleSiteScoreFuture`. Their `get()` and `wait()` return the scores alone, as floats with `nan` and infinities included: one per scored sequence in the order submitted, or for `single_site` 20 per scanned position, positions in sequence order and substitutions in `openprotein.utils.sequence.AMINO_ACIDS` order, the position's own residue included. v0.17.0 returned `Score` rows with `name`, `sequence`, `score` and `query_id`, and `SingleSiteScore` rows with `mut_code`. +* **models:** ESM-IF1, ProteinMPNN and SolubleMPNN `generate` raises `TypeError` for a `query` and a `design` together, since the design's structures are the queries. v0.17.0 sent both. ESM-IF1 takes one query, so a list of several raises `ValueError`. +* **models:** RFdiffusion and BoltzGen design from a query only. `generate` takes `query`, `num_samples` (was `N`) and `random_seed`, plus `diffusion_batch_size`, `step_scale` and `noise_scale` for BoltzGen, and the API refuses any other keyword. RFdiffusion's `contigs`, `structure_file`, `inpaint_seq`, `provide_seq`, `hotspot`, `T`, `partial_T`, `use_active_site_model`, `use_beta_model`, `symmetry`, `order`, `add_potential`, `scaffold_target_structure_file` and `scaffold_target_use_struct` are gone, and so are BoltzGen's `design_spec`, `structure_file`, `scaffolds`, `scaffold_set` and `extra_structure_files`. `openprotein.scaffolds` is removed. Describe the design with the query, e.g. `Protein.from_expr(60)` for a 60-residue de novo design. `predict` is no longer an alias of `generate` on these two handles, so call `generate`. +* **models:** `openprotein.models.base.ProteinModel` and the `openprotein.models.foundation` modules (`boltzgen`, `boltzgen_schema`, `esmif1`, `proteinmpnn`, `rfdiffusion`, `solublempnn`) are removed. The class names v0.17.0 exported from `openprotein.models` still resolve, see Deprecations. +* **molecules:** `openprotein.chains` and `openprotein.protein` are removed; import from `openprotein.molecules`. `Protein.make_cif_string()` and `make_pdb_string()` are removed; use `to_string()` and `to_string(format="pdb")`. All four warned in v0.17.0 that they would be removed. +* **embeddings:** PoET-2 `score`, `indel` and `single_site` raise `InvalidParameterError` for `decoder_type="mlm"`. Leave it out to score with the `clm` decoder. +* **prompt:** `Query.get_as_complex()` keeps the chain ids of the structure it was created from. v0.17.0 returned a single-chain mmCIF query under chain `A`; read the chain from the returned complex's keys. +* **align:** `MSAFuture.get()`, `MSAFuture.wait()` and `session.align.get_msa(job_id)` read the stored MSA: a3m for a search or an uploaded MSA, FASTA for MAFFT, Clustal Omega and AbNumber. Read before a search finishes, it raises `HTTPError` 409 `msa is RUNNING`, and an MSA that is not stored raises `HTTPError` 404. +* **base:** every request made without `timeout` uses the session timeout, 180 s unless set with `openprotein.connect(..., timeout=...)`. v0.17.0 applied it to POST only, so a slow GET could wait indefinitely. Raise the session timeout, or set `session.timeout = None` for no limit. +* **base:** when retries on a failing response are spent, the SDK raises its own error for the last response (`openprotein.errors.HTTPError`, or `openprotein.base.CloudFrontError` / `openprotein.base.TimeoutError`) instead of `requests.exceptions.RetryError`. +* **jobs:** a future with no repr of its own prints as `Name(job_id=..., status=..., args=...)`. v0.17.0 printed the job record. +* **molecules:** writing a `Protein` with a length range, such as `Protein.from_expr("10..20")`, to a structure raises `ValueError`. v0.17.0 raised `RuntimeError`. +* **utils:** `openprotein.utils.uuid.is_valid_uuid` accepts any UUID version by default, since job ids are not all version 4. Pass `version=4` for the v0.17.0 check. +* **api:** `PATH_PREFIX` is removed from the clustering, design, embeddings, fold, predictor, svd and umap `api` modules, with no deprecation. +* **errors:** `openprotein.errors.UPGRADE_MESSAGE` and `openprotein.base.SKEW_SECONDS` are removed, with no deprecation. `openprotein.config` is unchanged. +* **common:** `openprotein.common.residue_contants` is renamed to `openprotein.common.residue_constants`, with no alias. + + +### Deprecations + +Each of these still works in 0.18.0, warns with a `FutureWarning` that names the replacement, and is removed in 0.19.0. + +* **align:** `session.align.mafft_file`, `clustalo_file` and `abnumber_file`: pass sequences and names to `mafft`, `clustalo` and `abnumber`. +* **align:** `session.align.upload_msa` and `openprotein.align.api.msa_post`: store an MSA with `session.data.MSA.create(f.read(), format="a3m")` (formats `a2m`, `a3m`, `csv`, `fasta`, `sto`) and sample it with `MSA.sample_prompt`, which takes `replicates`, `max_msa_sequences`, `max_msa_tokens`, `seed` and `force_include_first` in place of `num_ensemble_prompts`, `num_sequences`, `num_residues`, `random_seed` and `always_include_seed_sequence`, and returns a `session.data.Prompt`. For a seed sequence, use `session.align.create_msa`. +* **align:** `openprotein.align.api.mafft_post`, `clustalo_post` and `abnumber_post` called with `sequence_file`: pass sequences and names to the same functions. +* **align:** `openprotein.align.api.prompt_post`: use `MSAFuture.sample_prompt`, or `session.data.MSA(id=msa_id).sample_prompt(...)` with the arguments above. +* **align:** `AlignFuture.get_input`, `openprotein.align.api.get_input` and `openprotein.align.api.get_align_job_inputs`: for the MSA use `MSAFuture.wait()` or `session.data.MSA(id=...).to_string()`, for an MSA job's seed use `get_seed`, and for a prompt use `Prompt.get()`. Other align jobs' input has no replacement, so keep your own copy. +* **data:** `session.data.create`, `get`, `list` and `load_assay`, and `len(session.data)`: use `session.data.Assay.create`, `session.data.Assay(id=...)`, `session.data.Assay.list()` and `len(session.data.Assay.list())`. +* **data:** `update(assay_name=, assay_description=)` on an assay: use `update(name=, description=)`. +* **models:** `generate(seed=...)` and `single_site(sequence=...)` on ESM-IF1, ProteinMPNN and SolubleMPNN: use `random_seed=` and `base_sequence=`. +* **models:** `openprotein.models.BoltzGenModel`, `ESMIF1Model`, `ProteinMPNNModel` and `RFdiffusionModel`, also under `openprotein.models.models`: use `openprotein.models.BoltzGen`, `ESMIF1`, `ProteinMPNN` and `RFdiffusion`. The names resolve to the new handles, whose methods changed (see Breaking Changes). +* **models:** `openprotein.models.SolubleMPNNModel`: use `session.models.solublempnn`. +* **models:** the embedding and fold classes imported from `openprotein.models` (`ESMModel`, `OpenProteinModel`, `PoETModel`, `PoET2Model`, `AlphaFold2Model`, `Boltz1Model`, `Boltz1xModel`, `Boltz2Model`, `ESMFoldModel`, `ESMFold2Model`, `ESMFold2FastModel`, `MiniFoldModel`, `ProtenixModel`, `ProtenixV2Model`, `RosettaFold3Model`): import them from `openprotein.embeddings` and `openprotein.fold`. +* **models:** `openprotein.models.BoltzGenFuture` and `RFdiffusionFuture`: submit designs with `session.models.boltzgen.generate(...)` and `session.models.rfdiffusion.generate(...)`, which return `openprotein.jobs.StructureDesignFuture`. `session.jobs.get(id)` loads a v0.17.0 design job as a `StructureGenerationFuture`. + + +### Features + +* **models:** `session.models.` reaches every listed model through a handle class per base model: `ESM2`, `ESMC`, `PoET`, `PoET2`, `Boltz2`, `ProteinMPNN`, `ESMIF1`, `RFdiffusion`, `BoltzGen` and the rest, importable from `openprotein.models`. `session.models.get_model(id)` loads a handle by id. +* **models:** each handle has `embed`, `logits`, `attn`, `score`, `single_site`, `indel`, `generate`, `fold` and `predict`, as the model allows, plus `metadata` and `methods`. `embed(assay)` embeds an assay dataset. +* **models:** `design=` on ESM-IF1, ProteinMPNN, SolubleMPNN and PoET-2 `generate` takes an RFdiffusion or BoltzGen job or its id, finished or not. The generation runs once the design finishes, with each designed structure as a query, so ESM-IF1 generates from a design with several structures. +* **models:** `session.models.list_models(verbose=False, *, path=None)` lists system models, across every page. `path` keeps the models with a matching method path. Fitted models are listed by `session.models.GP.list`, `SVD.list` and `UMAP.list`. +* **models:** `session.models.bioemu`, `alphaflow` and `esmflow` sample structure ensembles with `sample(inputs, num_samples=...)`. Each takes its own typed input: `BioEmuInput`, `AlphaFlowInput` or `ESMFlowInput`. +* **models:** `session.models.opendde` and `opendde_abag` fold with OpenDDE. +* **models:** estimators `session.models.SVD(n_components=None, seed=None)`, `UMAP(n_components=None, n_neighbors=None, min_dist=None)` and `GP(kernel="rbf", period=None, alpha=None, name=None, description=None)` hold a fit's settings. `fit(X)` fits on an embeddings job, and UMAP and GP also take a fitted SVD as `X`. `fit(model=..., sequences=...)` on SVD and UMAP, or `fit(model=..., assay=...)`, has a system model or a fitted SVD embed the input as part of the fit. `GP.fit` takes `assay=` and `property=`, and `assay=` alone trains on one-hot features. +* **models:** `fit` submits straight away and returns an `SVDFitFuture`, `UMAPFitFuture` or `GPFitFuture`, which keeps `dataset`. `wait()` returns the fitted `SVDModel`, `UMAPModel` or `GPModel` and raises if the fit failed. A fit with the wrong mix of `X`, `model=`, `sequences=` and `assay=` raises before anything is sent. +* **models:** `SVDFitFuture.transform` and `UMAPFitFuture.transform` take sequences or an assay and submit a projection that runs once the fit finishes. `embed` is the same call, and `fit_transform` on SVD and UMAP returns the same fit future as `fit`. +* **models:** `SVD(id=...)`, `UMAP(id=...)` and `GP(id=...)` on `session.models` load a fitted model by its id, and `list(limit=None, offset=None)` lists the caller's fits. +* **models:** fitted models: `SVDModel` has `transform` (or `embed`), `n_components`, `requested_n_components`, `embedding`, `fit_umap`, `fit_gp` and `delete`; `UMAPModel` has `transform` (or `embed`), `spec` and `delete`; `GPModel` has `predict`, `single_site`, `crossvalidate`, `evaluations`, `training`, `spec` and `delete`. +* **models:** `fit_svd`, `fit_umap` and `fit_gp` on a protein language model handle fit with that model. +* **models:** `GPModel.crossvalidate(n_splits=...)` or `crossvalidate(folds=...)` with integer folds returns a `CrossvalidateFuture`, whose `get()` and `wait()` return `CrossvalidateResults`. +* **predictor:** `kernel`, `mean` and `noise` read a trained GP's hyperparameters on `session.predictor` predictors and on `session.models` GPs. `kernel` is typed by kernel: `RBFKernel`, `PeriodicKernel`, `RationalQuadraticKernel` and the rest. An ensemble, or a GP trained before hyperparameters were recorded, raises `HTTPError` 404. +* **jobs:** a `session.models` future reads its outputs with `outputs`, `get_item`, `stream`, `units` and `unit(i)`, which raise `APIError` on jobs that store no outputs. Every future has `args` and `dataset`. `units` and `unit(i)` return `FutureUnit` handles, whose `status` is a `JobStatus`. The typed result futures add `len()`, iteration and indexing. +* **jobs:** every future has `name`, `description` and `rename(...)`, except that `openprotein.prompt.Prompt` and `PredictorModel` keep the name they were created with. `session.jobs.list(name=...)` matches a name exactly and `session.jobs.update` renames a job by id. +* **jobs:** a job type the client does not know returns an `UnknownJobFuture` instead of raising. Its `status` and `wait_until_done` work, and `get()` and `wait()` raise `NotImplementedError`. +* **jobs:** `wait(...)` passes keyword arguments on to `get`. `wait(timeout=...)` caps each poll and sleep by the time left and raises `TimeoutException`; a stalled poll is retried first, so a wait can run past its timeout. +* **jobs:** `wait()` on a canceled `session.models` job raises `JobFailedException`. +* **jobs:** `JobStatus.CREATED`, and `openprotein.errors.JobOutputsNotReady` for an output that is not complete yet. +* **data:** `session.data.MSA`, `session.data.Prompt` and `session.data.Assay` store MSAs, prompts and assays: `create`, `list` across every page up to `limit`, `session.data.MSA(id=...)` to load one, and `update`, `delete` and `refresh` on each. +* **data:** a stored MSA, prompt or assay answers a future's calls: `done`, `wait_until_done`, `get`, `wait`, `job`, `job_type`, `created_date`, `start_date` and `end_date`. `wait()` returns it once it is ready, and `get()` returns it if it is ready and raises `JobOutputsNotReady` if not. One that no job made is always ready, and its job fields raise `openprotein.errors.NoJobError`. +* **data:** iterating a stored MSA yields its `(name, sequence)` rows with insertions left out. An a2m or Stockholm upload whose rows don't all mark the same insert columns by lowercase and `.` keeps every column. `to_string(format=None)` renders it, by default in its stored format. +* **data:** `MSA.sample_prompt(...)` samples a stored MSA and returns the stored `Prompt`, which iterates as one list of sequences per replicate. `session.jobs.get` loads that sampling job as the same `Prompt`. +* **data:** an MSA, prompt or assay whose job has not finished reads back with that job's `status` and `job_id`. +* **data:** assay text metadata: `session.data.Assay.create(..., metadata_columns=[...])`, `Assay.metadata_names` and `get_slice(include_metadata=True)`. +* **data:** `AssayDataset` is now `Assay`, and the old name stays. +* **embeddings:** `single_site` on the ESM models (`ESMModel`) and on AbLang2. +* **fold:** OpenDDE: `OpenDDEModel` and `OpenDDEAbagModel` (`opendde`, `opendde-abag`), with `OpenDDEConfidence`, and a `FoldConfidence` schema for fold confidence files. +* **fold:** `fold(seed=...)` on Protenix, Boltz, OpenDDE and RosettaFold-3. +* **fold:** `fold` takes a single complex, protein or sequence as well as a list. +* **align:** `session.align.create_msa(pairing=...)` sets cross-chain pairing for a complex seed, as an `openprotein.align.schemas.Pairing`. +* **codecs:** `openprotein.codecs` decodes stored result files: `msa-parquet-v1`, `ndarray-v1`, `prompt-npz-v1`, JSON, mmCIF and FASTA text. `msa-parquet-v1` needs `pyarrow`, installed with the `msa` extra. +* **base:** deprecation warnings sent by the API are shown as `FutureWarning`s. + + +### Bug Fixes + +* **base:** every unsuccessful response raises `HTTPError`. v0.17.0 could return some 4xx responses to the caller. +* **base:** requests to an `http://` backend are retried like `https://` ones. +* **data:** `session.data.list()` returns every assay. v0.17.0 returned the first 100. +* **data:** an assay's `update` sends JSON, which the API accepts. v0.17.0 sent form data and got a 400. +* **data:** creating an assay keeps its stored sequence length, which is null for sequences of mixed lengths, and leaves the table's column names as they were. +* **fold:** a template mapped to chain `A` is accepted on a lone `Protein`. +* **fold:** a `:`-delimited string folds as one multichain complex on models that take templates. +* **fold:** a batch whose later complexes have a chain the first lacks folds, and a shared template is checked against every complex before anything is uploaded. +* **prompt:** a hyphenated id in any letter case is used as an id. +* **prompt:** `get_query` reads a query that was uploaded as a PDB file. +* **design:** design constraints leave out chain-break positions, so a multichain constraint submits. +* **molecules:** `Complex.to_string("cif")` numbers its model from 1. v0.17.0 wrote model 0. +* **molecules:** selenomethionine `SE` atoms are read as `SD` instead of being dropped. +* **molecules:** `rmsd` returns the exact value, without an epsilon under the root. + ## 0.17.0 (2026-08-22) @@ -23,11 +120,6 @@ ## 0.16.1 (2026-07-14) - -### Bug Fixes - -* remove internal backend PR references from multichain e2e - ## 0.16.0 (2026-07-14) diff --git a/README.md b/README.md index 9d81ad5..839c941 100644 --- a/README.md +++ b/README.md @@ -75,9 +75,10 @@ result = future.get(verbose=True) # get the result from a finished job ## Jobs Interface ### Listing Jobs -To view all jobs associated with each session, the following method is available, providing an option to filter results by date, job type, or status. +To view all jobs associated with each session, the following method is available, providing an option to filter results by date, job type, status, or name. ``` session.jobs.list() +session.jobs.list(name="my-run") # filter to jobs with an exact name match ``` ### Retrieving Specific Job @@ -86,6 +87,15 @@ For detailed information about a particular job, use the following command with session.jobs.get(JOB_ID) # Replace JOB_ID with the ID of the specific job to be retrieved ``` +### Naming Jobs +A job can be given a name and description once it's created, to make it easier to find: +``` +session.jobs.update(JOB_ID, name="my-run", description="baseline model") + +# equivalent, from a Future +future.rename(name="my-run", description="baseline model") +``` + ### Resuming Jobs Jobs from prior workflows can be resumed using the load_job method provided by each API. ``` diff --git a/openprotein/__init__.py b/openprotein/__init__.py index d4d704a..498b721 100644 --- a/openprotein/__init__.py +++ b/openprotein/__init__.py @@ -26,6 +26,27 @@ from openprotein.jobs import Future from openprotein.base import APISession +__all__ = [ + "SVDAPI", + "UMAPAPI", + "APISession", + "AlignAPI", + "ClusteringAPI", + "DataAPI", + "DeprecationError", + "DesignAPI", + "EmbeddingsAPI", + "FoldAPI", + "Future", + "JobsAPI", + "ModelsAPI", + "OpenProtein", + "PredictorAPI", + "PromptAPI", + "__version__", + "connect", +] + class OpenProtein(APISession): """ @@ -102,9 +123,7 @@ def embedding(self) -> EmbeddingsAPI: @property def svd(self) -> SVDAPI: - """ - The embedding submodule gives access to protein embedding models and their inference endpoints. - """ + """Fit and apply SVD projections through the SVD API.""" if self._svd is None: self._svd = SVDAPI( session=self, @@ -113,9 +132,7 @@ def svd(self) -> SVDAPI: @property def umap(self) -> UMAPAPI: - """ - The embedding submodule gives access to protein embedding models and their inference endpoints. - """ + """Fit and apply UMAP projections through the UMAP API.""" if self._umap is None: self._umap = UMAPAPI( session=self, diff --git a/openprotein/_deprecation.py b/openprotein/_deprecation.py new file mode 100644 index 0000000..a06dc99 --- /dev/null +++ b/openprotein/_deprecation.py @@ -0,0 +1,38 @@ +"""Helper for deprecating public interfaces.""" + +import warnings + + +def warn_deprecated( + name: str, + use: str, + *, + since: str, + removed_in: str, + stacklevel: int = 3, +) -> None: + """ + Warn that a public interface is deprecated. + + The default ``stacklevel`` points the warning at the caller of the + deprecated function that calls this helper. + + Parameters + ---------- + name : str + Name of the deprecated interface. + use : str + The replacement, already formatted for display. + since : str + Version the interface was deprecated in. + removed_in : str + Version the interface is removed in. + stacklevel : int, default=3 + Stack level passed to `warnings.warn`. + """ + warnings.warn( + f"`{name}` is deprecated since {since} and will be removed in {removed_in}. " + f"Use {use}.", + FutureWarning, + stacklevel=stacklevel, + ) diff --git a/openprotein/_version.py b/openprotein/_version.py index b3653c1..f9ca545 100644 --- a/openprotein/_version.py +++ b/openprotein/_version.py @@ -8,8 +8,6 @@ def _get_hatch_version(): """Compute the most up-to-date version number in a development environment. Returns `None` if Hatchling is not installed, e.g. in a production environment. - - For more details, see . """ import os diff --git a/openprotein/align/__init__.py b/openprotein/align/__init__.py index 2196942..3867d2d 100644 --- a/openprotein/align/__init__.py +++ b/openprotein/align/__init__.py @@ -6,3 +6,5 @@ from .msa import MSAFuture from .align import AlignAPI + +__all__ = ["AlignAPI", "MSAFuture"] diff --git a/openprotein/align/_files.py b/openprotein/align/_files.py new file mode 100644 index 0000000..518493e --- /dev/null +++ b/openprotein/align/_files.py @@ -0,0 +1,61 @@ +"""Sequence files read by the deprecated align methods.""" + +import csv + +from openprotein import fasta +from openprotein.errors import InvalidParameterError + + +def read_file_content(file) -> bytes | bytearray | str: + """Read the sequence file a deprecated align method was given. + + Accepts a file-like object, ``bytes``, ``bytearray``, ``str`` or a + ``(filename, fileobj)`` / ``(filename, fileobj, content_type)`` tuple or list. + """ + if isinstance(file, (tuple, list)): + file = file[1] + return file.read() if hasattr(file, "read") else file + + +def read_sequences( + content: bytes | bytearray | str, +) -> tuple[list[str], list[str] | None]: + """Parse FASTA or headerless CSV text into sequences and optional names.""" + if isinstance(content, (bytes, bytearray)): + content = content.decode("utf-8-sig") + text = content.removeprefix("\ufeff") + lines = text.splitlines() + if any(line.lstrip().startswith(">") for line in lines): + parsed_names, parsed_sequences = fasta.parse(lines) + names: list[str] | None = [] + sequences: list[str] = [] + for name, sequence in zip(parsed_names, parsed_sequences): + if sequence.strip(): + names.append(str(name)) + sequences.append(str(sequence)) + else: + rows = [] + width = 1 + for row in csv.reader(text.splitlines(keepends=True)): + trimmed = row.copy() + while trimmed and not trimmed[-1].strip(): + trimmed.pop() + if trimmed: + rows.append(row) + width = max(width, len(trimmed)) + if width > 2: + raise InvalidParameterError( + "CSV must have one sequence column or name and sequence columns." + ) + names = None if width == 1 else [] + sequences = [] + for row in rows: + sequence = row[1] if names is not None and len(row) > 1 else row[0] + if not sequence.strip(): + continue + sequences.append(sequence.strip()) + if names is not None: + names.append(row[0].strip() if len(row) > 1 else "") + if not sequences: + raise InvalidParameterError("The file contains no sequences.") + return sequences, names diff --git a/openprotein/align/align.py b/openprotein/align/align.py index 7645bfa..d64ea5b 100644 --- a/openprotein/align/align.py +++ b/openprotein/align/align.py @@ -1,17 +1,29 @@ """Align API interface for creating alignments and MSAs (multiple sequence alignments) which can be used for other protein tasks.""" from collections.abc import Sequence -from io import BytesIO from typing import BinaryIO, Iterator +from openprotein import _deprecation from openprotein.base import APISession from openprotein.errors import DeprecationError from openprotein.jobs import Job -from openprotein.molecules import Protein from . import api +from ._files import read_file_content, read_sequences from .msa import MSAFuture -from .schemas import AbNumberScheme, AlignType, UnnumberedPolicy +from .schemas import AbNumberScheme, Pairing, UnnumberedPolicy + +__all__ = ["AlignAPI"] + + +def _as_sequences(sequences: Sequence[bytes | str]) -> list[str]: + """Coerce the caller's sequences to the JSON array the align endpoints take.""" + return [s.decode() if isinstance(s, bytes) else s for s in sequences] + + +def _as_names(names: Sequence[str] | None) -> list[str] | None: + """Coerce optional row labels to a list, leaving ``None`` alone.""" + return None if names is None else list(names) class AlignAPI: @@ -38,7 +50,8 @@ def mafft( sequences : Sequence[bytes or str] Sequences to align. names : Sequence[str], optional - Optional list of sequence names, must be the same length as sequences if provided. + Row labels for the aligned output, same length as sequences. Omit them + and the aligner labels the rows itself. auto : bool, default=True Set to True to automatically set algorithm parameters. ep : float, optional @@ -50,44 +63,39 @@ def mafft( ------- MSAFuture Future object awaiting the contents of the MSA upload. - - Raises - ------ - Exception - If names and sequences are not the same length. """ - if names is not None and len(names) != len(sequences): - raise Exception( - f"Names and sequences must be same length, but were {len(names)} and {len(sequences)}" - ) - lines = [] - if names is None: - # as CSV - lines = [s.encode() if isinstance(s, str) else s for s in sequences] - else: - # as fasta - for name, sequence in zip(names, sequences): - if isinstance(name, str): - name = name.encode() - if isinstance(sequence, str): - sequence = sequence.encode() - lines.append(b">" + name) - lines.append(sequence) - content = b"\n".join(lines) - stream = BytesIO(content) - return self.mafft_file(stream, auto=auto, ep=ep, op=op) - - def mafft_file(self, file, auto=True, ep=None, op=None) -> MSAFuture: + job = api.mafft_post( + self.session, + _as_sequences(sequences), + names=_as_names(names), + auto=auto, + ep=ep, + op=op, + ) + return MSAFuture.create(session=self.session, job=job) + + def mafft_file( + self, + file, + auto: bool = True, + ep: float | None = None, + op: float | None = None, + ) -> MSAFuture: """ - Align sequences using the `mafft` algorithm. Sequences can be provided as FASTA or CSV formats. - If CSV, the file must be headerless with either a single sequence column or name, sequence columns. + Align sequences from a file using the `mafft` algorithm. + + .. deprecated:: 0.18.0 + Use `AlignAPI.mafft` with sequences and names instead. + + Sequences can be provided as FASTA or CSV formats. If CSV, the file must be headerless with either a single sequence column or name, sequence columns. Set `auto` to True to automatically attempt the best parameters. Leave a parameter as None to use system defaults. Parameters ---------- - file : file-like object - Sequences to align in FASTA or CSV format. + file : file-like object, bytes, bytearray, str, tuple or list + Sequences to align in FASTA or CSV format. A tuple or list is + ``(filename, fileobj)`` or ``(filename, fileobj, content_type)``. auto : bool, default=True Set to True to automatically set algorithm parameters. ep : float, optional @@ -99,9 +107,20 @@ def mafft_file(self, file, auto=True, ep=None, op=None) -> MSAFuture: ------- MSAFuture Future object awaiting the contents of the MSA upload. + + Raises + ------ + InvalidParameterError + If the file has no sequences or a CSV has more than two columns. """ - job = api.mafft_post(self.session, file, auto=auto, ep=ep, op=op) - return MSAFuture.create(session=self.session, job=job) + _deprecation.warn_deprecated( + "AlignAPI.mafft_file", + "`AlignAPI.mafft` with sequences and names", + since="0.18.0", + removed_in="0.19.0", + ) + sequences, names = read_sequences(read_file_content(file)) + return self.mafft(sequences, names, auto=auto, ep=ep, op=op) def clustalo( self, @@ -113,14 +132,13 @@ def clustalo( """ Align sequences using the `clustal omega` algorithm. - Sequences can be provided as FASTA or CSV formats. If CSV, the file must be headerless with either a single sequence column or name, sequence columns. - Parameters ---------- sequences : Sequence[bytes or str] Sequences to align. names : Sequence[str], optional - Optional list of sequence names, must be the same length as sequences if provided. + Row labels for the aligned output, same length as sequences. Omit them + and the aligner labels the rows itself. clustersize : int, optional Maximum number of sequences per cluster during guide tree generation. If None, uses the default value. iterations : int, optional @@ -130,45 +148,35 @@ def clustalo( ------- MSAFuture Future object awaiting the contents of the MSA upload. - - Raises - ------ - Exception - If names and sequences are not the same length. """ - if names is not None and len(names) != len(sequences): - raise Exception( - f"Names and sequences must be same length, but were {len(names)} and {len(sequences)}" - ) - lines = [] - if names is None: - # as CSV - lines = [s.encode() if isinstance(s, str) else s for s in sequences] - else: - # as fasta - for name, sequence in zip(names, sequences): - if isinstance(name, str): - name = name.encode() - if isinstance(sequence, str): - sequence = sequence.encode() - lines.append(b">" + name) - lines.append(sequence) - content = b"\n".join(lines) - stream = BytesIO(content) - return self.clustalo_file( - stream, clustersize=clustersize, iterations=iterations + job = api.clustalo_post( + self.session, + _as_sequences(sequences), + names=_as_names(names), + clustersize=clustersize, + iterations=iterations, ) + return MSAFuture.create(session=self.session, job=job) - def clustalo_file(self, file, clustersize=None, iterations=None) -> MSAFuture: + def clustalo_file( + self, + file, + clustersize: int | None = None, + iterations: int | None = None, + ) -> MSAFuture: """ - Align sequences using the `clustal omega` algorithm. + Align sequences from a file using the `clustal omega` algorithm. + + .. deprecated:: 0.18.0 + Use `AlignAPI.clustalo` with sequences and names instead. Sequences can be provided as FASTA or CSV formats. If CSV, the file must be headerless with either a single sequence column or name, sequence columns. Parameters ---------- - file : file-like object - Sequences to align in FASTA or CSV format. + file : file-like object, bytes, bytearray, str, tuple or list + Sequences to align in FASTA or CSV format. A tuple or list is + ``(filename, fileobj)`` or ``(filename, fileobj, content_type)``. clustersize : int, optional Maximum number of sequences per cluster during guide tree generation. If None, uses the default value. iterations : int, optional @@ -178,11 +186,22 @@ def clustalo_file(self, file, clustersize=None, iterations=None) -> MSAFuture: ------- MSAFuture Future object awaiting the contents of the MSA upload. + + Raises + ------ + InvalidParameterError + If the file has no sequences or a CSV has more than two columns. """ - job = api.clustalo_post( - self.session, file, clustersize=clustersize, iterations=iterations + _deprecation.warn_deprecated( + "AlignAPI.clustalo_file", + "`AlignAPI.clustalo` with sequences and names", + since="0.18.0", + removed_in="0.19.0", + ) + sequences, names = read_sequences(read_file_content(file)) + return self.clustalo( + sequences, names, clustersize=clustersize, iterations=iterations ) - return MSAFuture.create(session=self.session, job=job) def abnumber( self, @@ -195,8 +214,6 @@ def abnumber( """ Align antibody sequences using `AbNumber`. - Sequences can be provided as FASTA or CSV formats. If CSV, the file must be headerless with either a single sequence column or name, sequence columns. - The antibody numbering scheme can be specified. Parameters @@ -204,7 +221,8 @@ def abnumber( sequences : Sequence[bytes or str] Sequences to align. names : Sequence[str], optional - Optional list of sequence names, must be the same length as sequences if provided. + Row labels for the aligned output, same length as sequences. Omit them + and the aligner labels the rows itself. scheme : AbNumberScheme, default=AbNumberScheme.CHOTHIA Antibody numbering scheme. drop_minority_chains : bool, default=False @@ -221,37 +239,16 @@ def abnumber( ------- MSAFuture Future object awaiting the contents of the MSA upload. - - Raises - ------ - Exception - If names and sequences are not the same length. """ - if names is not None and len(names) != len(sequences): - raise Exception( - f"Names and sequences must be same length, but were {len(names)} and {len(sequences)}" - ) - lines = [] - if names is None: - # as CSV - lines = [s.encode() if isinstance(s, str) else s for s in sequences] - else: - # as fasta - for name, sequence in zip(names, sequences): - if isinstance(name, str): - name = name.encode() - if isinstance(sequence, str): - sequence = sequence.encode() - lines.append(b">" + name) - lines.append(sequence) - content = b"\n".join(lines) - stream = BytesIO(content) - return self.abnumber_file( - stream, + job = api.abnumber_post( + self.session, + _as_sequences(sequences), + names=_as_names(names), scheme=scheme, drop_minority_chains=drop_minority_chains, unnumbered_policy=unnumbered_policy, ) + return MSAFuture.create(session=self.session, job=job) def abnumber_file( self, @@ -261,16 +258,18 @@ def abnumber_file( unnumbered_policy: UnnumberedPolicy = UnnumberedPolicy.ERROR, ) -> MSAFuture: """ - Align antibody sequences using `AbNumber`. + Align antibody sequences from a file using `AbNumber`. - Sequences can be provided as FASTA or CSV formats. If CSV, the file must be headerless with either a single sequence column or name, sequence columns. + .. deprecated:: 0.18.0 + Use `AlignAPI.abnumber` with sequences and names instead. - The antibody numbering scheme can be specified. + Sequences can be provided as FASTA or CSV formats. If CSV, the file must be headerless with either a single sequence column or name, sequence columns. Parameters ---------- - file : file-like object - Sequences to align in FASTA or CSV format. + file : file-like object, bytes, bytearray, str, tuple or list + Sequences to align in FASTA or CSV format. A tuple or list is + ``(filename, fileobj)`` or ``(filename, fileobj, content_type)``. scheme : AbNumberScheme, default=AbNumberScheme.CHOTHIA Antibody numbering scheme. drop_minority_chains : bool, default=False @@ -287,40 +286,67 @@ def abnumber_file( ------- MSAFuture Future object awaiting the contents of the MSA upload. + + Raises + ------ + InvalidParameterError + If the file has no sequences or a CSV has more than two columns. """ - job = api.abnumber_post( - self.session, - file, + _deprecation.warn_deprecated( + "AlignAPI.abnumber_file", + "`AlignAPI.abnumber` with sequences and names", + since="0.18.0", + removed_in="0.19.0", + ) + sequences, names = read_sequences(read_file_content(file)) + return self.abnumber( + sequences, + names, scheme=scheme, drop_minority_chains=drop_minority_chains, unnumbered_policy=unnumbered_policy, ) - return MSAFuture.create(session=self.session, job=job) def upload_msa(self, msa_file: BinaryIO) -> MSAFuture: """ - Upload an MSA from a file. + Upload a ready-made MSA. + + .. deprecated:: 0.18.0 + Use `session.data.MSA.create` and `MSA.sample_prompt` + instead. + + The returned future samples prompts with ``sample_prompt``. For a + complex, join the chains of each row with ``:``, or use the a3m + ``#\t`` header. Parameters ---------- - msa_file : str - Path to a ready-made MSA file. + msa_file : BinaryIO + The MSA as FASTA, a3m or a headerless CSV of names and sequences. Returns ------- MSAFuture - Future object awaiting the contents of the MSA upload. + Future for the upload. Raises ------ APIError If there is an issue with the API request. """ + _deprecation.warn_deprecated( + "AlignAPI.upload_msa", + "`session.data.MSA.create` and `MSA.sample_prompt`", + since="0.18.0", + removed_in="0.19.0", + ) return MSAFuture.create( - session=self.session, job=api.msa_post(self.session, msa_file=msa_file) + session=self.session, job=api._msa_post(self.session, msa_file=msa_file) ) - def create_msa(self, seed: bytes | str) -> MSAFuture: + def create_msa( + self, seed: bytes | str, pairing: Pairing = Pairing.BOTH + ) -> MSAFuture: """ Construct an MSA via homology search with the seed sequence. @@ -328,6 +354,9 @@ def create_msa(self, seed: bytes | str) -> MSAFuture: ---------- seed : bytes Seed sequence for the MSA construction. + pairing : Pairing, optional + Cross-chain pairing strategy for a complex (`:`-separated) seed; + has no effect on a single-chain seed. Defaults to `both`. Returns ------- @@ -340,7 +369,8 @@ def create_msa(self, seed: bytes | str) -> MSAFuture: If there is an issue with the API request. """ return MSAFuture.create( - session=self.session, job=api.msa_post(self.session, seed=seed) + session=self.session, + job=api._msa_mmseqs_search_post(self.session, seed=seed, pairing=pairing), ) def upload_prompt(self, prompt_file: BinaryIO): @@ -362,7 +392,7 @@ def upload_prompt(self, prompt_file: BinaryIO): Raises ------ DeprecationError - This method is no longer supported. + Always. Use `create_prompt` on the `prompt` module instead. """ raise DeprecationError( "This method is no longer supported! Use `create_prompt` on the `prompt` module instead." @@ -391,7 +421,7 @@ def get_prompt( Raises ------ DeprecationError - This method is no longer supported. + Always. Use `get_prompt` on the `prompt` module instead. """ raise DeprecationError( "This method is no longer supported! Use `get_prompt` on the `prompt` module instead." diff --git a/openprotein/align/api.py b/openprotein/align/api.py index bdb1b10..800bfe3 100644 --- a/openprotein/align/api.py +++ b/openprotein/align/api.py @@ -1,23 +1,88 @@ """Align REST API interface for making HTTP calls to our align backend.""" +import functools import io import random -from typing import BinaryIO, Iterator +from collections.abc import Callable, Iterator +from types import FunctionType +from typing import Any, BinaryIO import requests -from openprotein import csv, fasta -from openprotein.base import APISession -from openprotein.errors import APIError, InvalidParameterError, MissingParameterError -from openprotein.jobs import Job +from openprotein import _deprecation, csv, fasta +from openprotein.base import APISession, _silence_server_warnings +from openprotein.data.msa import MSADownloadFormat +from openprotein.data.msa._api import msa_download +from openprotein.errors import InvalidParameterError, MissingParameterError +from openprotein.jobs import Job, JobType +from openprotein.jobs.api import job_get +from openprotein.prompt.schemas import PromptMetadata +from ._files import read_file_content, read_sequences from .schemas import ( AbNumberScheme, AlignType, MSASamplingMethod, + Pairing, UnnumberedPolicy, ) +__all__ = [ + "abnumber_post", + "antibody_schema_get", + "clustalo_post", + "get_align_job_inputs", + "get_input", + "get_msa", + "get_seed", + "mafft_post", + "msa_post", + "prompt_post", +] + + +_MSA_REPLACEMENT = ( + "`MSAFuture.wait()` for the generated MSA, or " + "`session.data.MSA(id=...).to_string()`" +) +_PROMPT_REPLACEMENT = ( + "`Prompt.get()` for the replicates of a sampled prompt, indexed by replicate" +) +_SEED_REPLACEMENT = ( + "`openprotein.align.api.get_seed` for an MSA job's seed; the input of other " + "align jobs has no read of its own, so keep your own copy of the submitted " + "sequences" +) +_FUTURE_SEED_REPLACEMENT = "`MSAFuture.get_seed()` for the seed" + + +def _inputs_replacement(input_type: AlignType, *, on_future: bool = False) -> str: + """The replacement to name when the read of ``input_type`` is deprecated. + + ``on_future`` selects the text for reads through an ``MSAFuture``. + """ + if input_type == AlignType.MSA: + return _MSA_REPLACEMENT + if input_type == AlignType.PROMPT: + return _PROMPT_REPLACEMENT + return _FUTURE_SEED_REPLACEMENT if on_future else _SEED_REPLACEMENT + + +def _get_align_job_inputs( + session: APISession, + job_id: str, + input_type: AlignType, + prompt_index: int | None = None, +) -> requests.Response: + endpoint = "v1/align/inputs" + + params = {"job_id": job_id, "msa_type": input_type} + if prompt_index is not None: + params["replicate"] = prompt_index + + with _silence_server_warnings(): + return session.get(endpoint, params=params, stream=True) + def get_align_job_inputs( session: APISession, @@ -31,6 +96,15 @@ def get_align_job_inputs( Depending on `input_type`, returns either the original user seed (RAW), the generated MSA, or the prompt. If `input_type` is PROMPT, specify `prompt_index` to retrieve the specific prompt for each replicate. + .. deprecated:: 0.18.0 + For ``AlignType.MSA``, use `MSAFuture.wait()` for the generated MSA, or + `session.data.MSA(id=...).to_string()`. For ``AlignType.PROMPT``, use + `Prompt.get()` for the replicates of a sampled prompt, indexed by + replicate. For ``AlignType.INPUT``, use + `openprotein.align.api.get_seed` for an MSA job's seed; the input of other + align jobs has no read of its own, so keep your own copy of the submitted + sequences. + Parameters ---------- session : APISession @@ -47,14 +121,32 @@ def get_align_job_inputs( requests.Response The response object from the server. """ - endpoint = "v1/align/inputs" + _deprecation.warn_deprecated( + "openprotein.align.api.get_align_job_inputs", + _inputs_replacement(input_type), + since="0.18.0", + removed_in="0.19.0", + ) + return _get_align_job_inputs(session, job_id, input_type, prompt_index) - params = {"job_id": job_id, "msa_type": input_type} - if prompt_index is not None: - params["replicate"] = prompt_index - response = session.get(endpoint, params=params, stream=True) - return response +def _get_input( + session: APISession, + job_id: str, + input_type: AlignType, + prompt_index: int | None = None, +) -> Iterator[tuple[str, str]]: + response = _get_align_job_inputs( + session=session, job_id=job_id, input_type=input_type, prompt_index=prompt_index + ) + if response.headers.get("Content-Type") == "text/x-fasta": + return fasta.parse_stream(response.iter_lines(decode_unicode=True)) + else: + # take first two columns only + return ( + (row[0], row[1]) + for row in csv.parse_stream(response.iter_lines(decode_unicode=True)) + ) def get_input( @@ -66,6 +158,15 @@ def get_input( """ Retrieve input data for a given alignment job. + .. deprecated:: 0.18.0 + For ``AlignType.MSA``, use `MSAFuture.wait()` for the generated MSA, or + `session.data.MSA(id=...).to_string()`. For ``AlignType.PROMPT``, use + `Prompt.get()` for the replicates of a sampled prompt, indexed by + replicate. For ``AlignType.INPUT``, use + `openprotein.align.api.get_seed` for an MSA job's seed; the input of other + align jobs has no read of its own, so keep your own copy of the submitted + sequences. + Parameters ---------- session : APISession @@ -82,17 +183,13 @@ def get_input( Iterator[tuple[str, str]] An iterator over the name, sequence of the response. """ - response = get_align_job_inputs( - session=session, job_id=job_id, input_type=input_type, prompt_index=prompt_index + _deprecation.warn_deprecated( + "openprotein.align.api.get_input", + _inputs_replacement(input_type), + since="0.18.0", + removed_in="0.19.0", ) - if response.headers.get("Content-Type") == "text/x-fasta": - return fasta.parse_stream(response.iter_lines(decode_unicode=True)) - else: - # take first two columns only - return ( - (row[0], row[1]) - for row in csv.parse_stream(response.iter_lines(decode_unicode=True)) - ) + return _get_input(session, job_id, input_type, prompt_index) def get_seed(session: APISession, job_id: str) -> str: @@ -111,29 +208,66 @@ def get_seed(session: APISession, job_id: str) -> str: str The seed sequence. """ - # HACK for some reason this returns a csv - r = get_input(session=session, job_id=job_id, input_type=AlignType.INPUT) - seed = next(r)[1] - return seed + endpoint = "v1/align/seed" + response = session.get(endpoint, params={"msa_id": job_id}) + return response.json()["sequence"] + + +_FASTA_MSA_JOB_TYPES = { + JobType.mafft.value, + JobType.clustalo.value, + JobType.abnumber.value, +} + + +def _msa_format(job_type: str) -> MSADownloadFormat: + """The format an MSA is read in: FASTA for alignments, a3m for searches.""" + return "fasta" if job_type in _FASTA_MSA_JOB_TYPES else "a3m" + + +def _read_msa( + session: APISession, msa_id: str, format: MSADownloadFormat +) -> Iterator[tuple[str, str]]: + """Read a stored MSA in `format`, which must be "a3m" or "fasta".""" + content = msa_download(session, msa_id, format=format) + return fasta.parse_stream(iter(content.decode().splitlines())) def get_msa(session: APISession, job_id: str) -> Iterator[tuple[str, str]]: """ Retrieve the generated MSA (Multiple Sequence Alignment) for a given job. + The MSA is requested as a3m for a search or upload job and as FASTA for a + MAFFT, Clustal Omega or AbNumber job, whatever format it is stored in. + Parameters ---------- session : APISession The API session. job_id : str - The job identifier. + The job identifier, which is also the MSA identifier. Returns ------- Iterator[tuple[str, str]] An iterator over the name, sequence of the MSA. + + Raises + ------ + HTTPError + If the job is not found or its MSA is not stored. """ - return get_input(session=session, job_id=job_id, input_type=AlignType.MSA) + job = job_get(session, job_id) + return _read_msa(session, job_id, _msa_format(job.job_type)) + + +def _msa_post(session: APISession, msa_file: BinaryIO) -> Job: + endpoint = "v1/align/msa" + with _silence_server_warnings(): + response = session.post( + endpoint, files={"msa_file": msa_file}, params={"is_seed": False} + ) + return Job.model_validate(response.json()) def msa_post( @@ -142,19 +276,23 @@ def msa_post( seed: str | bytes | None = None, ) -> Job: """ - Create an MSA job. + Create an MSA job from a ready-made MSA or from a seed sequence. - Either a seed sequence (which will trigger MSA creation) or a ready-to-use MSA (via `msa_file`) must be provided. - `seed` and `msa_file` are mutually exclusive. + Exactly one of `msa_file` and `seed` must be provided. + + .. deprecated:: 0.18.0 + Use `session.data.MSA.create` for a ready-made MSA, or + `session.align.create_msa` for a seed. Parameters ---------- session : APISession The API session. msa_file : BinaryIO or None, optional - Ready-made MSA file. Defaults to None. + Ready-made MSA as FASTA, a3m or a headerless CSV of names and sequences. + Defaults to None. seed : str or bytes or None, optional - Seed sequence to trigger MSA job. Defaults to None. + Seed sequence to build an MSA from. Defaults to None. Raises ------ @@ -166,28 +304,131 @@ def msa_post( Job Job details. """ - if (msa_file is None and seed is None) or ( - msa_file is not None and seed is not None - ): + _deprecation.warn_deprecated( + "openprotein.align.api.msa_post", + "`session.data.MSA.create` for a ready-made MSA, " + "or `session.align.create_msa` for a seed", + since="0.18.0", + removed_in="0.19.0", + ) + if (msa_file is None) == (seed is None): raise MissingParameterError("seed OR msa_file must be provided.") - endpoint = "v1/align/msa" + if msa_file is not None: + return _msa_post(session, msa_file) + + assert seed is not None + seed = seed.encode() if isinstance(seed, str) else seed + with _silence_server_warnings(): + response = session.post( + "v1/align/msa", + files={"msa_file": io.BytesIO(b"\n".join([b">seed", seed]))}, + params={"is_seed": True}, + ) + return Job.model_validate(response.json()) + + +def _msa_mmseqs_search_post( + session: APISession, seed: str | bytes, pairing: Pairing = Pairing.BOTH +) -> Job: + """ + Launch a ColabFold MMseqs2 homology search to build an MSA for a query sequence. - is_seed = False - if seed is not None: - seed = seed.encode() if isinstance(seed, str) else seed - msa_file = io.BytesIO(b"\n".join([b">seed", seed])) - is_seed = True + Posts the query to the dedicated search endpoint. The query may be a single + sequence, or `:`-separated for a complex. - params = {"is_seed": is_seed} - files = {"msa_file": msa_file} + Parameters + ---------- + session : APISession + The API session. + seed : str or bytes + Query (seed) sequence to search. + pairing : Pairing, optional + Cross-chain pairing strategy for a complex query (default `both`); has no + effect on a single-chain query. - response = session.post(endpoint, files=files, params=params) + Returns + ------- + Job + Job details for the submitted search. + """ + endpoint = "v1/align/search/mmseqs2/msa" + + query = seed.decode() if isinstance(seed, bytes) else seed + data = {"query": query, "pairing": pairing.value} + + response = session.post(endpoint, data=data) return Job.model_validate(response.json()) +def _is_sequence_file(value: Any) -> bool: + """Whether ``value`` is a file, its content, or a ``(name, file)`` tuple.""" + if isinstance(value, tuple): + content = value[1] if len(value) > 1 else None + return hasattr(content, "read") or isinstance(content, (bytes, bytearray)) + return hasattr(value, "read") or isinstance(value, (bytes, bytearray, str)) + + +def _accepts_sequence_file( + *file_options: str, +) -> Callable[[FunctionType], Callable[..., Job]]: + """Let an align POST helper also take a deprecated ``sequence_file``. + + The file, given first or as ``sequence_file=``, is read into sequences and + names. ``file_options`` names the options that may follow it positionally. + """ + + def decorate(post: FunctionType) -> Callable[..., Job]: + name = post.__name__ + + @functools.wraps(post) + def wrapper( + session: APISession, *args: Any, sequence_file: Any = None, **kwargs: Any + ) -> Job: + if sequence_file is None and args and _is_sequence_file(args[0]): + sequence_file, args = args[0], args[1:] + if sequence_file is None: + return post(session, *args, **kwargs) + _deprecation.warn_deprecated( + f"openprotein.align.api.{name}(sequence_file=...)", + f"`openprotein.align.api.{name}` with sequences and names", + since="0.18.0", + removed_in="0.19.0", + ) + if len(args) > len(file_options): + raise TypeError( + f"{name}() takes at most {len(file_options)} options after " + "the sequence file" + ) + for option, value in zip(file_options, args): + if option in kwargs: + raise TypeError(f"{name}() got multiple values for {option!r}") + kwargs[option] = value + sequences, names = read_sequences(read_file_content(sequence_file)) + return post(session, sequences, names, **kwargs) + + return wrapper + + return decorate + + +def _body(sequences: list[str], names: list[str] | None) -> dict: + """The request body the align endpoints take.""" + body: dict = {"sequences": sequences} + if names is not None: + if len(names) != len(sequences): + raise InvalidParameterError( + "names and sequences must be the same length, " + f"not {len(names)} and {len(sequences)}" + ) + body["names"] = names + return body + + +@_accepts_sequence_file("auto", "ep", "op") def mafft_post( session: APISession, - sequence_file: BinaryIO, + sequences: list[str], + names: list[str] | None = None, auto: bool = True, ep: float | None = None, op: float | None = None, @@ -195,15 +436,23 @@ def mafft_post( """ Align sequences using the MAFFT algorithm. - Sequences can be provided as FASTA or CSV formats. If CSV, the file must be headerless with either a single sequence column or name, sequence columns. Set `auto` to True to automatically attempt the best parameters. Leave a parameter as None to use system defaults. + .. deprecated:: 0.18.0 + ``sequence_file``, a FASTA or headerless CSV file in place of + ``sequences`` and ``names``, is removed in 0.19.0. Pass ``sequences`` + and ``names`` instead. + Parameters ---------- session : APISession The API session. - sequence_file : BinaryIO - Sequences to align in FASTA or CSV format. + sequences : list[str] + Unaligned sequences, in the order they should be aligned. Use `:` to + separate the chains of a multi-chain sequence. + names : list[str] or None, optional + Row labels for the aligned output, same length as `sequences`. Omit them + and the aligner labels the rows itself. auto : bool, optional Set to True to automatically set algorithm parameters. Default is True. ep : float or None, optional @@ -218,35 +467,44 @@ def mafft_post( """ endpoint = "v1/align/mafft" - files = {"file": sequence_file} params: dict = {"auto": auto} if ep is not None: params["ep"] = ep if op is not None: params["op"] = op - response = session.post(endpoint, files=files, params=params) + response = session.post(endpoint, json=_body(sequences, names), params=params) return Job.model_validate(response.json()) +@_accepts_sequence_file("clustersize", "iterations") def clustalo_post( session: APISession, - sequence_file: BinaryIO, + sequences: list[str], + names: list[str] | None = None, clustersize: int | None = None, iterations: int | None = None, ) -> Job: """ Align sequences using the Clustal Omega algorithm. - Sequences can be provided as FASTA or CSV formats. If CSV, the file must be headerless with either a single sequence column or name, sequence columns. Leave a parameter as None to use system defaults. + .. deprecated:: 0.18.0 + ``sequence_file``, a FASTA or headerless CSV file in place of + ``sequences`` and ``names``, is removed in 0.19.0. Pass ``sequences`` + and ``names`` instead. + Parameters ---------- session : APISession The API session. - sequence_file : BinaryIO - Sequences to align in FASTA or CSV format. + sequences : list[str] + Unaligned sequences, in the order they should be aligned. Use `:` to + separate the chains of a multi-chain sequence. + names : list[str] or None, optional + Row labels for the aligned output, same length as `sequences`. Omit them + and the aligner labels the rows itself. clustersize : int or None, optional Clustal Omega parameter. Default is None. iterations : int or None, optional @@ -259,20 +517,21 @@ def clustalo_post( """ endpoint = "v1/align/clustalo" - files = {"file": sequence_file} params = {} if clustersize is not None: params["clustersize"] = clustersize if iterations is not None: params["iterations"] = iterations - response = session.post(endpoint, files=files, params=params) + response = session.post(endpoint, json=_body(sequences, names), params=params) return Job.model_validate(response.json()) +@_accepts_sequence_file("scheme", "drop_minority_chains", "unnumbered_policy") def abnumber_post( session: APISession, - sequence_file: BinaryIO, + sequences: list[str], + names: list[str] | None = None, scheme: AbNumberScheme | str = AbNumberScheme.IMGT, drop_minority_chains: bool = False, unnumbered_policy: UnnumberedPolicy | str = UnnumberedPolicy.ERROR, @@ -280,15 +539,23 @@ def abnumber_post( """ Align antibody sequences using AbNumber. - Sequences can be provided as FASTA or CSV formats. If CSV, the file must be headerless with either a single sequence column or name, sequence columns. The antibody numbering scheme can be specified. + .. deprecated:: 0.18.0 + ``sequence_file``, a FASTA or headerless CSV file in place of + ``sequences`` and ``names``, is removed in 0.19.0. Pass ``sequences`` + and ``names`` instead. + Parameters ---------- session : APISession The API session. - sequence_file : BinaryIO - Sequences to align in FASTA or CSV format. + sequences : list[str] + Unaligned sequences, in the order they should be aligned. Use `:` to + separate the chains of a multi-chain sequence. + names : list[str] or None, optional + Row labels for the aligned output, same length as `sequences`. Omit them + and the aligner labels the rows itself. scheme : AbNumberScheme, optional Antibody numbering scheme. Default is IMGT. drop_minority_chains : bool, optional @@ -315,7 +582,6 @@ def abnumber_post( f"Unnumbered residue policy {unnumbered_policy} not recognized" ) - files = {"file": sequence_file} params = { "scheme": scheme if isinstance(scheme, str) else scheme.value, "drop_minority_chains": drop_minority_chains, @@ -326,7 +592,7 @@ def abnumber_post( ), } - response = session.post(endpoint, files=files, params=params) + response = session.post(endpoint, json=_body(sequences, names), params=params) return Job.model_validate(response.json()) @@ -353,6 +619,56 @@ def antibody_schema_get(session: APISession, job_id: str) -> dict: return response.json() +def _sample_params( + msa_id: str, + num_sequences: int | None, + num_residues: int | None, + method: MSASamplingMethod, + homology_level: float, + max_similarity: float, + min_similarity: float, + always_include_seed_sequence: bool, + num_ensemble_prompts: int, + random_seed: int | None, +) -> dict: + """The query params of a prompt sampling request, checked.""" + if not (0 <= homology_level <= 1): + raise InvalidParameterError("The 'homology_level' must be between 0 and 1.") + if not (0 <= max_similarity <= 1): + raise InvalidParameterError("The 'max_similarity' must be between 0 and 1.") + if not (0 <= min_similarity <= 1): + raise InvalidParameterError("The 'min_similarity' must be between 0 and 1.") + + if num_residues is None and num_sequences is None: + num_residues = 12288 + + if (num_sequences is None and num_residues is None) or ( + num_sequences is not None and num_residues is not None + ): + raise MissingParameterError( + "Either 'num_sequences' or 'num_residues' must be set, but not both." + ) + + if random_seed is None: + random_seed = random.randrange(2**32) + + params = { + "msa_id": msa_id, + "msa_method": method, + "homology_level": homology_level, + "max_similarity": max_similarity, + "min_similarity": min_similarity, + "force_include_first": always_include_seed_sequence, + "replicates": num_ensemble_prompts, + "seed": random_seed, + } + if num_sequences is not None: + params["max_msa_sequences"] = num_sequences + if num_residues is not None: + params["max_msa_tokens"] = num_residues + return params + + def prompt_post( session: APISession, msa_id: str, @@ -371,6 +687,9 @@ def prompt_post( The MSA is specified by `msa_id` and created in `msa_post`. + .. deprecated:: 0.18.0 + Use `MSAFuture.sample_prompt` or `MSA.sample_prompt`. + Parameters ---------- session : APISession @@ -408,42 +727,57 @@ def prompt_post( Job Job details. """ - endpoint = "v1/align/prompt" - - if not (0 <= homology_level <= 1): - raise InvalidParameterError("The 'homology_level' must be between 0 and 1.") - if not (0 <= max_similarity <= 1): - raise InvalidParameterError("The 'max_similarity' must be between 0 and 1.") - if not (0 <= min_similarity <= 1): - raise InvalidParameterError("The 'min_similarity' must be between 0 and 1.") - - if num_residues is None and num_sequences is None: - num_residues = 12288 - - if (num_sequences is None and num_residues is None) or ( - num_sequences is not None and num_residues is not None - ): - raise MissingParameterError( - "Either 'num_sequences' or 'num_residues' must be set, but not both." - ) + _deprecation.warn_deprecated( + "openprotein.align.api.prompt_post", + "`MSAFuture.sample_prompt` or `MSA.sample_prompt`", + since="0.18.0", + removed_in="0.19.0", + ) + params = _sample_params( + msa_id, + num_sequences, + num_residues, + method, + homology_level, + max_similarity, + min_similarity, + always_include_seed_sequence, + num_ensemble_prompts, + random_seed, + ) + with _silence_server_warnings(): + response = session.post("v1/align/prompt", params=params) + return Job.model_validate(response.json()) - if random_seed is None: - random_seed = random.randrange(2**32) - params = { - "msa_id": msa_id, - "msa_method": method, - "homology_level": homology_level, - "max_similarity": max_similarity, - "min_similarity": min_similarity, - "force_include_first": always_include_seed_sequence, - "replicates": num_ensemble_prompts, - "seed": random_seed, - } - if num_sequences is not None: - params["max_msa_sequences"] = num_sequences - if num_residues is not None: - params["max_msa_tokens"] = num_residues +def _sample_prompt( + session: APISession, + msa_id: str, + num_sequences: int | None = None, + num_residues: int | None = None, + method: MSASamplingMethod = MSASamplingMethod.NEIGHBORS_NONGAP_NORM_NO_LIMIT, + homology_level: float = 0.8, + max_similarity: float = 1.0, + min_similarity: float = 0.0, + always_include_seed_sequence: bool = False, + num_ensemble_prompts: int = 1, + random_seed: int | None = None, +) -> PromptMetadata: + """Sample a prompt from an MSA; returns its metadata in PENDING status. - response = session.post(endpoint, params=params) - return Job.model_validate(response.json()) + Takes the parameters of `prompt_post`. + """ + params = _sample_params( + msa_id, + num_sequences, + num_residues, + method, + homology_level, + max_similarity, + min_similarity, + always_include_seed_sequence, + num_ensemble_prompts, + random_seed, + ) + response = session.post("v1/prompt/sample_msa", params=params) + return PromptMetadata.model_validate(response.json()) diff --git a/openprotein/align/future.py b/openprotein/align/future.py index 59ec5f1..0cbd8bd 100644 --- a/openprotein/align/future.py +++ b/openprotein/align/future.py @@ -1,11 +1,14 @@ """Align results represented as futures.""" +from openprotein import _deprecation from openprotein.base import APISession from openprotein.jobs import Job from . import api from .schemas import AlignType +__all__ = ["AlignFuture"] + class AlignFuture: """A future object representing an alignment job, providing methods to retrieve job inputs and seed sequences.""" @@ -17,6 +20,13 @@ def get_input(self, input_type: AlignType): """ Retrieve input data for this alignment job. + .. deprecated:: 0.18.0 + For ``AlignType.MSA``, use `MSAFuture.wait()` for the generated MSA, or + `session.data.MSA(id=...).to_string()`. For ``AlignType.PROMPT``, use + `Prompt.get()` for the replicates of a sampled prompt, indexed by + replicate. For ``AlignType.INPUT``, use + `MSAFuture.get_seed()` for the seed. + Parameters ---------- input_type : AlignType @@ -27,7 +37,13 @@ def get_input(self, input_type: AlignType): Iterator[list[str]] An iterator over the input data rows. """ - return api.get_input( + _deprecation.warn_deprecated( + "openprotein.align.future.AlignFuture.get_input", + api._inputs_replacement(input_type, on_future=True), + since="0.18.0", + removed_in="0.19.0", + ) + return api._get_input( session=self.session, job_id=self.job.job_id, input_type=input_type ) diff --git a/openprotein/align/msa.py b/openprotein/align/msa.py index 9835ca9..b20e1d7 100644 --- a/openprotein/align/msa.py +++ b/openprotein/align/msa.py @@ -1,11 +1,11 @@ """MSA results represented as a future.""" import warnings -from typing import Iterator +from collections.abc import Iterator from openprotein import config from openprotein.base import APISession -from openprotein.jobs import Future, JobType +from openprotein.jobs import Future from openprotein.prompt import Prompt from . import api @@ -19,11 +19,18 @@ MSASamplingMethod, ) +__all__ = ["MSAFuture"] -# TODO - AbNumber should probably be different subclass, because it supports an additional `get` API for the antibody numbering + +# TODO - AbNumber should be a separate subclass, since it supports an extra `get` API for antibody numbering class MSAFuture(AlignFuture, Future): """ Represents a future for MSA (Multiple Sequence Alignment) results. + + See Also + -------- + openprotein.data.MSA : A stored MSA. ``session.data.MSA`` uploads, lists and + loads MSAs. """ job: MSAJob | MafftJob | ClustalOJob | AbNumberJob @@ -63,7 +70,11 @@ def _get(self, verbose: bool = False) -> Iterator[tuple[str, str]]: An iterator over names and sequences of the MSA data. """ self._warn_once() - return api.get_msa(session=self.session, job_id=self.job.job_id) + return api._read_msa( + session=self.session, + msa_id=self.job.msa_id, + format=api._msa_format(self.job.job_type), + ) def _warn_once(self) -> None: """Surface what the job reported about its own output, once.""" @@ -73,7 +84,7 @@ def _warn_once(self) -> None: try: job_warnings = self.get_warnings() except Exception: - # reading the results cannot depend on the schema endpoint answering + # warnings are best-effort and never block reading results return for job_warning in job_warnings: warnings.warn(f"{job_warning.code}: {job_warning.message}") @@ -159,7 +170,7 @@ def sample_prompt( A Prompt instance for the created prompt job. """ msa_id = self.msa_id - job = api.prompt_post( + metadata = api._sample_prompt( self.session, msa_id=msa_id, num_sequences=num_sequences, @@ -172,7 +183,4 @@ def sample_prompt( num_ensemble_prompts=num_ensemble_prompts, random_seed=random_seed, ) - future = Prompt.create( - session=self.session, job=job, num_replicates=num_ensemble_prompts - ) - return future + return Prompt(session=self.session, metadata=metadata) diff --git a/openprotein/align/schemas.py b/openprotein/align/schemas.py index 9761ad4..ff3c0c9 100644 --- a/openprotein/align/schemas.py +++ b/openprotein/align/schemas.py @@ -7,6 +7,20 @@ from openprotein.jobs import Job, JobType +__all__ = [ + "AbNumberJob", + "AbNumberScheme", + "AlignType", + "ClustalOJob", + "JobWarning", + "MSAJob", + "MSASamplingMethod", + "MafftJob", + "Pairing", + "PromptPostParams", + "UnnumberedPolicy", +] + class AlignType(str, Enum): """ @@ -52,6 +66,27 @@ class MSASamplingMethod(str, Enum): TOP = "TOP" +class Pairing(str, Enum): + """ + Cross-chain pairing strategy for a complex (multi-chain) MSA search. + + Has no effect on a single-chain query. + + Attributes + ---------- + UNPAIRED : str + Search each chain independently. + PAIRED : str + Keep only cross-chain paired hits. + BOTH : str + Return both paired and unpaired hits (the default). + """ + + UNPAIRED = "unpaired" + PAIRED = "paired" + BOTH = "both" + + class PromptPostParams(BaseModel): """ Parameters for posting a prompt to generate an MSA. @@ -99,7 +134,7 @@ class MSAJob(Job): Attributes ---------- job_type : Literal[JobType.align_align] - The type of job (must be JobType.align_align). + Discriminator identifying a generic alignment job. """ job_type: Literal[JobType.align_align] @@ -107,14 +142,14 @@ class MSAJob(Job): @property def msa_id(self): """ - Returns the MSA identifier for this job. + The MSA identifier for this job. Returns ------- str - The MSA identifier. + Identifier of the MSA this job produced, used to fetch its results. """ - return self.msa_id + return (self.model_extra or {}).get("msa_id") or self.job_id class MafftJob(MSAJob, Job): @@ -124,7 +159,7 @@ class MafftJob(MSAJob, Job): Attributes ---------- job_type : Literal[JobType.mafft] - The type of job (must be JobType.mafft). + Discriminator identifying a MAFFT alignment job. """ job_type: Literal[JobType.mafft] @@ -137,7 +172,7 @@ class ClustalOJob(MSAJob, Job): Attributes ---------- job_type : Literal[JobType.clustalo] - The type of job (must be JobType.clustalo). + Discriminator identifying a Clustal Omega alignment job. """ job_type: Literal[JobType.clustalo] @@ -150,7 +185,7 @@ class AbNumberJob(MSAJob, Job): Attributes ---------- job_type : Literal[JobType.abnumber] - The type of job (must be JobType.abnumber). + Discriminator identifying an AbNumber antibody-numbering job. """ job_type: Literal[JobType.abnumber] diff --git a/openprotein/auth_store.py b/openprotein/auth_store.py index 209d2b2..7160a83 100644 --- a/openprotein/auth_store.py +++ b/openprotein/auth_store.py @@ -6,6 +6,8 @@ from filelock import FileLock from pydantic import BaseModel, ValidationError +__all__ = ["TokenRecord", "TokenStore"] + class TokenRecord(BaseModel): """A persisted auth record for one identity.""" @@ -40,8 +42,7 @@ def lock(self): return self._lock def _read_all(self) -> dict: - # Caller must hold self._lock: this is the read half of the - # read-modify-write critical section in load()/save(). + # Caller must hold self._lock. try: return json.loads(self.path.read_text()) except (OSError, json.JSONDecodeError): diff --git a/openprotein/base.py b/openprotein/base.py index deca00d..9402613 100644 --- a/openprotein/base.py +++ b/openprotein/base.py @@ -1,23 +1,151 @@ +import contextvars +import re import sys import threading import time import warnings -from typing import Mapping, Sequence +from collections.abc import Generator, Mapping, Sequence +from contextlib import contextmanager from urllib.parse import urljoin import requests import requests.auth from requests.adapters import HTTPAdapter +from requests.models import complexjson from requests.packages.urllib3.util.retry import Retry # type: ignore from openprotein._version import __version__ from openprotein.auth_store import TokenRecord, TokenStore from openprotein.errors import AuthError, HTTPError -# Refresh the access token this many seconds before it actually expires, -# to absorb clock skew and request latency. 30s is a conservative buffer for -# typical clock drift plus a round-trip against a ~15-minute access token. -SKEW_SECONDS = 30 +__all__ = [ + "APISession", + "BearerAuth", + "CloudFrontError", + "TimeoutError", +] + + +class _NoReplayRetry(Retry): + """Resend a POST only when it failed to connect, so it was never sent. + + urllib3 retries an unclassified error such as a TLS failure for every + method, after the server may already have received the request. + """ + + def increment( + self, + method=None, + url=None, + response=None, + error=None, + _pool=None, + _stacktrace=None, + ): + if ( + (method or "").upper() == "POST" + and error is not None + and not self._is_connection_error(error) + ): + raise error.with_traceback(_stacktrace) + return super().increment(method, url, response, error, _pool, _stacktrace) + + +class _ModelSubmissionRetry(_NoReplayRetry): + """Retry model POSTs on 503 or a failure to establish a connection.""" + + def is_retry(self, method, status_code, has_retry_after=False): + if method.upper() == "POST": + return status_code == 503 + return super().is_retry(method, status_code, has_retry_after) + + +# Each POST to these creates a new sampling job, so a resend samples twice. +_SAMPLING_PATHS = ( + "v1/data/prompts/sample_msa", + "v1/prompt/sample_msa", + "v1/align/prompt", +) + + +# Refresh the access token this many seconds before it expires, to absorb +# clock skew and request latency. +_SKEW_SECONDS = 30 +_IDEMPOTENCY_KEY_HEADER = "Idempotency-Key" + + +def _freeze_idempotent_json(kwargs: dict) -> None: + """Make a keyed JSON request's body stable across session-level retries. + + urllib3 retries one prepared request, but the reactive authentication retry + below prepares a request again. Supplying the already encoded bytes for both + paths keeps the body byte-for-byte identical while leaving ordinary SDK + requests on the existing ``json=`` path. + """ + headers = kwargs.get("headers") + if not isinstance(headers, Mapping) or "json" not in kwargs: + return + if not any( + isinstance(name, str) and name.lower() == _IDEMPOTENCY_KEY_HEADER.lower() + for name in headers + ): + return + if "data" in kwargs and kwargs["data"] is not None: + return + if kwargs["json"] is None: + return + + kwargs["data"] = complexjson.dumps(kwargs["json"], allow_nan=False).encode("utf-8") + request_headers = dict(headers) + if not any( + isinstance(name, str) and name.lower() == "content-type" + for name in request_headers + ): + request_headers["Content-Type"] = "application/json" + kwargs["headers"] = request_headers + + +# `299 ""`: a persistent warning, which the API sends on deprecated calls +_SERVER_WARNING = re.compile(r'299\s+\S+\s+"(?P[^"]*)"') + + +_server_warnings_silenced: contextvars.ContextVar[bool] = contextvars.ContextVar( + "server_warnings_silenced", default=False +) + + +@contextmanager +def _silence_server_warnings() -> Generator[None]: + """Drop the server's `Warning: 299` header on requests made in this block. + + For SDK functions that emit their own versioned deprecation warning. + """ + token = _server_warnings_silenced.set(True) + try: + yield + finally: + _server_warnings_silenced.reset(token) + + +@contextmanager +def _surface_server_warnings() -> Generator[None]: + """Keep the server's `Warning: 299` header on requests made in this block, + inside a call that silences it for its own request. + """ + token = _server_warnings_silenced.set(False) + try: + yield + finally: + _server_warnings_silenced.reset(token) + + +def _warn_from_server(response: requests.Response) -> None: + """Surface a response's `Warning: 299` header as a `FutureWarning`.""" + if _server_warnings_silenced.get(): + return + match = _SERVER_WARNING.match(response.headers.get("Warning", "")) + if match is not None: + warnings.warn(match["text"], FutureWarning, stacklevel=2) class BearerAuth(requests.auth.AuthBase): @@ -57,22 +185,7 @@ 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." ) - super().__init__() - self.backend = backend - self.verify = True - self.timeout = timeout - - # Custom retry strategies - # auto retry for pesky connection reset errors and others - # 503 will catch if BE is refreshing - retry = Retry( - total=4, - backoff_factor=3, # 0,1,4,13s - status_forcelist=[500, 502, 503, 504, 101, 104], - ) - adapter = HTTPAdapter(max_retries=retry) - self.mount("https://", adapter) - self.headers["User-Agent"] = f"openprotein-python/{__version__}" + self._init_transport(backend, timeout) # Auth / refresh state. Initialised before any network call so that # request() can read _refreshing / _legacy_mode safely. @@ -93,6 +206,40 @@ def __init__( self._init_auth() + def _init_transport(self, backend: str, timeout: float) -> None: + """Configure the HTTP transport: retry policy, adapters, and headers.""" + super().__init__() + self.backend = backend + self.verify = True + self.timeout = timeout + + retry = Retry( + total=4, + backoff_factor=3, # 0,1,4,13s + status_forcelist=[500, 502, 503, 504, 101, 104], + raise_on_status=False, + ) + adapter = HTTPAdapter(max_retries=retry) + for scheme in ("https://", "http://"): + self.mount(scheme, adapter) + model_retry = _ModelSubmissionRetry( + total=retry.total, + backoff_factor=retry.backoff_factor, + status_forcelist=retry.status_forcelist, + allowed_methods=frozenset({"GET"}), + raise_on_status=False, + ) + self.mount(urljoin(backend, "v1/models/"), HTTPAdapter(max_retries=model_retry)) + sampling_retry = _NoReplayRetry( + total=retry.total, + backoff_factor=retry.backoff_factor, + status_forcelist=retry.status_forcelist, + raise_on_status=False, + ) + for path in _SAMPLING_PATHS: + self.mount(urljoin(backend, path), HTTPAdapter(max_retries=sampling_retry)) + self.headers["User-Agent"] = f"openprotein-python/{__version__}" + @property def _refreshing(self) -> bool: return getattr(self._tl, "refreshing", False) @@ -138,7 +285,6 @@ def login(self, username: str, password: str): password: str password """ - # unset the auth first self.auth = None self._get_auth_token(username, password) @@ -165,7 +311,7 @@ def _get_auth_token(self, username: str, password: str): ) except HTTPError as e: if e.status_code == 404: - # Backend not yet upgraded -> use the legacy endpoint. + # Older servers have no token endpoint; use the legacy login. return self._legacy_login(username, password) raise AuthError( "Authentication failed. Please check your credentials and connection." @@ -199,7 +345,7 @@ def _apply_token_response(self, result: dict, username: str): raise AuthError("Unable to authenticate with given credentials.") refresh_token = result.get("refresh_token") if refresh_token is None: - # Cookie-mode / pre-rotation backend -> no refresh available. + # No refresh token issued, so refresh is unavailable. self._legacy_mode = True self._refresh_token = None self._expires_at = 0.0 @@ -245,7 +391,11 @@ def _refresh(self): already rotated the token, adopt that instead of refreshing again (replaying a superseded refresh token would revoke the session). """ - with self._refresh_lock, self._token_store.lock(): + with ( + self._refresh_lock, + self._token_store.lock(), + _surface_server_warnings(), + ): record = self._token_store.load(self._identity) if ( record is not None @@ -268,12 +418,9 @@ def _refresh(self): timeout=10, ) except HTTPError as e: - # Recover by re-logging-in when the refresh token is rejected - # (401/403) or when the endpoint is absent (404 from a backend - # that issued a refresh token but doesn't expose /auth/refresh, - # e.g. mid-rollback) — re-login itself drops to legacy mode if - # the backend has no refresh support. Other statuses are real - # errors and propagate. + # A rejected (401/403) or missing (404) refresh endpoint falls back + # to a fresh login, which drops to legacy mode when the server has + # no refresh support. Other statuses propagate. if e.status_code in (401, 403, 404): self._relogin() return @@ -294,13 +441,19 @@ def _should_refresh_proactively(self) -> bool: not self._refreshing and not self._legacy_mode and self._refresh_token is not None - and time.time() >= self._expires_at - SKEW_SECONDS + and time.time() >= self._expires_at - _SKEW_SECONDS ) def request(self, method: str, url: str, *args, **kwargs): + kwargs.setdefault("timeout", self.timeout) if self._should_refresh_proactively(): self._refresh() + # Freeze the JSON body once so a reactive 401 retry resends the same + # payload under the same idempotency key. + if method.upper() == "POST": + _freeze_idempotent_json(kwargs) + full_url = urljoin(self.backend, url) response = super().request(method, full_url, *args, **kwargs) @@ -314,13 +467,13 @@ def request(self, method: str, url: str, *args, **kwargs): self._refresh() response = super().request(method, full_url, *args, **kwargs) - if (js := kwargs.get("json")) and js is not None: - if _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." - ) + _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." + ) - # intercept CloudFront errors if "cloudfront" in response.headers.get("Server", "").lower(): if response.status_code in (502, 503): raise CloudFrontError( @@ -330,8 +483,7 @@ def request(self, method: str, url: str, *args, **kwargs): 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." ) - elif not response.ok: - # raise custom exception that prints better error message than requests.HTTPError + if not response.ok: raise HTTPError(response) return response diff --git a/openprotein/chains.py b/openprotein/chains.py deleted file mode 100644 index d261285..0000000 --- a/openprotein/chains.py +++ /dev/null @@ -1,12 +0,0 @@ -import warnings - -warnings.warn( - "openprotein.chains is deprecated and will be removed in v0.11. " - "Use `from openprotein.molecules import DNA, RNA, Ligand` instead.", - FutureWarning, - stacklevel=2, -) - -from openprotein.molecules import DNA, RNA, Ligand - -__all__ = ["DNA", "RNA", "Ligand"] diff --git a/openprotein/clustering/__init__.py b/openprotein/clustering/__init__.py index 6efd8dc..f9f0959 100644 --- a/openprotein/clustering/__init__.py +++ b/openprotein/clustering/__init__.py @@ -12,3 +12,13 @@ ) from .models import HierarchicalClusteringFuture from .clustering import ClusteringAPI + +__all__ = [ + "ClusteringAPI", + "ClusteringMetadata", + "HierarchicalClusteringFuture", + "HierarchicalClusteringResult", + "HierarchicalFitJob", + "LinkageMethod", + "Metric", +] diff --git a/openprotein/clustering/api.py b/openprotein/clustering/api.py index 073821d..f05f61f 100644 --- a/openprotein/clustering/api.py +++ b/openprotein/clustering/api.py @@ -11,7 +11,18 @@ HierarchicalFitJob, ) -PATH_PREFIX = "v1/clustering" +__all__ = [ + "clustering_delete", + "clustering_get", + "clustering_get_result", + "clustering_get_sequences", + "clustering_hierarchical_post", + "clustering_list_get", + "clustering_redispatch_post", +] + + +_PATH_PREFIX = "v1/clustering" def clustering_list_get( @@ -28,35 +39,33 @@ def clustering_list_get( params["limit"] = limit if offset is not None: params["offset"] = offset - response = session.get(PATH_PREFIX, params=params or None) + response = session.get(_PATH_PREFIX, params=params or None) return TypeAdapter(list[ClusteringMetadata]).validate_python(response.json()) def clustering_get(session: APISession, clustering_id: str) -> ClusteringMetadata: """Fetch clustering job metadata.""" - response = session.get(f"{PATH_PREFIX}/{clustering_id}") + response = session.get(f"{_PATH_PREFIX}/{clustering_id}") return ClusteringMetadata.model_validate(response.json()) def clustering_get_result( session: APISession, clustering_id: str ) -> HierarchicalClusteringResult: - """Fetch the clustering result (linkage + leaf_order). Sequences are NOT - filled by this function — callers that need them should call - `clustering_get_sequences` and assign to `.sequences`.""" - response = session.get(f"{PATH_PREFIX}/{clustering_id}/result") + """Fetch the clustering result (linkage + leaf_order).""" + response = session.get(f"{_PATH_PREFIX}/{clustering_id}/result") return HierarchicalClusteringResult.model_validate(response.json()) def clustering_get_sequences(session: APISession, clustering_id: str) -> list[bytes]: """Fetch the input sequences used for the clustering job.""" - response = session.get(f"{PATH_PREFIX}/{clustering_id}/sequences") + response = session.get(f"{_PATH_PREFIX}/{clustering_id}/sequences") return TypeAdapter(list[bytes]).validate_python(response.json()) def clustering_delete(session: APISession, clustering_id: str) -> bool: """Delete a clustering job.""" - response = session.delete(f"{PATH_PREFIX}/{clustering_id}") + response = session.delete(f"{_PATH_PREFIX}/{clustering_id}") if 200 <= response.status_code < 300: return True raise APIError(response.text) @@ -65,8 +74,8 @@ def clustering_delete(session: APISession, clustering_id: str) -> bool: def clustering_redispatch_post( session: APISession, clustering_id: str ) -> HierarchicalFitJob: - """Redispatch a clustering job.""" - response = session.post(f"{PATH_PREFIX}/{clustering_id}/redispatch") + """Resubmit a clustering job.""" + response = session.post(f"{_PATH_PREFIX}/{clustering_id}/redispatch") return HierarchicalFitJob.model_validate(response.json()) @@ -105,5 +114,5 @@ def clustering_hierarchical_post( body["assay_id"] = assay_id body.update(**kwargs) - response = session.post(f"{PATH_PREFIX}/hierarchical", json=body) + response = session.post(f"{_PATH_PREFIX}/hierarchical", json=body) return HierarchicalFitJob.model_validate(response.json()) diff --git a/openprotein/clustering/clustering.py b/openprotein/clustering/clustering.py index 383fbae..9861d7b 100644 --- a/openprotein/clustering/clustering.py +++ b/openprotein/clustering/clustering.py @@ -13,6 +13,8 @@ from .models import HierarchicalClusteringFuture from .schemas import LinkageMethod, Metric +__all__ = ["ClusteringAPI"] + class ClusteringAPI: """Top-level clustering API. Use `session.clustering.hierarchical(...)` to @@ -60,11 +62,12 @@ def hierarchical( ) -> HierarchicalClusteringFuture: """Fit a hierarchical clustering on sequences, returning a future that resolves to a HierarchicalClusteringResult (scipy linkage + leaf order).""" - # resolve assay_id assay_id = ( assay.assay_id if isinstance(assay, AssayMetadata) - else assay.id if isinstance(assay, AssayDataset) else assay + else assay.id + if isinstance(assay, AssayDataset) + else assay ) if sequences is not None and assay_id is not None: raise InvalidParameterError( @@ -80,11 +83,12 @@ def hierarchical( raise InvalidParameterError( f"clustering size cap exceeded: N={n} > 10000" ) - # infer feature_type from model type feature_type = ( FeatureType.PLM if isinstance(model, EmbeddingModel) - else FeatureType.SVD if isinstance(model, SVDModel) else feature_type + else FeatureType.SVD + if isinstance(model, SVDModel) + else feature_type ) if feature_type is None: raise InvalidParameterError( @@ -94,7 +98,6 @@ def hierarchical( feature_type = FeatureType(feature_type) if isinstance(reduction, str): reduction = ReductionType(reduction) - # combo validation — mirrors the Go server rule _WARD_ONLY_METRICS = {"ward", "centroid", "median"} lm_val = ( linkage_method.value @@ -106,7 +109,6 @@ def hierarchical( raise InvalidParameterError( f"linkage_method={lm_val!r} requires metric='euclidean', got {m_val!r}" ) - # resolve model_id and svd_id svd_id: str | None = None if feature_type == FeatureType.PLM: if reduction is None: @@ -160,8 +162,6 @@ def hierarchical( def get(self, clustering_id: str) -> HierarchicalClusteringFuture: """Fetch a clustering job by ID.""" - # Single-method dispatch today; when new methods are added, - # branch on metadata.method to pick the concrete future type. metadata = api.clustering_get(self.session, clustering_id) return HierarchicalClusteringFuture(session=self.session, metadata=metadata) @@ -171,12 +171,7 @@ def list( limit: int | None = None, offset: int | None = None, ) -> list[HierarchicalClusteringFuture]: - """List clustering jobs, optionally filtering by method. - - Pass `limit` / `offset` to paginate (the clustering list endpoint - uses `limit`/`offset`, unlike the `jobs` endpoint's page_size/page_offset).""" - # Single-method dispatch today; when new methods are added, - # branch on metadata.method to pick the concrete future type. + """List clustering jobs, optionally filtering by method.""" return [ HierarchicalClusteringFuture(session=self.session, metadata=md) for md in api.clustering_list_get( diff --git a/openprotein/clustering/models.py b/openprotein/clustering/models.py index f97d4c2..0cbedb3 100644 --- a/openprotein/clustering/models.py +++ b/openprotein/clustering/models.py @@ -4,7 +4,13 @@ from openprotein.jobs import Future, JobsAPI from . import api -from .schemas import ClusteringMetadata, HierarchicalClusteringResult, HierarchicalFitJob +from .schemas import ( + ClusteringMetadata, + HierarchicalClusteringResult, + HierarchicalFitJob, +) + +__all__ = ["HierarchicalClusteringFuture"] class HierarchicalClusteringFuture(Future["HierarchicalClusteringResult"]): @@ -27,9 +33,7 @@ def __init__( if job is None: jobs_api = getattr(session, "jobs", None) assert isinstance(jobs_api, JobsAPI) - job = HierarchicalFitJob.create( - jobs_api.get_job(job_id=metadata.id) - ) + job = HierarchicalFitJob.create(jobs_api.get_job(job_id=metadata.id)) self._sequences: list[bytes] | None = None super().__init__(session, job) @@ -52,7 +56,7 @@ def metadata(self) -> ClusteringMetadata: @property def sequences(self) -> list[bytes]: - """Input sequences used to fit the clustering job (cached).""" + """Input sequences used to fit the clustering job.""" if self._sequences is None: self._sequences = api.clustering_get_sequences( session=self.session, clustering_id=self.id @@ -60,7 +64,7 @@ def sequences(self) -> list[bytes]: return self._sequences def _get(self, verbose: bool = False) -> HierarchicalClusteringResult: - """Fetch the clustering result. Called by Future.get after SUCCESS.""" + """Fetch the clustering result.""" result = api.clustering_get_result(self.session, self.id) result.sequences = self.sequences return result @@ -70,6 +74,6 @@ def delete(self) -> bool: return api.clustering_delete(self.session, self.id) def redispatch(self) -> "HierarchicalClusteringFuture": - """Redispatch this clustering job.""" + """Resubmit this clustering job.""" job = api.clustering_redispatch_post(self.session, self.id) return HierarchicalClusteringFuture(session=self.session, job=job) diff --git a/openprotein/clustering/schemas.py b/openprotein/clustering/schemas.py index 4644770..2a0fa10 100644 --- a/openprotein/clustering/schemas.py +++ b/openprotein/clustering/schemas.py @@ -10,6 +10,14 @@ from openprotein.common import FeatureType from openprotein.jobs import Job, JobStatus, JobType +__all__ = [ + "ClusteringMetadata", + "HierarchicalClusteringResult", + "HierarchicalFitJob", + "LinkageMethod", + "Metric", +] + class LinkageMethod(str, Enum): """Hierarchical clustering linkage methods (scipy.cluster.hierarchy).""" @@ -64,10 +72,9 @@ class HierarchicalClusteringResult(BaseModel): `linkage` is the scipy linkage matrix with shape (N-1, 4); pass it directly to `scipy.cluster.hierarchy.dendrogram` or `fcluster`. - `sequences` is filled by `HierarchicalClusteringFuture._get` after the API fetch. - Note: `linkage` is a numpy array, so this model is not JSON-serializable via - `model_dump_json()` (use `linkage.tolist()` first if you need to serialize). + `linkage` is a numpy array, so `model_dump_json()` will not serialize this + model; convert it with `linkage.tolist()` first. """ n_leaves: int diff --git a/openprotein/codecs/__init__.py b/openprotein/codecs/__init__.py new file mode 100644 index 0000000..870c7f1 --- /dev/null +++ b/openprotein/codecs/__init__.py @@ -0,0 +1,55 @@ +"""Codecs for stored result files. + +A ``Codec`` is looked up by its immutable ``name`` with ``get``. The built-ins +are registered at import. +""" + +from __future__ import annotations + +from ._text import fasta_utf8_v1, json_utf8_v1, mmcif_utf8_v1 +from .codec import Codec +from .msa import MSA, MSARecord, msa_parquet_v1 +from .ndarray import ndarray_v1 +from .prompt import InvalidPrompt, PromptComplex, PromptReplicate, prompt_npz_v1 + +_REGISTRY: dict[str, Codec] = {} + + +def _register(codec: Codec) -> None: + """Add ``codec`` under its name; a name is bound to one codec for good.""" + existing = _REGISTRY.get(codec.name) + if existing is not None and existing is not codec: + raise ValueError(f"codec {codec.name!r} is already registered") + _REGISTRY[codec.name] = codec + + +def get(name: str) -> Codec | None: + return _REGISTRY.get(name) + + +for _builtin in ( + ndarray_v1, + mmcif_utf8_v1, + fasta_utf8_v1, + json_utf8_v1, + msa_parquet_v1, + prompt_npz_v1, +): + _register(_builtin) +del _builtin + +__all__ = [ + "MSA", + "Codec", + "InvalidPrompt", + "MSARecord", + "PromptComplex", + "PromptReplicate", + "fasta_utf8_v1", + "get", + "json_utf8_v1", + "mmcif_utf8_v1", + "msa_parquet_v1", + "ndarray_v1", + "prompt_npz_v1", +] diff --git a/openprotein/codecs/_text.py b/openprotein/codecs/_text.py new file mode 100644 index 0000000..43b4b13 --- /dev/null +++ b/openprotein/codecs/_text.py @@ -0,0 +1,32 @@ +"""UTF-8 text codecs: ``mmcif-utf8-v1``, ``fasta-utf8-v1`` and ``json-utf8-v1``.""" + +from __future__ import annotations + +import json +from typing import Any + +from .codec import Codec + + +def encode(value: str) -> bytes: + return value.encode("utf-8") + + +def decode(data: bytes) -> str: + return data.decode("utf-8") + + +mmcif_utf8_v1 = Codec(name="mmcif-utf8-v1", encode=encode, decode=decode) +fasta_utf8_v1 = Codec(name="fasta-utf8-v1", encode=encode, decode=decode) + + +def encode_json(value: Any) -> bytes: + """Compact JSON; NaN and infinities raise ``ValueError``.""" + return json.dumps(value, allow_nan=False, separators=(",", ":")).encode("utf-8") + + +def decode_json(data: bytes) -> Any: + return json.loads(data.decode("utf-8")) + + +json_utf8_v1 = Codec(name="json-utf8-v1", encode=encode_json, decode=decode_json) diff --git a/openprotein/codecs/codec.py b/openprotein/codecs/codec.py new file mode 100644 index 0000000..79999d5 --- /dev/null +++ b/openprotein/codecs/codec.py @@ -0,0 +1,22 @@ +"""The ``Codec`` record: a named, stable mapping between values and bytes.""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any + +__all__ = ["Codec"] + + +@dataclass(frozen=True) +class Codec: + """Encode a value to bytes and decode it back. + + ``name`` identifies the on-disk format. Names are immutable and + append-only: a format change is a new name. + """ + + name: str + encode: Callable[[Any], bytes] + decode: Callable[[bytes], Any] diff --git a/openprotein/codecs/msa.py b/openprotein/codecs/msa.py new file mode 100644 index 0000000..18792e1 --- /dev/null +++ b/openprotein/codecs/msa.py @@ -0,0 +1,193 @@ +"""The MSA model and the ``msa-parquet-v1`` codec: ``MSA`` <-> canonical Parquet. + +One row per sequence record; MSA-level metadata is stored in the Parquet +file-level (footer) key/value metadata so it can be read without scanning the +row groups. + +Stockholm annotations are preserved: per-sequence ``#=GS`` / ``#=GR`` ride in +optional ``gs`` / ``gr`` JSON columns, and alignment-level ``#=GF`` / ``#=GC`` in +the footer. All are written only when present, so a3m/fasta/csv blobs keep the +plain ``name`` / ``sequence`` schema. + +``MSA.chain_copies`` rides in an optional ``chain_copies`` JSON-list footer key +(schema 1.2), written only when the MSA carries it; a schema 1.1 file has no such +key and reads back with ``chain_copies`` ``None``. + +pyarrow is imported on first use; install it with ``openprotein-python[msa]``. +""" + +from __future__ import annotations + +import io +import json +from dataclasses import dataclass +from typing import Any + +from .codec import Codec + +__all__ = ["MSA", "SCHEMA_VERSION", "MSARecord", "decode", "encode", "msa_parquet_v1"] + + +SCHEMA_VERSION = "1.2" + + +@dataclass(slots=True) +class MSARecord: + """One aligned sequence in an MSA. + + ``name`` is the record's header stored **verbatim** — the entire string after + ``>`` exactly as uploaded, with its original whitespace (spaces or tabs) + preserved. It is an opaque label; we never split it into id/description, so + headers round-trip byte-for-byte. + + ``sequence`` preserves case: uppercase / ``-`` are match columns, lowercase + are insert residues (a3m convention). + + ``annotations`` / ``column_annotations`` carry this record's own metadata + (``None`` for formats that have no such concept): ``annotations`` is an ordered + list of ``(feature, value)`` (Stockholm ``#=GS``); ``column_annotations`` maps + ``feature -> per-column string`` (Stockholm ``#=GR``, e.g. ``PP``, ``SS``), one + character per alignment column. + """ + + name: str + sequence: str + annotations: list[tuple[str, str]] | None = None + column_annotations: dict[str, str] | None = None + + +@dataclass(slots=True) +class MSA: + """An MSA as parsed from any supported format. + + ``annotations`` / ``column_annotations`` describe the alignment as a whole + rather than any one record (``None`` when the file carried none): + ``annotations`` is an ordered list of ``(feature, value)`` (Stockholm ``#=GF``, + and the ``# `` comment lines the FASTA-family codecs read); + ``column_annotations`` maps ``feature -> per-column string`` (Stockholm + ``#=GC``, e.g. ``RF``, ``SS_cons``). + + The per-record counterparts live on ``MSARecord`` under the same two names. + + ``chain_copies`` is a complex's copy count per chain of the query row, in query + order (``None`` when the source named no more than one copy in total). + """ + + records: list[MSARecord] + source_format: str + num_match_columns: int + annotations: list[tuple[str, str]] | None = None + column_annotations: dict[str, str] | None = None + chain_copies: list[int] | None = None + + @property + def num_sequences(self) -> int: + """Number of sequence records.""" + return len(self.records) + + @property + def has_insertions(self) -> bool: + """True if any record carries lowercase insert residues.""" + return any( + char.islower() for record in self.records for char in record.sequence + ) + + +def _pyarrow() -> tuple[Any, Any]: + try: + import pyarrow as pa + import pyarrow.parquet as pq + except ImportError as exc: + raise ImportError( + "msa-parquet-v1 requires pyarrow; install openprotein-python[msa]" + ) from exc + return pa, pq + + +def encode(msa: MSA) -> bytes: + """Serialize an ``MSA`` to Parquet bytes.""" + pa, pq = _pyarrow() + columns = { + "name": pa.array([r.name for r in msa.records], type=pa.string()), + "sequence": pa.array([r.sequence for r in msa.records], type=pa.string()), + } + # Per-record annotations, only added when any record carries them. Keys use + # the Stockholm short names (gs/gr/gf/gc), which are part of the stored format. + if any(r.annotations for r in msa.records): + columns["gs"] = pa.array( + [json.dumps(r.annotations) if r.annotations else None for r in msa.records], + type=pa.string(), + ) + if any(r.column_annotations for r in msa.records): + columns["gr"] = pa.array( + [ + json.dumps(r.column_annotations) if r.column_annotations else None + for r in msa.records + ], + type=pa.string(), + ) + table = pa.table(columns) + + metadata = { + b"schema_version": SCHEMA_VERSION.encode(), + b"source_format": msa.source_format.encode(), + b"num_match_columns": str(msa.num_match_columns).encode(), + b"num_sequences": str(msa.num_sequences).encode(), + } + if msa.annotations: + metadata[b"gf"] = json.dumps(msa.annotations).encode() + if msa.column_annotations: + metadata[b"gc"] = json.dumps(msa.column_annotations).encode() + if msa.chain_copies is not None: + metadata[b"chain_copies"] = json.dumps(msa.chain_copies).encode() + table = table.replace_schema_metadata(metadata) + + buf = io.BytesIO() + # zstd compresses repetitive (gapped, annotation-heavy) columns far + # better than the snappy default + pq.write_table(table, buf, compression="zstd", compression_level=3) + return buf.getvalue() + + +def decode(data: bytes) -> MSA: + """Deserialize Parquet bytes back into an ``MSA``.""" + _, pq = _pyarrow() + table = pq.read_table(io.BytesIO(data)) + meta = _decode_metadata(table.schema.metadata) + cols = table.to_pydict() + gs_col = cols.get("gs") + gr_col = cols.get("gr") + + records = [] + for i in range(table.num_rows): + gs = json.loads(gs_col[i]) if gs_col and gs_col[i] else None + gr = json.loads(gr_col[i]) if gr_col and gr_col[i] else None + records.append( + MSARecord( + name=cols["name"][i], + sequence=cols["sequence"][i], + annotations=[tuple(pair) for pair in gs] if gs else None, + column_annotations=gr, + ) + ) + + gf = json.loads(meta["gf"]) if "gf" in meta else None + return MSA( + records=records, + source_format=meta.get("source_format", "a3m"), + num_match_columns=int(meta.get("num_match_columns", "0")), + annotations=[tuple(pair) for pair in gf] if gf else None, + column_annotations=json.loads(meta["gc"]) if "gc" in meta else None, + chain_copies=json.loads(meta["chain_copies"]) + if "chain_copies" in meta + else None, + ) + + +def _decode_metadata(metadata: dict[bytes, bytes] | None) -> dict[str, str]: + if not metadata: + return {} + return {k.decode(): v.decode() for k, v in metadata.items()} + + +msa_parquet_v1 = Codec(name="msa-parquet-v1", encode=encode, decode=decode) diff --git a/openprotein/codecs/ndarray.py b/openprotein/codecs/ndarray.py new file mode 100644 index 0000000..a7d33b7 --- /dev/null +++ b/openprotein/codecs/ndarray.py @@ -0,0 +1,34 @@ +"""The ``ndarray-v1`` codec: a numeric numpy array as ``.npy`` bytes.""" + +from __future__ import annotations + +import io + +import numpy as np + +from .codec import Codec + +__all__ = ["decode", "encode", "ndarray_v1"] + + +def encode(value: np.ndarray) -> bytes: + buf = io.BytesIO() + np.save(buf, value, allow_pickle=False) + return buf.getvalue() + + +def decode(data: bytes) -> np.ndarray: + source = io.BytesIO(data) + value = np.load(source, allow_pickle=False) + if ( + not isinstance(value, np.ndarray) + or value.dtype.hasobject + or value.dtype.kind not in "iufcb" + ): + raise ValueError("ndarray artifact must contain a numeric array") + if source.read(1): + raise ValueError("ndarray artifact contains trailing bytes") + return value + + +ndarray_v1 = Codec(name="ndarray-v1", encode=encode, decode=decode) diff --git a/openprotein/codecs/prompt.py b/openprotein/codecs/prompt.py new file mode 100644 index 0000000..d356095 --- /dev/null +++ b/openprotein/codecs/prompt.py @@ -0,0 +1,226 @@ +"""The ``prompt-npz-v1`` codec: one file per replicate, a one-context ``prompt.npz``. + +``context_0_sequence`` is every complex's ``:``-joined sequence concatenated +(uint8 ASCII); ``context_0_seqlens`` is each complex's length, so the +concatenation splits back apart unambiguously. ``context_0_coordinates`` is +written when at least one complex carries real coordinates, NaN-filled for +any complex that doesn't; ``context_0_plddt`` is written alongside it, +NaN-filled wherever a complex carries no pLDDT of its own. +``context_0_names`` is written when at least one complex has a name: one +string per complex, empty for a complex without one. +""" + +from __future__ import annotations + +import io +from collections.abc import Sequence +from dataclasses import dataclass +from zipfile import BadZipFile + +import numpy as np + +from .codec import Codec + +__all__ = [ + "InvalidPrompt", + "PromptComplex", + "PromptReplicate", + "decode", + "encode", + "prompt_npz_v1", +] + + +class InvalidPrompt(ValueError): + """Raised when a prompt replicate or its ``prompt-npz-v1`` bytes are malformed.""" + + +@dataclass(slots=True, eq=False) +class PromptComplex: + """One complex of a replicate: its chains joined by ``:`` in ``sequence``. + + ``coordinates``, when given, is a per-residue backbone array whose + leading axis has length ``len(sequence)`` (the ``:`` delimiter positions + carry NaN rows); ``plddt``, when given, is a matching 1-D array. Either + may be absent independently of the other. ``name`` is the complex's record + name, such as the accession of the MSA row it was sampled from. + """ + + sequence: str + coordinates: np.ndarray | None = None + plddt: np.ndarray | None = None + name: str | None = None + + +@dataclass(slots=True, eq=False) +class PromptReplicate: + """One replicate: its complexes, concatenated in this order at rest.""" + + complexes: list[PromptComplex] + + +def encode(replicate: PromptReplicate) -> bytes: + """Render one replicate to ``prompt-npz-v1`` bytes. + + Raises + ------ + InvalidPrompt + If the replicate has no complexes, a sequence is not ASCII, a + ``coordinates``/``plddt`` array's length does not match its + complex's sequence length, or ``coordinates`` or ``plddt`` arrays + across complexes disagree on trailing shape. + """ + complexes = replicate.complexes + if not complexes: + raise InvalidPrompt("a prompt replicate needs at least one complex") + + sequence_arrays = [] + seqlens = [] + for complex_ in complexes: + try: + encoded = complex_.sequence.encode("ascii") + except UnicodeEncodeError as exc: + raise InvalidPrompt(f"non-ASCII sequence: {complex_.sequence!r}") from exc + sequence_arrays.append(np.frombuffer(encoded, dtype=np.uint8)) + seqlens.append(len(encoded)) + if complex_.coordinates is not None and len(complex_.coordinates) != len( + encoded + ): + raise InvalidPrompt( + f"coordinates length {len(complex_.coordinates)} does not match " + f"sequence length {len(encoded)}" + ) + if complex_.plddt is not None and len(complex_.plddt) != len(encoded): + raise InvalidPrompt( + f"plddt length {len(complex_.plddt)} does not match sequence " + f"length {len(encoded)}" + ) + + files: dict[str, np.ndarray] = { + "context_0_sequence": np.concatenate(sequence_arrays), + "context_0_seqlens": np.array(seqlens, dtype=np.int64), + } + coordinates = _stack_optional(complexes, seqlens, "coordinates") + if coordinates is not None and np.isnan(coordinates).all(): + coordinates = None + plddt = _stack_optional(complexes, seqlens, "plddt") + if plddt is not None and np.isnan(plddt).all(): + plddt = None + if coordinates is not None: + files["context_0_coordinates"] = coordinates + if plddt is None: + plddt = np.full(len(coordinates), np.nan, dtype=np.float32) + if plddt is not None: + files["context_0_plddt"] = plddt + names = [complex_.name for complex_ in complexes] + if any(name is not None for name in names): + files["context_0_names"] = np.array( + [name or "" for name in names], dtype=np.str_ + ) + + buf = io.BytesIO() + np.savez_compressed(buf, allow_pickle=False, **files) + return buf.getvalue() + + +def _stack_optional( + complexes: Sequence[PromptComplex], seqlens: list[int], field: str +) -> np.ndarray | None: + present = [getattr(complex_, field) for complex_ in complexes] + if all(value is None for value in present): + return None + trailing_shape = next( + np.asarray(value).shape[1:] for value in present if value is not None + ) + parts = [ + np.full((length, *trailing_shape), np.nan, dtype=np.float32) + if value is None + else np.asarray(value, dtype=np.float32) + for value, length in zip(present, seqlens, strict=True) + ] + try: + return np.concatenate(parts) + except ValueError as exc: + raise InvalidPrompt( + f"inconsistent {field} shape across complexes: {exc}" + ) from exc + + +def decode(data: bytes) -> PromptReplicate: + """Parse ``prompt-npz-v1`` bytes back into one replicate's complexes. + + Splits ``context_0_sequence`` by the cumulative ``context_0_seqlens``, + matching Gen 1 PoET's per-context decode exactly, so a file this codec + writes round-trips through either reader. + + Raises + ------ + InvalidPrompt + If the bytes are not a well-formed ``prompt-npz-v1`` file, a + required key is missing, the sequence is not uint8, seqlens is not a + 1-D integer array, the sequence, coordinates or pLDDT lengths are + inconsistent, the names are not one string per complex, or a sequence + is not ASCII. + """ + try: + with np.load(io.BytesIO(data), allow_pickle=False) as npz: + sequence = npz["context_0_sequence"] + seqlens = npz["context_0_seqlens"] + coordinates = npz.get("context_0_coordinates") + plddt = npz.get("context_0_plddt") + names = npz.get("context_0_names") + except (BadZipFile, KeyError, ValueError) as exc: + raise InvalidPrompt(f"malformed prompt-npz-v1 bytes: {exc}") from exc + + if sequence.dtype != np.uint8: + raise InvalidPrompt("prompt sequence must be uint8") + if seqlens.ndim != 1 or seqlens.dtype.kind not in "iu": + raise InvalidPrompt("prompt seqlens must be a 1-D integer array") + if len(sequence) != seqlens.sum(): + raise InvalidPrompt("sequence length does not match the sum of seqlens") + if coordinates is not None and len(coordinates) != len(sequence): + raise InvalidPrompt("coordinates length does not match the sequence length") + if plddt is not None and len(plddt) != len(sequence): + raise InvalidPrompt("plddt length does not match the sequence length") + if names is not None and ( + names.ndim != 1 or names.dtype.kind != "U" or len(names) != len(seqlens) + ): + raise InvalidPrompt("prompt names must be one string per complex") + + breaks = np.cumsum(seqlens)[:-1] + sequence_splits = np.split(sequence, breaks) + coordinate_splits = ( + np.split(coordinates, breaks) + if coordinates is not None + else [None] * len(seqlens) + ) + plddt_splits = ( + np.split(plddt, breaks) if plddt is not None else [None] * len(seqlens) + ) + name_list = ( + [str(name) or None for name in names] + if names is not None + else [None] * len(seqlens) + ) + try: + complexes = [ + PromptComplex( + sequence=seq.tobytes().decode("ascii"), + coordinates=coord, + plddt=p, + name=name, + ) + for seq, coord, p, name in zip( + sequence_splits, coordinate_splits, plddt_splits, name_list, strict=True + ) + ] + except UnicodeDecodeError as exc: + raise InvalidPrompt(f"non-ASCII sequence bytes: {exc}") from exc + except ValueError as exc: + raise InvalidPrompt( + f"seqlens does not match the encoded complexes: {exc}" + ) from exc + return PromptReplicate(complexes=complexes) + + +prompt_npz_v1 = Codec(name="prompt-npz-v1", encode=encode, decode=decode) diff --git a/openprotein/common/__init__.py b/openprotein/common/__init__.py index e2c010a..97b04a2 100644 --- a/openprotein/common/__init__.py +++ b/openprotein/common/__init__.py @@ -3,3 +3,13 @@ from .features import Feature, FeatureType from .model_metadata import ModelDescription, ModelMetadata, TokenInfo from .reduction import Reduction, ReductionType + +__all__ = [ + "Feature", + "FeatureType", + "ModelDescription", + "ModelMetadata", + "Reduction", + "ReductionType", + "TokenInfo", +] diff --git a/openprotein/common/features.py b/openprotein/common/features.py index 178ce77..903d082 100644 --- a/openprotein/common/features.py +++ b/openprotein/common/features.py @@ -3,13 +3,12 @@ from enum import Enum from typing import Literal +__all__ = ["Feature", "FeatureType"] -class FeatureType(str, Enum): +class FeatureType(str, Enum): PLM = "PLM" SVD = "SVD" -# NOTE: only works with python 3.12+ -# Feature = Literal[*tuple([r.value for r in FeatureType])] Feature = Literal["PLM", "SVD"] diff --git a/openprotein/common/model_metadata.py b/openprotein/common/model_metadata.py index 6470696..64d7ea8 100644 --- a/openprotein/common/model_metadata.py +++ b/openprotein/common/model_metadata.py @@ -2,6 +2,8 @@ from pydantic import BaseModel, Field +__all__ = ["ModelDescription", "ModelMetadata", "TokenInfo"] + class ModelDescription(BaseModel): """Description of available protein embedding models.""" diff --git a/openprotein/common/reduction.py b/openprotein/common/reduction.py index 04e9c9d..080ab11 100644 --- a/openprotein/common/reduction.py +++ b/openprotein/common/reduction.py @@ -3,6 +3,8 @@ from enum import Enum from typing import Literal +__all__ = ["Reduction", "ReductionType"] + class ReductionType(str, Enum): """ @@ -17,6 +19,4 @@ class ReductionType(str, Enum): SUM = "SUM" -# NOTE: only works with python 3.12+ -# Reduction = Literal[*tuple([r.value for r in ReductionType])] Reduction = Literal["MEAN", "SUM"] diff --git a/openprotein/common/residue_contants.py b/openprotein/common/residue_constants.py similarity index 97% rename from openprotein/common/residue_contants.py rename to openprotein/common/residue_constants.py index 784395b..e568f8d 100644 --- a/openprotein/common/residue_contants.py +++ b/openprotein/common/residue_constants.py @@ -1,3 +1,6 @@ +__all__ = ["residue_atoms", "restype_1to3"] + + # fmt: off residue_atoms = { "ALA": ["C", "CA", "CB", "N", "O"], diff --git a/openprotein/config.py b/openprotein/config.py index 839e698..ad1c791 100644 --- a/openprotein/config.py +++ b/openprotein/config.py @@ -1,3 +1,14 @@ +__all__ = [ + "BASE_PAGE_SIZE", + "EMBEDDING_PAGE_SIZE", + "MAX_CONCURRENT_WORKERS", + "POET_MAX_PAGE_SIZE", + "POET_PAGE_SIZE", + "POLLING_INTERVAL", + "POLLING_TIMEOUT", +] + + POLLING_INTERVAL = 5 POLLING_TIMEOUT = 900 diff --git a/openprotein/csv.py b/openprotein/csv.py index fba7ab0..f196790 100644 --- a/openprotein/csv.py +++ b/openprotein/csv.py @@ -1,10 +1,27 @@ import csv from typing import Iterator +__all__ = ["ensure_str_lines", "parse_stream"] + def ensure_str_lines( lines: Iterator[str] | Iterator[bytes], encoding="utf-8" ) -> Iterator[str]: + """ + Decode bytes lines, passing str lines through unchanged. + + Parameters + ---------- + lines : Iterator[str] | Iterator[bytes] + Lines to normalize. A mix of str and bytes lines is permitted. + encoding : str, optional + Encoding used to decode bytes lines. Defaults to "utf-8". + + Yields + ------ + str + Each line as text. + """ for line in lines: if isinstance(line, bytes): yield line.decode(encoding) @@ -14,17 +31,17 @@ def ensure_str_lines( def parse_stream(lines: Iterator[str] | Iterator[bytes]) -> Iterator[list[str]]: """ - Returns a CSV reader from a requests.Response object. + Parse lines of CSV text, yielding one list of fields per row. Parameters ---------- - response : requests.Response - The response object to parse. + lines : Iterator[str] | Iterator[bytes] + Lines of CSV text. Bytes lines are decoded as UTF-8. - Returns - ------- - csv.reader - A csv reader object for the response. + Yields + ------ + list[str] + The fields of one CSV row. """ reader = csv.reader(ensure_str_lines(lines)) for row in reader: diff --git a/openprotein/data/__init__.py b/openprotein/data/__init__.py index ad01b87..f28fe67 100644 --- a/openprotein/data/__init__.py +++ b/openprotein/data/__init__.py @@ -4,6 +4,21 @@ isort:skip_file """ -from .schemas import AssayDataPage, AssayDataRow, AssayMetadata -from .assaydataset import AssayDataset +from .assaydataset import Assay, AssayDataset from .data import DataAPI +from .msa import MSA, MSAFormat, MSAMetadata +from .prompts import Prompt +from .schemas import AssayDataPage, AssayDataRow, AssayMetadata + +__all__ = [ + "MSA", + "Assay", + "AssayDataPage", + "AssayDataRow", + "AssayDataset", + "AssayMetadata", + "DataAPI", + "MSAFormat", + "MSAMetadata", + "Prompt", +] diff --git a/openprotein/data/_reads.py b/openprotein/data/_reads.py new file mode 100644 index 0000000..af57ed9 --- /dev/null +++ b/openprotein/data/_reads.py @@ -0,0 +1,24 @@ +"""Reads of stored data rows.""" + +import copy + +from requests import Response + +from openprotein.base import APISession +from openprotein.errors import HTTPError + + +def read(session: APISession, path: str, **kwargs) -> Response: + """GET a stored row and return the response. + + Errors are raised as the session raises them, except that a 425 is raised + as a 404. + """ + try: + return session.get(path, **kwargs) + except HTTPError as error: + if error.status_code != 425: + raise + response = copy.copy(error.response) + response.status_code = 404 + raise HTTPError(response) from None diff --git a/openprotein/data/_resource.py b/openprotein/data/_resource.py new file mode 100644 index 0000000..01b2ff3 --- /dev/null +++ b/openprotein/data/_resource.py @@ -0,0 +1,307 @@ +"""Behaviour shared by the stored-data handles.""" + +from __future__ import annotations + +from datetime import datetime +from typing import TYPE_CHECKING, Any, ClassVar, Generic, TypeVar, cast + +from typing_extensions import Self + +from openprotein import config +from openprotein.base import APISession +from openprotein.errors import ( + HTTPError, + JobFailedException, + JobOutputsNotReady, + NoJobError, +) +from openprotein.jobs.schemas import JobStatus + +if TYPE_CHECKING: + from openprotein.jobs.schemas import Job + +M = TypeVar("M") + + +class _Resource(Generic[M]): + """A stored row: its metadata, and the job that produces it. + + ``session.data`` hands out each class bound to its session. ``id=`` alone + loads a row. A row answers ``Future``'s calls: ``done``, ``wait_until_done``, + ``get`` and ``wait`` return once it is ready, and ``get`` and ``wait`` + return the row itself. A row no job made, such as an upload, is always + ready, and its job fields raise `NoJobError`. + """ + + _session: ClassVar[APISession | None] = None + _unbound: ClassVar[type | None] = None + _job: Job | None = None + # The metadata came from the job, as the row couldn't be read; the job's + # status says nothing about whether the row exists. + _from_job_only: bool = False + + session: APISession + metadata: M + + def __init__( + self, + session: APISession | None = None, + metadata: M | None = None, + *, + id: str | None = None, + ): + if id is not None: + if session is not None or metadata is not None: + raise TypeError("pass id alone to load a stored row") + session = self._bound() + metadata = self._load(session, id) + elif session is None or metadata is None: + raise TypeError( + f"{type(self).__name__} takes id=, or a session and its metadata" + ) + self.session = session + self.metadata = metadata + + @classmethod + def _bind(cls, session: APISession) -> type[Self]: + """This class, creating, listing and loading through ``session``.""" + attrs = { + "_session": session, + "_unbound": cls._unbound or cls, + "__module__": cls.__module__, + "__qualname__": cls.__qualname__, + "__doc__": cls.__doc__, + } + return cast("type[Self]", type(cls.__name__, (cls,), attrs)) + + @classmethod + def _for(cls, session: APISession) -> type[Self]: + """``session.data``'s own class, else this class bound to ``session``.""" + from openprotein.data.data import DataAPI + + data = getattr(session, "data", None) + if isinstance(data, DataAPI): + return getattr(data, cls.__name__) + return cls._bind(session) + + @classmethod + def _bound(cls) -> APISession: + if cls._session is None: + raise TypeError( + f"{cls.__name__} needs a session; use session.data.{cls.__name__}" + ) + return cls._session + + @classmethod + def _load(cls, session: APISession, id: str) -> M: + """Read one row's metadata by id.""" + raise NotImplementedError + + def __reduce__(self) -> tuple[Any, ...]: + return (_restore, (self._unbound or type(self), vars(self).copy())) + + def __str__(self) -> str: + return str(self.metadata) + + def __repr__(self) -> str: + return repr(self.metadata) + + def __bool__(self) -> bool: + return True + + @property + def id(self) -> str: + raise NotImplementedError + + @property + def status(self) -> JobStatus: + raise NotImplementedError + + @property + def job_id(self) -> str | None: + raise NotImplementedError + + @property + def job(self) -> Job | None: + """The job that made the row, read on first use; ``None`` if no job did.""" + job_id = self.job_id + if job_id is None: + return None + if self._job is None: + from openprotein.jobs import api + from openprotein.jobs.schemas import Job + + self._job = Job.create(api.job_get(self.session, job_id)) + return self._job + + def _job_if_present(self) -> Job | None: + """The row's job, or ``None`` if no job made it or its job is gone.""" + try: + return self.job + except HTTPError as error: + if error.status_code in (404, 410): + return None + raise + + def _job_field(self, name: str) -> Any: + job = self.job + if job is None: + raise NoJobError( + f"{type(self).__name__} {self.id} was not made by a job, " + f"so it has no {name}" + ) + return getattr(job, name) + + @property + def job_type(self) -> str: + """The type of the job that made the row.""" + return self._job_field("job_type") + + @property + def created_date(self) -> datetime: + """When the job that made the row was created.""" + return self._job_field("created_date") + + @property + def start_date(self) -> datetime | None: + """When the job that made the row started.""" + return self._job_field("start_date") + + @property + def end_date(self) -> datetime | None: + """When the job that made the row finished.""" + return self._job_field("end_date") + + def _forget(self) -> None: + """Drop content read earlier.""" + + def refresh(self) -> Self: + """Read the metadata again, and drop the job and content read earlier.""" + self.metadata = self._load(self.session, self.id) + self._from_job_only = False + self._job = None + self._forget() + return self + + def done(self) -> bool: + """Whether the row is ready, failed or canceled, as last read.""" + return self.status.done() + + def wait_until_done( + self, + interval: float = config.POLLING_INTERVAL, + timeout: int | None = None, + verbose: bool = False, + ) -> bool: + """Wait for the job that makes the row to finish, then read the row again. + + A row that is already done returns at once. A failure does not raise; + ``get`` raises it. + + Parameters + ---------- + interval : float, optional + Seconds between polls. Defaults to `config.POLLING_INTERVAL`. + timeout : int, optional + Seconds to wait before raising. Defaults to no limit. + verbose : bool, optional + Show a progress bar. Defaults to False. + + Returns + ------- + bool + Whether the row is done. + + Raises + ------ + TimeoutException + If the wait exceeds ``timeout``. + """ + if self.done(): + return True + job = self._job_if_present() + if job is not None: + from openprotein.jobs.futures import Future + + tracker: Future[Any] = Future(self.session, job) + if not tracker.done(): + tracker.wait_until_done( + interval=interval, timeout=timeout, verbose=verbose + ) + job = tracker.job + self.refresh() + self._job = job + return self.done() + + def get(self, verbose: bool = False, **kwargs: Any) -> Self: + """The row, once it is ready. + + Raises + ------ + JobOutputsNotReady + If the row isn't ready yet. + JobFailedException + If the job that makes the row failed or was canceled. + """ + if not self.done() or self._from_job_only: + self.refresh() + failure = None + if self.status is JobStatus.FAILURE: + job = self._job_if_present() + failure = None if job is None else job.failure_message + self._check(failure) + return self + + def wait( + self, + interval: float = config.POLLING_INTERVAL, + timeout: int | None = None, + verbose: bool = False, + ) -> Self: + """Wait until the row is ready and return it, as ``get`` does. + + Parameters + ---------- + interval : float, optional + Seconds between polls. Defaults to `config.POLLING_INTERVAL`. + timeout : int, optional + Seconds to wait before raising. Defaults to no limit. + verbose : bool, optional + Show a progress bar. Defaults to False. + + Raises + ------ + TimeoutException + If the wait exceeds ``timeout``. + JobFailedException + If the job that makes the row failed or was canceled. + JobOutputsNotReady + If the job finished but the row isn't ready yet. + """ + self.wait_until_done(interval=interval, timeout=timeout, verbose=verbose) + return self.get() + + def _require_ready(self) -> None: + """Raise unless the row's content can be read.""" + if self.status is not JobStatus.SUCCESS or self._from_job_only: + self.refresh() + self._check() + + def _check(self, failure: str | None = None) -> None: + status = self.status + if status is JobStatus.CANCELED: + raise JobFailedException(self.job_id or self.id, "the job was canceled") + if status is JobStatus.FAILURE: + raise JobFailedException(self.job_id or self.id, failure) + if status is not JobStatus.SUCCESS: + raise JobOutputsNotReady( + f"{type(self).__name__} {self.id} is {status.value}; " + "wait() returns it once it is ready" + ) + + +def _restore(cls: type, state: dict[str, Any]) -> Any: + """A handle of ``cls`` holding ``state``, as pickled.""" + handle = object.__new__(cls) + vars(handle).update(state) + return handle diff --git a/openprotein/data/api.py b/openprotein/data/api.py index e83ebb2..372ca82 100644 --- a/openprotein/data/api.py +++ b/openprotein/data/api.py @@ -1,3 +1,6 @@ +import json +from collections.abc import Sequence + from pydantic import TypeAdapter from openprotein.base import APISession @@ -5,6 +8,16 @@ from .schemas import AssayDataPage, AssayMetadata +__all__ = [ + "assaydata_delete", + "assaydata_list", + "assaydata_page_get", + "assaydata_post", + "assaydata_put", + "get_assay_metadata", + "list_models", +] + def list_models(session: APISession, assay_id: str) -> list: """ @@ -32,6 +45,7 @@ def assaydata_post( assay_file, assay_name: str, assay_description: str | None = "", + metadata_columns: Sequence[str] | None = None, ) -> AssayMetadata: """ Post assay data. @@ -46,6 +60,8 @@ def assaydata_post( Name of the assay. assay_description : str, optional Description of the assay, by default ''. + metadata_columns : Sequence[str], optional + Columns stored as free-text metadata per row instead of measurements. Returns ------- @@ -56,6 +72,10 @@ def assaydata_post( files = {"assay_data": assay_file} data = {"assay_name": assay_name, "assay_description": assay_description} + if isinstance(metadata_columns, str): + raise TypeError("metadata_columns must be a list of column names") + if metadata_columns is not None: + data["metadata_columns"] = json.dumps(list(metadata_columns)) response = session.post(endpoint, files=files, data=data) if response.status_code == 200: @@ -173,13 +193,27 @@ def assaydata_put( if assay_description is not None: data["assay_description"] = assay_description - response = session.put(endpoint, data=data) + response = session.put(endpoint, json=data) if response.status_code == 200: return TypeAdapter(AssayMetadata).validate_python(response.json()) else: raise APIError(f"Unable to update assay data: {response.text}") +def assaydata_delete(session: APISession, assay_id: str) -> None: + """ + Delete an assay. + + Parameters + ---------- + session : APISession + Session object for API communication. + assay_id : str + Id of the assay. + """ + session.delete(f"v1/assaydata/{assay_id}") + + def assaydata_page_get( session: APISession, assay_id: str, @@ -187,6 +221,7 @@ def assaydata_page_get( page_offset: int = 0, page_size: int = 1000, data_format: str = "wide", + include_metadata: bool = False, ) -> AssayDataPage: """ Get a page of assay data. @@ -205,6 +240,8 @@ def assaydata_page_get( Size of the page, by default 1000. data_format : str, optional data_format of the data, by default 'wide'. + include_metadata : bool, optional + Include each row's metadata values, by default False. Wide format only. Returns ------- @@ -221,6 +258,8 @@ def assaydata_page_get( params = {"page_offset": page_offset, "page_size": page_size, "format": data_format} if measurement_name is not None: params["measurement_name"] = measurement_name + if include_metadata: + params["include_metadata"] = True response = session.get(endpoint, params=params) if response.status_code == 200: diff --git a/openprotein/data/assaydataset.py b/openprotein/data/assaydataset.py index 3310d8e..a1d2fb3 100644 --- a/openprotein/data/assaydataset.py +++ b/openprotein/data/assaydataset.py @@ -1,38 +1,112 @@ +"""Assays (``session.data.Assay``). + +>>> assay = session.data.Assay.create(table, "stability") +>>> assay = session.data.Assay(id=assay.id) +>>> first_rows = assay.get_slice(0, 10) +""" + +from __future__ import annotations + +import builtins +import io +from collections.abc import Sequence +from datetime import datetime + import pandas as pd +from typing_extensions import Self from openprotein import config +from openprotein._deprecation import warn_deprecated from openprotein.base import APISession from openprotein.errors import APIError +from openprotein.jobs.schemas import JobStatus from . import api -from .schemas import AssayDataPage, AssayMetadata - - -class AssayDataset: - """Assay dataset which contains your sequences and measurements which can be used for training predictors.""" - - def __init__(self, session: APISession, metadata: AssayMetadata): +from ._resource import _Resource +from .schemas import AssayMetadata + +__all__ = ["Assay", "AssayDataset"] + +_LIST_PAGE = 1000 + + +class Assay(_Resource[AssayMetadata]): + """An assay: your sequences and their measurements, which predictors train on. + + ``session.data.Assay.create`` uploads one, ``session.data.Assay.list`` lists + the caller's and ``session.data.Assay(id=...)`` loads one. + """ + + def __init__( + self, + session: APISession | None = None, + metadata: AssayMetadata | None = None, + *, + id: str | None = None, + ): + super().__init__(session, metadata, id=id) + self.page_size = min(config.BASE_PAGE_SIZE, 1000) + + @classmethod + def _load(cls, session: APISession, id: str) -> AssayMetadata: + return api.get_assay_metadata(session, id) + + @classmethod + def create( + cls, + table: pd.DataFrame, + name: str, + description: str | None = None, + metadata_columns: Sequence[str] | None = None, + ) -> Self: """ - init for AssayDataset. + Upload a table as an assay. Parameters ---------- - session : APISession - Session object for API communication. - metadata : AssayMetadata - Metadata object of the assay data. - """ - self.session = session - self.metadata = metadata - self.page_size = config.BASE_PAGE_SIZE - if self.page_size > 1000: - self.page_size = 1000 - - def __str__(self) -> str: - return str(self.metadata) + table : pd.DataFrame + DataFrame containing the assay data. + name : str + Name of the assay. + description : str, optional + Description of the assay, by default None. + metadata_columns : Sequence[str], optional + Columns of free text, such as notes, kept per row as metadata. + They are not measurements and cannot be used to train models. - def __repr__(self) -> str: - return repr(self.metadata) + Returns + ------- + Assay + The stored assay. + """ + session = cls._bound() + stream = io.BytesIO() + table.to_csv(stream, index=False) + stream.seek(0) + metadata = api.assaydata_post( + session, + stream, + name, + assay_description=description, + metadata_columns=metadata_columns, + ) + return cls(session, metadata) + + @classmethod + def list( + cls, limit: int | None = None, offset: int | None = None + ) -> builtins.list[Self]: + """The caller's assays from every page, at most ``limit``, starting at ``offset``.""" + session = cls._bound() + start = offset or 0 + assays: builtins.list[Self] = [] + while limit is None or len(assays) < limit: + size = _LIST_PAGE if limit is None else min(_LIST_PAGE, limit - len(assays)) + page = api.assaydata_list(session, limit=size, offset=start + len(assays)) + assays.extend(cls(session, metadata) for metadata in page) + if len(page) < size: + break + return assays @property def id(self): @@ -46,10 +120,28 @@ def name(self): def description(self): return self.metadata.assay_description + @property + def status(self) -> JobStatus: + """``SUCCESS`` once the dataset is ready, else the status of the job producing it.""" + return self.metadata.status + + @property + def job_id(self) -> str | None: + """The job that produces the dataset, such as an alignment; ``None`` for an upload.""" + return self.metadata.align_job_id + + @property + def created_at(self) -> datetime: + return self.metadata.created_date + @property def measurement_names(self): return self.metadata.measurement_names + @property + def metadata_names(self) -> builtins.list[str]: + return self.metadata.metadata_names or [] + @property def sequence_length(self): return self.metadata.sequence_length @@ -57,6 +149,9 @@ def sequence_length(self): def __len__(self): return self.metadata.num_rows + def __bool__(self) -> bool: + return len(self) != 0 + @property def shape(self): return (len(self), len(self.measurement_names) + 1) @@ -73,29 +168,46 @@ def list_models(self): return api.list_models(self.session, self.id) def update( - self, assay_name: str | None = None, assay_description: str | None = None - ) -> None: + self, + name: str | None = None, + description: str | None = None, + *, + assay_name: str | None = None, + assay_description: str | None = None, + ) -> Self: + """Update the name or description; only the ones given change. + + .. deprecated:: 0.18.0 + ``assay_name`` and ``assay_description``. Use ``name`` and + ``description``. """ - Update the assay metadata. - - Parameters - ---------- - assay_name : str, optional - New name of the assay, by default None. - assay_description : str, optional - New description of the assay, by default None. - - Returns - ------- - None - """ - metadata = api.assaydata_put( - self.session, - self.id, - assay_name=assay_name, - assay_description=assay_description, + if assay_name is not None or assay_description is not None: + if (name is not None and assay_name is not None) or ( + description is not None and assay_description is not None + ): + raise TypeError( + "pass name and description, without assay_name or assay_description" + ) + warn_deprecated( + "Assay.update(assay_name=, assay_description=)", + "`Assay.update(name=, description=)`", + since="0.18.0", + removed_in="0.19.0", + ) + name = assay_name if name is None else name + description = assay_description if description is None else description + updated = api.assaydata_put( + self.session, self.id, assay_name=name, assay_description=description ) - self.metadata = metadata + if updated.align_job_id is None and self.job_id is not None: + # The update's answer leaves out the job, so its status reads SUCCESS. + updated = self._load(self.session, self.id) + self.metadata = updated + return self + + def delete(self) -> None: + """Delete this assay.""" + api.assaydata_delete(self.session, self.id) def _get_all(self, verbose: bool = False) -> pd.DataFrame: """ @@ -140,10 +252,12 @@ def get_first(self) -> pd.DataFrame: for row in entries.assaydata: row = [row.mut_sequence] + row.measurement_values rows.append(row) - table = pd.DataFrame(rows, columns=["sequence"] + self.measurement_names) # type: ignore + table = pd.DataFrame(rows, columns=["sequence"] + self.measurement_names) return table - def get_slice(self, start: int, end: int) -> pd.DataFrame: + def get_slice( + self, start: int, end: int, include_metadata: bool = False + ) -> pd.DataFrame: """ Get a slice of assay data. @@ -153,6 +267,8 @@ def get_slice(self, start: int, end: int) -> pd.DataFrame: Start index of the slice. end : int End index of the slice. + include_metadata : bool, optional + Append the metadata columns after the measurements, by default False. Returns ------- @@ -161,18 +277,38 @@ def get_slice(self, start: int, end: int) -> pd.DataFrame: """ rows = [] page_size = self.page_size - # loop over the range for i in range(start, end, page_size): # the last page might be smaller than the page size current_page_size = min(page_size, end - i) entries = api.assaydata_page_get( - self.session, self.id, page_offset=i, page_size=current_page_size + self.session, + self.id, + page_offset=i, + page_size=current_page_size, + include_metadata=include_metadata, ) for row in entries.assaydata: - row = [row.mut_sequence] + row.measurement_values - rows.append(row) - - table = pd.DataFrame(rows, columns=["sequence"] + self.measurement_names) # type: ignore + values = [row.mut_sequence] + row.measurement_values + if include_metadata: + metadata = list(row.metadata_values or []) + values += metadata + [None] * ( + len(self.metadata_names) - len(metadata) + ) + rows.append(values) + + columns = ["sequence"] + self.measurement_names + if include_metadata: + columns += self.metadata_names + table = pd.DataFrame(rows, columns=columns) + if include_metadata: + # object dtype keeps a missing metadata value as None; pandas 3 infers + # its str dtype, which reads one as NaN + start = len(columns) - len(self.metadata_names) + for i, name in enumerate(self.metadata_names, start=start): + table[name] = pd.Series([row[i] for row in rows], dtype=object) return table + + +AssayDataset = Assay diff --git a/openprotein/data/data.py b/openprotein/data/data.py index 0a0a0bc..8515ede 100644 --- a/openprotein/data/data.py +++ b/openprotein/data/data.py @@ -1,27 +1,61 @@ -import io +import builtins +from collections.abc import Sequence import pandas as pd +from openprotein._deprecation import warn_deprecated from openprotein.base import APISession -from . import api +from . import assaydataset from .assaydataset import AssayDataset +from .msa import msa as stored_msa +from .prompts import prompts as stored_prompts + +__all__ = ["DataAPI"] class DataAPI: - """API interface for calling AssayData endpoints""" + """Stored data: assays, MSAs and prompts, each through its class.""" + + _assay_class = None + _msa_class = None + _prompt_class = None def __init__(self, session: APISession): self.session = session - # `list` shadows the builtin, so the return annotation is quoted to keep it - # resolving to the builtin (not this method) under PEP 649 deferred evaluation. + @property + def Assay(self) -> type[assaydataset.Assay]: + """Assays: ``Assay.create`` uploads, ``Assay.list`` lists, ``Assay(id=...)`` loads.""" + if self._assay_class is None: + self._assay_class = assaydataset.Assay._bind(self.session) + return self._assay_class + + @property + def MSA(self) -> type[stored_msa.MSA]: + """Stored MSAs: ``MSA.create`` uploads, ``MSA.list`` lists, ``MSA(id=...)`` loads.""" + if self._msa_class is None: + self._msa_class = stored_msa.MSA._bind(self.session) + return self._msa_class + + @property + def Prompt(self) -> type[stored_prompts.Prompt]: + """Stored prompts: ``Prompt.create`` uploads, ``Prompt.list`` lists, ``Prompt(id=...)`` loads.""" + if self._prompt_class is None: + self._prompt_class = stored_prompts.Prompt._bind(self.session) + return self._prompt_class + def list( self, limit: int | None = None, offset: int | None = None - ) -> "list[AssayDataset]": + ) -> builtins.list[AssayDataset]: """ - List all assay datasets. + List the caller's assays. + .. deprecated:: 0.18.0 + Use ``session.data.Assay.list``. + + Parameters + ---------- limit : int, optional Limit the number of assays to return. offset : int, optional @@ -30,17 +64,29 @@ def list( Returns ------- List[AssayDataset] - List of all assay datasets. + The assays from every page. """ - metadata = api.assaydata_list(session=self.session, limit=limit, offset=offset) - return [AssayDataset(self.session, x) for x in metadata] + warn_deprecated( + "session.data.list", + "`session.data.Assay.list`", + since="0.18.0", + removed_in="0.19.0", + ) + return builtins.list(self.Assay.list(limit=limit, offset=offset)) def create( - self, table: pd.DataFrame, name: str, description: str | None = None + self, + table: pd.DataFrame, + name: str, + description: str | None = None, + metadata_columns: Sequence[str] | None = None, ) -> AssayDataset: """ Create a new assay dataset. + .. deprecated:: 0.18.0 + Use ``session.data.Assay.create``. + Parameters ---------- table : pd.DataFrame @@ -49,26 +95,32 @@ def create( Name of the assay dataset. description : str, optional Description of the assay dataset, by default None. + metadata_columns : Sequence[str], optional + Columns of free text, such as notes, kept per row as metadata. + They are not measurements and cannot be used to train models. Returns ------- AssayDataset Created assay dataset. """ - stream = io.BytesIO() - table.to_csv(stream, index=False) - stream.seek(0) - metadata = api.assaydata_post( - self.session, stream, name, assay_description=description + warn_deprecated( + "session.data.create", + "`session.data.Assay.create`", + since="0.18.0", + removed_in="0.19.0", + ) + return self.Assay.create( + table, name, description=description, metadata_columns=metadata_columns ) - table.columns = [str(column).lower() for column in table.columns] - metadata.sequence_length = len(table["sequence"].values[0]) - return AssayDataset(self.session, metadata) def get(self, assay_id: str, verbose: bool = False) -> AssayDataset: """ Get an assay dataset by its ID. + .. deprecated:: 0.18.0 + Use ``session.data.Assay(id=...)``. + Parameters ---------- assay_id : str @@ -78,26 +130,41 @@ def get(self, assay_id: str, verbose: bool = False) -> AssayDataset: ------- AssayDataset Assay dataset with the specified ID. - - Raises - ------ - KeyError - If no assay dataset with the given ID is found. """ - return AssayDataset( - session=self.session, - metadata=api.get_assay_metadata(self.session, assay_id), + warn_deprecated( + "session.data.get", + "`session.data.Assay(id=...)`", + since="0.18.0", + removed_in="0.19.0", ) + return self.Assay(id=assay_id) - load_assay = get + def load_assay(self, assay_id: str, verbose: bool = False) -> AssayDataset: + """ + Get an assay dataset by its ID. + + .. deprecated:: 0.18.0 + Use ``session.data.Assay(id=...)``. + """ + warn_deprecated( + "session.data.load_assay", + "`session.data.Assay(id=...)`", + since="0.18.0", + removed_in="0.19.0", + ) + return self.Assay(id=assay_id) def __len__(self) -> int: """ - Get the number of assay datasets. + The number of the caller's assays. - Returns - ------- - int - Number of assay datasets. + .. deprecated:: 0.18.0 + Use ``len(session.data.Assay.list())``. """ - return len(self.list()) + warn_deprecated( + "len(session.data)", + "`len(session.data.Assay.list())`", + since="0.18.0", + removed_in="0.19.0", + ) + return len(self.Assay.list()) diff --git a/openprotein/data/msa/__init__.py b/openprotein/data/msa/__init__.py new file mode 100644 index 0000000..d136699 --- /dev/null +++ b/openprotein/data/msa/__init__.py @@ -0,0 +1,14 @@ +"""Client for accessing MSA data. + +isort:skip_file +""" + +from .msa import MSA +from .schemas import MSADownloadFormat, MSAFormat, MSAMetadata + +__all__ = [ + "MSA", + "MSADownloadFormat", + "MSAFormat", + "MSAMetadata", +] diff --git a/openprotein/data/msa/_api.py b/openprotein/data/msa/_api.py new file mode 100644 index 0000000..ab45c89 --- /dev/null +++ b/openprotein/data/msa/_api.py @@ -0,0 +1,193 @@ +from pydantic import BaseModel + +from openprotein.base import APISession +from openprotein.data._reads import read + +from .schemas import MSADownloadFormat, MSAFormat, MSAMetadata + + +class MSAPage(BaseModel): + """One page of MSA metadata.""" + + items: list[MSAMetadata] + total: int + limit: int + offset: int + + +def msa_post( + session: APISession, + file: bytes, + format: MSAFormat, + name: str | None = None, + description: str | None = None, + filename: str | None = None, +) -> MSAMetadata: + """ + Upload an MSA, declaring its ``format``. + + Parameters + ---------- + session : APISession + Session object for API communication. + file : bytes + The MSA contents to upload. + format : MSAFormat + The upload's format (one of "a2m", "a3m", "csv", "fasta", "sto"), naming its + parser. + name, description : str, optional + Human-readable metadata to store alongside the MSA. + filename : str, optional + Original filename to record; defaults to a name derived from ``format``. + + Returns + ------- + MSAMetadata + Metadata of the stored MSA. + """ + endpoint = "v1/data/msa" + data: dict = {"format": format} + if name is not None: + data["name"] = name + if description is not None: + data["description"] = description + files = {"file": (filename or f"msa.{format}", file)} + response = session.post(endpoint, data=data, files=files) + return MSAMetadata.model_validate(response.json()) + + +def msa_list( + session: APISession, + limit: int | None = None, + offset: int = 0, +) -> MSAPage: + """ + List one page of the caller's stored MSAs (metadata only). + + Parameters + ---------- + session : APISession + Session object for API communication. + limit : int, optional + Maximum number of records to return; the server pages when left unset. + offset : int + Offset into the result set. + + Returns + ------- + MSAPage + A page of MSA metadata and the total across pages. + """ + endpoint = "v1/data/msa" + params: dict = {"offset": offset} + if limit is not None: + params["limit"] = limit + response = session.get(endpoint, params=params) + return MSAPage.model_validate(response.json()) + + +def msa_get_metadata(session: APISession, msa_id: str) -> MSAMetadata: + """ + Retrieve metadata for one MSA. + + A deleted or unknown id is a 404. + + Parameters + ---------- + session : APISession + Session object for API communication. + msa_id : str + Id of the MSA. + + Returns + ------- + MSAMetadata + Metadata for the MSA. + """ + response = read(session, f"v1/data/msa/{msa_id}/metadata") + return MSAMetadata.model_validate(response.json()) + + +def msa_download( + session: APISession, msa_id: str, format: MSADownloadFormat | None = None +) -> bytes: + """ + Download a live MSA's alignment bytes, optionally converted to ``format``. + + Raises a 404 unless the MSA is live. + + Parameters + ---------- + session : APISession + Session object for API communication. + msa_id : str + Id of the MSA. + format : MSADownloadFormat, optional + Render to this format (one of "a2m", "a3m", "csv", "fasta", "sto"), or + "parquet" for the stored ``msa-parquet-v1`` bytes; defaults to the + source format. + + Returns + ------- + bytes + The rendered alignment. + """ + params = {"format": format} if format is not None else None + response = read(session, f"v1/data/msa/{msa_id}", params=params) + return response.content + + +def msa_put( + session: APISession, + msa_id: str, + name: str | None = None, + description: str | None = None, + tags: list[str] | None = None, +) -> MSAMetadata: + """ + Update the mutable metadata (name / description / tags) of an MSA. + + Only the fields provided are changed; the alignment itself is immutable. + + Parameters + ---------- + session : APISession + Session object for API communication. + msa_id : str + Id of the MSA. + name, description : str, optional + New name / description. + tags : list[str], optional + Replacement tag list. + + Returns + ------- + MSAMetadata + The updated metadata. + """ + body: dict = {} + if name is not None: + body["name"] = name + if description is not None: + body["description"] = description + if tags is not None: + body["tags"] = tags + if not body: + # nothing to change - skip the no-op PUT and return the current metadata + return msa_get_metadata(session, msa_id) + response = session.put(f"v1/data/msa/{msa_id}", json=body) + return MSAMetadata.model_validate(response.json()) + + +def msa_delete(session: APISession, msa_id: str) -> None: + """ + Delete an MSA. + + Parameters + ---------- + session : APISession + Session object for API communication. + msa_id : str + Id of the MSA. + """ + session.delete(f"v1/data/msa/{msa_id}") diff --git a/openprotein/data/msa/msa.py b/openprotein/data/msa/msa.py new file mode 100644 index 0000000..14eb943 --- /dev/null +++ b/openprotein/data/msa/msa.py @@ -0,0 +1,352 @@ +"""Stored MSAs (``session.data.MSA``). + +Upload an MSA, or build one with ``session.align.create_msa``, and address it by +its ``id``. Iterating a stored MSA reads its rows, ``to_string`` renders it in +any supported format, and ``sample_prompt`` samples it into a prompt. + +>>> msa = session.data.MSA.create(open("aln.a3m", "rb").read(), format="a3m") +>>> len(msa) +128 +>>> name, sequence = msa[0] +>>> fasta = msa.to_string("fasta") +>>> prompt = msa.sample_prompt(replicates=2).wait() +""" + +from __future__ import annotations + +import builtins +import re +from collections.abc import Iterator +from datetime import datetime +from typing import TYPE_CHECKING, get_args, overload + +from typing_extensions import Self + +from openprotein import fasta +from openprotein.base import APISession +from openprotein.data._resource import _Resource +from openprotein.jobs.schemas import JobStatus + +from . import _api +from .schemas import MSAFormat, MSAMetadata + +if TYPE_CHECKING: + from openprotein.align.schemas import MSASamplingMethod + from openprotein.data.prompts import Prompt + +__all__ = ["MSA"] + +_LIST_PAGE = 200 + +# Rectangular formats that can mark inserts. Their FASTA rendering keeps every +# column, so their rows come from the a2m rendering with the inserts dropped. +_INSERTS_KEPT_BY_FASTA = frozenset({"a2m", "sto"}) + + +class MSA(_Resource[MSAMetadata]): + """A stored MSA. + + ``session.data.MSA.create`` uploads one, ``session.data.MSA.list`` lists the + caller's and ``session.data.MSA(id=...)`` loads one. Iterating it yields its + ``(name, sequence)`` rows, read on first use. + + See Also + -------- + openprotein.align.MSAFuture : The job that builds an MSA. Its id is the id + of the MSA it stores. + """ + + _rows: builtins.list[tuple[str, str]] | None = None + + @classmethod + def _load(cls, session: APISession, id: str) -> MSAMetadata: + return _api.msa_get_metadata(session, id) + + @classmethod + def create( + cls, + file: bytes | str, + format: MSAFormat, + name: str | None = None, + description: str | None = None, + filename: str | None = None, + ) -> Self: + """Upload an MSA, declaring its ``format`` (e.g. ``"a3m"``, ``"fasta"``). + + Parameters + ---------- + file : bytes | str + The MSA contents; a ``str`` is encoded as UTF-8 (read a file first, + e.g. ``open(path, "rb").read()``). + format : str + The upload's format, naming the codec used to parse it. + name, description : str, optional + Human-readable metadata to store alongside the MSA. + filename : str, optional + Original filename to record; defaults to a name derived from ``format``. + + Returns + ------- + MSA + The stored MSA. + """ + session = cls._bound() + content = file.encode() if isinstance(file, str) else file + metadata = _api.msa_post( + session, + file=content, + format=format, + name=name, + description=description, + filename=filename, + ) + return cls(session, metadata) + + @classmethod + def list(cls, limit: int | None = None) -> builtins.list[Self]: + """The caller's stored MSAs from every page, at most ``limit``.""" + session = cls._bound() + msas: builtins.list[Self] = [] + while limit is None or len(msas) < limit: + size = _LIST_PAGE if limit is None else min(_LIST_PAGE, limit - len(msas)) + page = _api.msa_list(session, limit=size, offset=len(msas)) + msas.extend(cls(session, metadata) for metadata in page.items) + if not page.items or len(msas) >= page.total: + break + return msas if limit is None else msas[:limit] + + @property + def id(self) -> str: + """The MSA's id.""" + return self.metadata.msa_id + + @property + def digest(self) -> str | None: + """The row's content digest.""" + return self.metadata.digest + + @property + def name(self) -> str | None: + return self.metadata.name + + @property + def description(self) -> str | None: + return self.metadata.description + + @property + def status(self) -> JobStatus: + """``SUCCESS`` once the MSA is ready, else the status of the job producing it.""" + return self.metadata.status + + @property + def job_id(self) -> str | None: + """The job that produces the MSA; ``None`` for an upload.""" + return self.metadata.job_id + + @property + def source_format(self) -> MSAFormat | None: + return self.metadata.source_format + + @property + def num_sequences(self) -> int | None: + return self.metadata.num_sequences + + @property + def num_match_columns(self) -> int | None: + return self.metadata.num_match_columns + + @property + def has_insertions(self) -> bool | None: + return self.metadata.has_insertions + + @property + def tags(self) -> builtins.list[str]: + return self.metadata.tags + + @property + def original_filename(self) -> str | None: + return self.metadata.original_filename + + @property + def created_at(self) -> datetime: + return self.metadata.created_at + + @property + def updated_at(self) -> datetime: + return self.metadata.updated_at + + def _forget(self) -> None: + self._rows = None + + def _read(self) -> builtins.list[tuple[str, str]]: + if self._rows is None: + self._require_ready() + rows = None + if self.source_format in _INSERTS_KEPT_BY_FASTA and self.num_match_columns: + rows = _match_column_rows(self._download("a2m"), self.num_match_columns) + self._rows = rows if rows is not None else self._download("fasta") + return self._rows + + def _download(self, format: MSAFormat) -> builtins.list[tuple[str, str]]: + text = _api.msa_download(self.session, self.id, format).decode() + return builtins.list(fasta.parse_stream(iter(text.splitlines()))) + + def __len__(self) -> int: + if self._rows is None and self.metadata.num_sequences is not None: + return self.metadata.num_sequences + return len(self._read()) + + def __iter__(self) -> Iterator[tuple[str, str]]: + """The ``(name, sequence)`` rows, aligned to one length. + + Insertions relative to the query are left out; ``to_string`` keeps + them. An a2m or Stockholm upload whose rows don't all mark the same + insert columns, by lowercase and ``.``, keeps every column. The rows + are read on first use. + """ + return iter(self._read()) + + @overload + def __getitem__(self, index: int) -> tuple[str, str]: ... + + @overload + def __getitem__(self, index: slice) -> builtins.list[tuple[str, str]]: ... + + def __getitem__( + self, index: int | slice + ) -> tuple[str, str] | builtins.list[tuple[str, str]]: + return self._read()[index] + + def to_string(self, format: MSAFormat | None = None) -> str: + """The alignment as text in ``format``, by default the stored format. + + Parameters + ---------- + format : str, optional + One of ``"a2m"``, ``"a3m"``, ``"csv"``, ``"fasta"`` and ``"sto"``. + + Raises + ------ + ValueError + If ``format`` is not one of the five. + """ + if format is not None and format not in get_args(MSAFormat): + raise ValueError( + f"format must be one of {', '.join(get_args(MSAFormat))}, " + f"not {format!r}" + ) + self._require_ready() + return _api.msa_download(self.session, self.id, format).decode() + + def sample_prompt( + self, + replicates: int = 1, + seed: int | None = None, + method: MSASamplingMethod | None = None, + homology_level: float | None = None, + max_similarity: float | None = None, + min_similarity: float | None = None, + max_msa_sequences: int | None = None, + max_msa_tokens: int | None = None, + force_include_first: bool | None = None, + ) -> Prompt: + """Sample this MSA into a prompt, one sample per replicate. + + Every option but ``replicates`` and ``seed`` is omitted when unset so + the sampling default applies. Sampling stops at whichever of ``max_msa_sequences`` + and ``max_msa_tokens`` is set; leave both unset to take the default + budget. + + Parameters + ---------- + replicates : int, optional + Number of prompts to sample. Defaults to 1. + seed : int, optional + Seed for the sampling. Each replicate draws its own from it. A + missing seed is drawn client-side. + method : MSASamplingMethod, optional + Sampling method. + homology_level : float, optional + Level of homology for sequences in the MSA, between 0 and 1 + (neighbors methods only). + max_similarity : float, optional + Maximum similarity between sequences in the MSA and the seed, + between 0 and 1. + min_similarity : float, optional + Minimum similarity between sequences in the MSA and the seed, + between 0 and 1. + max_msa_sequences : int, optional + Cap on the number of sequences sampled. + max_msa_tokens : int, optional + Cap on the number of residues sampled. + force_include_first : bool, optional + Whether to always include the seed sequence. + + Returns + ------- + Prompt + The prompt being sampled. ``wait`` returns it once it is ready. + + Raises + ------ + MissingParameterError + If both ``max_msa_sequences`` and ``max_msa_tokens`` are given. + """ + from openprotein.data.prompts.prompts import _sample + + return _sample( + self.session, + self.id, + replicates=replicates, + seed=seed, + method=method, + homology_level=homology_level, + max_similarity=max_similarity, + min_similarity=min_similarity, + max_msa_sequences=max_msa_sequences, + max_msa_tokens=max_msa_tokens, + force_include_first=force_include_first, + ) + + def update( + self, + name: str | None = None, + description: str | None = None, + tags: builtins.list[str] | None = None, + ) -> Self: + """Update the name, description or tags; only the ones given change.""" + self.metadata = _api.msa_put( + self.session, self.id, name=name, description=description, tags=tags + ) + return self + + def delete(self) -> None: + """Delete this MSA.""" + _api.msa_delete(self.session, self.id) + + +_INSERT = re.compile(r"[a-z.]") + + +def _match_column_rows( + rows: builtins.list[tuple[str, str]], num_match_columns: int +) -> builtins.list[tuple[str, str]] | None: + """The a2m rows without their insert columns, if every row marks the same ones. + + Stockholm need not mark inserts by lowercase and ``.``: it can use ``.`` as a + gap or lowercase for a masked residue. Rows that mark different columns, or + leave other than ``num_match_columns``, give ``None``. + """ + inserts: builtins.list[int] | None = None + stripped = [] + for name, sequence in rows: + marks = [match.start() for match in _INSERT.finditer(sequence)] + if inserts is None: + inserts = marks + elif marks != inserts: + return None + kept = _INSERT.sub("", sequence) + if len(kept) - kept.count(":") != num_match_columns: + return None + stripped.append((name, kept)) + return stripped diff --git a/openprotein/data/msa/schemas.py b/openprotein/data/msa/schemas.py new file mode 100644 index 0000000..8136243 --- /dev/null +++ b/openprotein/data/msa/schemas.py @@ -0,0 +1,38 @@ +from datetime import datetime +from typing import Literal + +from pydantic import BaseModel, Field + +from openprotein.jobs.schemas import JobStatus + +__all__ = ["MSADownloadFormat", "MSAFormat", "MSAMetadata"] + + +MSAFormat = Literal["a2m", "a3m", "csv", "fasta", "sto"] +MSADownloadFormat = Literal["a2m", "a3m", "csv", "fasta", "sto", "parquet"] + + +class MSAMetadata(BaseModel): + """Metadata for one stored MSA (never carries the sequence body). + + A search row has no uploaded original, so its ``msa_hash`` and + ``original_filename`` are ``None``. Until its job produces it, a row has a + ``status`` other than ``SUCCESS`` and no stats. + """ + + msa_id: str + status: JobStatus = JobStatus.SUCCESS + job_id: str | None = None + msa_hash: str | None = None + name: str | None = None + description: str | None = None + tags: list[str] = Field(default_factory=list) + project_uuid: str | None = None + source_format: MSAFormat | None = None + num_sequences: int | None = None + num_match_columns: int | None = None + has_insertions: bool | None = None + original_filename: str | None = None + digest: str | None = None + created_at: datetime + updated_at: datetime diff --git a/openprotein/data/prompts/__init__.py b/openprotein/data/prompts/__init__.py new file mode 100644 index 0000000..df40812 --- /dev/null +++ b/openprotein/data/prompts/__init__.py @@ -0,0 +1,10 @@ +"""Client for stored prompts (``session.data.Prompt``).""" + +from .prompts import Prompt +from .schemas import PromptRecord, PromptSummary + +__all__ = [ + "Prompt", + "PromptRecord", + "PromptSummary", +] diff --git a/openprotein/data/prompts/_api.py b/openprotein/data/prompts/_api.py new file mode 100644 index 0000000..d34581d --- /dev/null +++ b/openprotein/data/prompts/_api.py @@ -0,0 +1,151 @@ +"""Wire calls for stored prompts (``session.data.Prompt``).""" + +import secrets +from typing import Any + +from pydantic import BaseModel + +from openprotein.align.schemas import MSASamplingMethod +from openprotein.base import APISession +from openprotein.data._reads import read +from openprotein.errors import MissingParameterError + +from .schemas import PromptRecord, PromptSummary + + +class PromptPage(BaseModel): + """One page of prompt summaries, newest first.""" + + items: list[PromptSummary] + next: str | None = None + + +PATH_PREFIX = "v1/data/prompts" + + +def prompts_list( + session: APISession, after: str | None = None, limit: int | None = None +) -> PromptPage: + """List the caller's live prompts, newest first.""" + params: dict[str, Any] = {} + if after is not None: + params["after"] = after + if limit is not None: + params["limit"] = limit + response = session.get(PATH_PREFIX, params=params or None) + return PromptPage.model_validate(response.json()) + + +def prompts_get(session: APISession, prompt_id: str) -> PromptRecord: + """Get one prompt. + + A prompt whose job hasn't finished comes back with that job's ``status``. + A deleted or unknown id is a 404. + """ + return PromptRecord.model_validate( + read(session, f"{PATH_PREFIX}/{prompt_id}").json() + ) + + +def prompts_put( + session: APISession, + prompt_id: str, + name: str | None = None, + description: str | None = None, +) -> PromptRecord: + """Update name/description; only the given fields are sent.""" + body: dict[str, str] = {} + if name is not None: + body["name"] = name + if description is not None: + body["description"] = description + response = session.patch(f"{PATH_PREFIX}/{prompt_id}", json=body) + return PromptRecord.model_validate(response.json()) + + +def prompts_delete(session: APISession, prompt_id: str) -> None: + """Delete the prompt.""" + session.delete(f"{PATH_PREFIX}/{prompt_id}") + + +def prompts_post( + session: APISession, + replicates: list[bytes], + name: str | None = None, + description: str | None = None, +) -> PromptRecord: + """Upload a prompt, one FASTA file per replicate, in position order.""" + data: dict[str, str] = {} + if name is not None: + data["name"] = name + if description is not None: + data["description"] = description + files = [ + ("replicates", (f"replicate-{position}.fasta", content)) + for position, content in enumerate(replicates) + ] + response = session.post(PATH_PREFIX, data=data, files=files) + return PromptRecord.model_validate(response.json()) + + +def prompts_download(session: APISession, prompt_id: str) -> bytes: + """Download the zip of replicate FASTA files. + + 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 + + +def prompts_sample_post( + session: APISession, + msa_id: str, + replicates: int = 1, + seed: int | None = None, + method: MSASamplingMethod | None = None, + homology_level: float | None = None, + max_similarity: float | None = None, + min_similarity: float | None = None, + max_msa_sequences: int | None = None, + max_msa_tokens: int | None = None, + force_include_first: bool | None = None, +) -> dict[str, Any]: + """Submit one alignment for sampling into prompt replicates. + + A missing ``seed`` is drawn here. ``replicates`` is always sent. Every + other option is omitted when unset so the server's default applies. The + request carries no idempotency key, so it is sent once and never retried. + + Returns + ------- + dict + The sampling's job, whose ``job_id`` is the prompt's id. + + Raises + ------ + MissingParameterError + If both ``max_msa_sequences`` and ``max_msa_tokens`` are given. + """ + if max_msa_sequences is not None and max_msa_tokens is not None: + raise MissingParameterError( + "Either 'max_msa_sequences' or 'max_msa_tokens' may be set, but not both." + ) + + body: dict[str, Any] = { + "msa_id": msa_id, + "seed": secrets.randbits(32) if seed is None else seed, + "replicates": replicates, + } + optional: dict[str, Any] = { + "method": None if method is None else MSASamplingMethod(method).value, + "homology_level": homology_level, + "max_similarity": max_similarity, + "min_similarity": min_similarity, + "max_msa_sequences": max_msa_sequences, + "max_msa_tokens": max_msa_tokens, + "force_include_first": force_include_first, + } + body.update({k: v for k, v in optional.items() if v is not None}) + + response = session.post(f"{PATH_PREFIX}/sample_msa", json=body) + return response.json() diff --git a/openprotein/data/prompts/_replicates.py b/openprotein/data/prompts/_replicates.py new file mode 100644 index 0000000..94cfa50 --- /dev/null +++ b/openprotein/data/prompts/_replicates.py @@ -0,0 +1,28 @@ +"""Each replicate's complex sequences, from the prompt download.""" + +import re +import zipfile +from io import BytesIO + +from openprotein import fasta + +_REPLICATE_NAME = re.compile(r"replicate-(\d+)\.fasta$") + + +def parse_replicates(data: bytes) -> list[list[str]]: + """One entry per replicate, in position order; each a list of complex sequences.""" + with zipfile.ZipFile(BytesIO(data)) as archive: + positions = sorted( + (int(match.group(1)), name) + for name in archive.namelist() + if (match := _REPLICATE_NAME.search(name)) + ) + return [ + [ + sequence + for _, sequence in fasta.parse_stream( + iter(archive.read(name).decode("utf-8").splitlines()) + ) + ] + for _, name in positions + ] diff --git a/openprotein/data/prompts/prompts.py b/openprotein/data/prompts/prompts.py new file mode 100644 index 0000000..94b3c51 --- /dev/null +++ b/openprotein/data/prompts/prompts.py @@ -0,0 +1,250 @@ +"""Stored prompts (``session.data.Prompt``). + +Upload a prompt or sample one from a stored MSA, and address it by its ``id``. +Iterating a prompt reads its replicates. + +>>> prompt = session.data.Prompt.create([open("r0.fasta", "rb").read()]) +>>> replicate = prompt[0] +>>> sampled = msa.sample_prompt(replicates=2).wait() +""" + +from __future__ import annotations + +import builtins +from collections.abc import Iterator +from datetime import datetime +from typing import TYPE_CHECKING, overload + +from typing_extensions import Self + +from openprotein.base import APISession +from openprotein.data._resource import _Resource +from openprotein.errors import HTTPError +from openprotein.jobs.schemas import Job, JobStatus + +from . import _api, _replicates +from .schemas import PromptSummary + +if TYPE_CHECKING: + from openprotein.align.schemas import MSASamplingMethod + +__all__ = ["Prompt"] + +_LIST_PAGE = 200 + + +class Prompt(_Resource[PromptSummary]): + """A stored prompt. + + ``session.data.Prompt.create`` uploads one, ``session.data.Prompt.list`` + lists the caller's and ``session.data.Prompt(id=...)`` loads one. Iterating + it yields its replicates, read on first use. + + See Also + -------- + openprotein.prompt.Prompt : A prompt created from sequences and structures + with ``session.prompt.create_prompt``. + """ + + _replicates: builtins.list[builtins.list[str]] | None = None + + @classmethod + def _load(cls, session: APISession, id: str) -> PromptSummary: + return _api.prompts_get(session, id) + + @classmethod + def _from_job(cls, session: APISession, job: Job) -> Self: + """The prompt a sampling job produces, as stored or else as the job reports it.""" + bound = cls._for(session) + try: + return bound(session, cls._load(session, job.job_id)) + except HTTPError as error: + if error.status_code != 404: + raise + prompt = bound( + session, + PromptSummary( + id=job.job_id, + status=job.status, + job_id=job.job_id, + created_at=job.created_date, + ), + ) + prompt._job = job + prompt._from_job_only = job.status is JobStatus.SUCCESS + return prompt + + @classmethod + def create( + cls, + replicates: builtins.list[bytes | str], + name: str | None = None, + description: str | None = None, + ) -> Self: + """Upload a prompt, one FASTA file per replicate, in position order. + + Parameters + ---------- + replicates : list of bytes or str + One FASTA file per replicate; a ``str`` is encoded as UTF-8. + name, description : str, optional + Human-readable metadata to store alongside the prompt. + + Returns + ------- + Prompt + The stored prompt. + + Raises + ------ + TypeError + If ``replicates`` is a bare ``str`` or ``bytes``. + """ + if isinstance(replicates, (str, bytes)): + raise TypeError( + "replicates must be a list of FASTA files, " + f"not a {type(replicates).__name__}; " + "pass a list of files, e.g. create([contents])" + ) + session = cls._bound() + contents = [ + replicate.encode() if isinstance(replicate, str) else replicate + for replicate in replicates + ] + return cls( + session, + _api.prompts_post(session, contents, name=name, description=description), + ) + + @classmethod + def list(cls, limit: int | None = None) -> builtins.list[Self]: + """The caller's stored prompts from every page, newest first, at most ``limit``.""" + session = cls._bound() + prompts: builtins.list[Self] = [] + after: str | None = None + while limit is None or len(prompts) < limit: + size = ( + _LIST_PAGE if limit is None else min(_LIST_PAGE, limit - len(prompts)) + ) + page = _api.prompts_list(session, after=after, limit=size) + prompts.extend(cls(session, item) for item in page.items) + after = page.next + if after is None: + break + return prompts if limit is None else prompts[:limit] + + @property + def id(self) -> str: + return self.metadata.id + + @property + def status(self) -> JobStatus: + """``SUCCESS`` once the prompt is ready, else the status of the job producing it.""" + return self.metadata.status + + @property + def job_id(self) -> str | None: + """The job that produces the prompt; ``None`` for an upload.""" + return self.metadata.job_id + + @property + def owner(self) -> str | None: + return self.metadata.owner + + @property + def name(self) -> str | None: + return self.metadata.name + + @property + def description(self) -> str | None: + return self.metadata.description + + @property + def created_at(self) -> datetime | None: + return self.metadata.created_at + + @property + def digest(self) -> str | None: + """The row's content identity.""" + return self.metadata.digest + + def _forget(self) -> None: + self._replicates = None + + def _read(self) -> builtins.list[builtins.list[str]]: + if self._replicates is None: + self._require_ready() + self._replicates = _replicates.parse_replicates( + _api.prompts_download(self.session, self.id) + ) + return self._replicates + + def __len__(self) -> int: + return len(self._read()) + + def __iter__(self) -> Iterator[builtins.list[str]]: + """Each replicate's sequences, a complex's chains joined by ``:``. + + The replicates are read on first use. + """ + return iter(self._read()) + + @overload + def __getitem__(self, index: int) -> builtins.list[str]: ... + + @overload + def __getitem__(self, index: slice) -> builtins.list[builtins.list[str]]: ... + + def __getitem__( + self, index: int | slice + ) -> builtins.list[str] | builtins.list[builtins.list[str]]: + return self._read()[index] + + def update(self, name: str | None = None, description: str | None = None) -> Self: + """Update the name or description; only the ones given change.""" + self.metadata = _api.prompts_put( + self.session, self.id, name=name, description=description + ) + return self + + def delete(self) -> None: + """Delete this prompt.""" + _api.prompts_delete(self.session, self.id) + + +def _sample( + session: APISession, + msa_id: str, + replicates: int = 1, + seed: int | None = None, + method: MSASamplingMethod | None = None, + homology_level: float | None = None, + max_similarity: float | None = None, + min_similarity: float | None = None, + max_msa_sequences: int | None = None, + max_msa_tokens: int | None = None, + force_include_first: bool | None = None, +) -> Prompt: + """Submit one sampling of a stored MSA and return the prompt it produces.""" + job = _api.prompts_sample_post( + session, + msa_id=msa_id, + replicates=replicates, + seed=seed, + method=method, + homology_level=homology_level, + max_similarity=max_similarity, + min_similarity=min_similarity, + max_msa_sequences=max_msa_sequences, + max_msa_tokens=max_msa_tokens, + force_include_first=force_include_first, + ) + return Prompt._for(session)( + session, + PromptSummary( + id=job["job_id"], + status=job["status"], + job_id=job["job_id"], + created_at=job.get("created_date"), + ), + ) diff --git a/openprotein/data/prompts/schemas.py b/openprotein/data/prompts/schemas.py new file mode 100644 index 0000000..85d50b9 --- /dev/null +++ b/openprotein/data/prompts/schemas.py @@ -0,0 +1,43 @@ +"""Schemas for stored prompts (``session.data.Prompt``).""" + +from datetime import datetime +from typing import Any + +from pydantic import BaseModel + +from openprotein.jobs.schemas import JobStatus + +__all__ = ["PromptRecord", "PromptSummary", "PromptUnitValue"] + + +class PromptSummary(BaseModel): + """One row as listed, without its replicates. + + A row whose job hasn't finished has a ``status`` other than ``SUCCESS`` and + no replicates. + """ + + id: str + status: JobStatus = JobStatus.SUCCESS + job_id: str | None = None + owner: str | None = None + digest: str | None = None + name: str | None = None + description: str | None = None + created_at: datetime | None = None + + +class PromptUnitValue(BaseModel): + """One replicate's presigned value.""" + + position: int + value: dict[str, Any] + + +class PromptRecord(PromptSummary): + """One row read in full, carrying each replicate's presigned value. + + ``value`` is ``None`` until the row's job has produced the replicates. + """ + + value: list[PromptUnitValue] | None = None diff --git a/openprotein/data/schemas.py b/openprotein/data/schemas.py index 8c7a8b6..8031cf2 100644 --- a/openprotein/data/schemas.py +++ b/openprotein/data/schemas.py @@ -1,6 +1,10 @@ from datetime import datetime -from pydantic import BaseModel +from pydantic import BaseModel, field_validator + +from openprotein.jobs.schemas import JobStatus + +__all__ = ["AssayDataPage", "AssayDataRow", "AssayMetadata"] class AssayMetadata(BaseModel): @@ -14,11 +18,20 @@ class AssayMetadata(BaseModel): measurement_names: list[str] sequence_length: int | None = None has_name_column: bool = False + metadata_names: list[str] | None = None + status: JobStatus = JobStatus.SUCCESS + align_job_id: str | None = None + + @field_validator("status", mode="before") + @classmethod + def _null_status_is_success(cls, value): + return JobStatus.SUCCESS if value is None else value class AssayDataRow(BaseModel): mut_sequence: str measurement_values: list[float | None] + metadata_values: list[str | None] | None = None class AssayDataPage(BaseModel): diff --git a/openprotein/design/__init__.py b/openprotein/design/__init__.py index aee7370..56502db 100644 --- a/openprotein/design/__init__.py +++ b/openprotein/design/__init__.py @@ -14,3 +14,14 @@ ) from .future import DesignFuture from .design import DesignAPI + +__all__ = [ + "Criteria", + "Criterion", + "DesignAPI", + "DesignConstraint", + "DesignFuture", + "ModelCriterion", + "Subcriterion", + "n_mutations", +] diff --git a/openprotein/design/api.py b/openprotein/design/api.py index ff3e71a..a1f3b80 100644 --- a/openprotein/design/api.py +++ b/openprotein/design/api.py @@ -19,7 +19,18 @@ Subcriterion, ) -PATH_PREFIX = "v1/designer/design" +__all__ = [ + "decode_design_result", + "decode_design_results_stream", + "design_delete", + "design_get", + "designer_create_genetic_algorithm", + "designer_get_design_results", + "designs_list", +] + + +_PATH_PREFIX = "v1/designer/design" def designs_list(session: APISession) -> list[Design]: @@ -36,7 +47,7 @@ def designs_list(session: APISession) -> list[Design]: list[Design] List of designs. """ - endpoint = PATH_PREFIX + endpoint = _PATH_PREFIX response = session.get(endpoint) return TypeAdapter(list[Design]).validate_python(response.json()) @@ -57,7 +68,7 @@ def design_get(session: APISession, design_id: str) -> Design: Design Design metadata. """ - endpoint = PATH_PREFIX + f"/{design_id}" + endpoint = _PATH_PREFIX + f"/{design_id}" response = session.get(endpoint) return TypeAdapter(Design).validate_python(response.json()) @@ -86,9 +97,9 @@ def designer_create_genetic_algorithm( criteria: list[list[DesignCriterion]] List of list of design criteria, logically grouping by OR then AND. num_steps: int, optional - The number of steps in the genetic algorithm. Default is 8. + The number of steps in the genetic algorithm. Default is 25. pop_size: int, optional - The population size for the genetic algorithm. Default is 256. + The population size for the genetic algorithm. Default is 1024. n_offsprings: int, optional The number of offspring for the genetic algorithm. Default is 5120. crossover_prob: float, optional @@ -112,7 +123,7 @@ def designer_create_genetic_algorithm( if isinstance(allowed_tokens, DesignConstraint): allowed_tokens = allowed_tokens.as_dict() - endpoint = PATH_PREFIX + "/genetic-algorithm" + endpoint = _PATH_PREFIX + "/genetic-algorithm" body = { "assay_id": assay_id, @@ -139,7 +150,7 @@ def designer_get_design_results( step: int | None = None, ) -> Iterator[list[str]]: """ - Get csv encoded results for a design ID. + Get the results for a design ID. Parameters ---------- @@ -152,14 +163,15 @@ def designer_get_design_results( Returns ------- - bytes + Iterator[list[str]] + An iterator over the rows of the design results. """ params = {} if step is not None: if step != -1: step -= 1 params["step"] = step - endpoint = PATH_PREFIX + f"/{design_id}/results" + endpoint = _PATH_PREFIX + f"/{design_id}/results" response = session.get(endpoint, params=params, stream=True) return csv.parse_stream(response.iter_lines()) @@ -171,15 +183,19 @@ def decode_design_result( pred_start_index: int, ) -> DesignResult: """ - Decode prediction scores. + Decode a row of design results into scores, subscores and predictions. Args: - data (bytes): raw bytes encoding the array received over the API - batched (bool): whether or not the result was batched. affects the retrieved csv format whether they contain additional columns and header rows. + row: One row of design results, as yielded by `designer_get_design_results`. + score_start_index: Index of the first score column. + subscore_start_index: Index of the first subscore column, which also + marks the end of the scores. + pred_start_index: Index of the first prediction column, which also marks + the end of the subscores. Predictions alternate mean and variance + from this column onward. Returns: - mus (np.ndarray): decoded array of means - vars (np.ndarray): decoded array of variances + The decoded row. `step` and `sample_index` are returned 1-based. """ scores = np.array( [float(score) for score in row[score_start_index:subscore_start_index]] @@ -228,7 +244,6 @@ def decode_design_results_stream( K array of means for each model subscriterion. vars: np.ndarray[float] K array of variances for each model subscriterion. - vars (np.ndarray): decoded array of variances """ if header is None: header = next(data) diff --git a/openprotein/design/design.py b/openprotein/design/design.py index 57a04c0..1a4ee1b 100644 --- a/openprotein/design/design.py +++ b/openprotein/design/design.py @@ -1,13 +1,14 @@ """Design API providing the interface to design novel proteins based on a your design criteria.""" from openprotein.base import APISession -from openprotein.data import AssayDataset, DataAPI -from openprotein.jobs import JobsAPI +from openprotein.data import AssayDataset from . import api from .future import DesignFuture from .schemas import Criteria, Criterion, DesignConstraint, Subcriterion +__all__ = ["DesignAPI"] + class DesignAPI: """Design API providing the interface to design novel proteins based on your design criteria.""" diff --git a/openprotein/design/future.py b/openprotein/design/future.py index 87aae19..fc762e9 100644 --- a/openprotein/design/future.py +++ b/openprotein/design/future.py @@ -9,6 +9,8 @@ from . import api from .schemas import Criteria, Design, DesignAlgorithm, DesignJob, DesignResult +__all__ = ["DesignFuture"] + class DesignFuture(StreamingFuture, Future): """A future object that will hold the results of the design job.""" @@ -29,7 +31,6 @@ def __init__( :meta private: """ self._design_assay = None - # initialize the metadata if metadata is None: if job is None: raise ValueError("Expected design metadata or job") @@ -116,11 +117,7 @@ def _refresh_metadata(self): ) def __delete(self) -> bool: - """ - Delete this design. - - TODO - implementation - """ + """Delete this design.""" return api.design_delete(session=self.session, design_id=self.id) def stream(self, step: int | None = None) -> Iterator[DesignResult]: @@ -143,4 +140,4 @@ def get_assay(self) -> AssayDataset: """ data_api = getattr(self.session, "data", None) assert isinstance(data_api, DataAPI) - return data_api.get(self._metadata.assay_id) + return data_api.Assay(id=self._metadata.assay_id) diff --git a/openprotein/design/schemas.py b/openprotein/design/schemas.py index ec211ac..8819abd 100644 --- a/openprotein/design/schemas.py +++ b/openprotein/design/schemas.py @@ -1,6 +1,5 @@ """Schemas for the OpenProtein design system.""" -from collections import namedtuple from datetime import datetime from enum import Enum from typing import Any, Literal, NamedTuple @@ -9,6 +8,22 @@ from pydantic import BaseModel, ConfigDict, Field, RootModel, model_serializer from openprotein.jobs import Job, JobStatus, JobType +from openprotein.utils.sequence import CHAIN_BREAK + +__all__ = [ + "Criteria", + "Criterion", + "CriterionType", + "Design", + "DesignAlgorithm", + "DesignConstraint", + "DesignJob", + "DesignResult", + "ModelCriterion", + "NMutationCriterion", + "Subcriterion", + "n_mutations", +] class CriterionType(str, Enum): @@ -410,6 +425,9 @@ class DesignConstraint: """ Class for managing design constraints on a sequence. + Positions are 1-indexed over the full sequence, including any ``:`` chain + breaks. Chain-break positions are fixed and cannot be constrained. + Attributes ---------- sequence : str @@ -444,7 +462,33 @@ def initialize(self, sequence: str) -> dict[int, set[str]]: dict of int to set of str Allowed amino acids at each position. """ - return {i: {aa} for i, aa in enumerate(sequence, start=1)} + return {i: {aa} for i, aa in enumerate(sequence, start=1) if aa != CHAIN_BREAK} + + def _resolve( + self, + amino_acids: list[str] | str | None, + positions: int | list[int] | None, + ) -> tuple[list[str], list[int]]: + if isinstance(positions, int): + positions = [positions] + elif positions is None: + positions = [ + i for i, aa in enumerate(self.sequence, start=1) if aa != CHAIN_BREAK + ] + if isinstance(amino_acids, str): + amino_acids = list(amino_acids) + elif amino_acids is None: + amino_acids = sorted(set(self.sequence) - {CHAIN_BREAK}) + + if CHAIN_BREAK in amino_acids: + raise ValueError(f"'{CHAIN_BREAK}' cannot be an allowed token") + for position in positions: + if ( + 1 <= position <= len(self.sequence) + and self.sequence[position - 1] == CHAIN_BREAK + ): + raise ValueError(f"position {position} is a chain break") + return amino_acids, positions def allow( self, @@ -461,14 +505,7 @@ def allow( positions : int or list of int or None, optional Positions to allow amino acids at. If None, allows at all positions. """ - if isinstance(positions, int): - positions = [positions] - elif positions is None: - positions = [i + 1 for i in range(len(self.sequence))] - if isinstance(amino_acids, str): - amino_acids = list(amino_acids) - elif amino_acids is None: - amino_acids = list(self.sequence) + amino_acids, positions = self._resolve(amino_acids, positions) for position in positions: if position in self.mutations: @@ -492,14 +529,7 @@ def remove( positions : int or list of int or None, optional Positions to remove amino acids from. If None, removes from all positions. """ - if isinstance(positions, int): - positions = [positions] - elif positions is None: - positions = [i + 1 for i in range(len(self.sequence))] - if isinstance(amino_acids, str): - amino_acids = list(amino_acids) - elif amino_acids is None: - amino_acids = list(self.sequence) + amino_acids, positions = self._resolve(amino_acids, positions) for position in positions: if position in self.mutations: @@ -605,7 +635,7 @@ class DesignJob(Job): Attributes ---------- job_type : Literal[JobType.designer] - The type of the job (always 'designer'). + Discriminator identifying a design job. """ job_type: Literal[JobType.designer] diff --git a/openprotein/embeddings/__init__.py b/openprotein/embeddings/__init__.py index 9a05e9d..fc2f47f 100644 --- a/openprotein/embeddings/__init__.py +++ b/openprotein/embeddings/__init__.py @@ -27,3 +27,25 @@ EmbeddingsScoreFuture, EmbeddingsScoreSingleSiteFuture, ) + +__all__ = [ + "AbLang2Model", + "AttnJob", + "ESMModel", + "EmbeddedSequence", + "EmbeddingModel", + "EmbeddingsAPI", + "EmbeddingsGenerateFuture", + "EmbeddingsJob", + "EmbeddingsResultFuture", + "EmbeddingsScoreFuture", + "EmbeddingsScoreSingleSiteFuture", + "GenerateJob", + "LogitsJob", + "OpenProteinModel", + "PoET2Model", + "PoETModel", + "ScoreIndelJob", + "ScoreJob", + "ScoreSingleSiteJob", +] diff --git a/openprotein/embeddings/ablang.py b/openprotein/embeddings/ablang.py index 294df17..d5994b9 100644 --- a/openprotein/embeddings/ablang.py +++ b/openprotein/embeddings/ablang.py @@ -1,7 +1,11 @@ """AbLang model.""" +from . import api +from .future import EmbeddingsScoreSingleSiteFuture from .models import EmbeddingModel +__all__ = ["AbLang2Model"] + class AbLang2Model(EmbeddingModel): """ @@ -19,3 +23,37 @@ class AbLang2Model(EmbeddingModel): """ model_id = ["ablang2"] + + def single_site( + self, + sequence: bytes | str, + ) -> EmbeddingsScoreSingleSiteFuture: + """ + Score all single substitutions of a paired antibody sequence. + + Masks each position of the sequence in turn and scores every + substitution there against the wild-type residue, so the wild type + scores 0 and a positive score means the model prefers the + substitution. `sequence` is a paired VH:VL sequence; the ':' + separator is kept and both chains are scanned. Gap ('-') positions + are skipped and kept in every variant. `include_gaps` is not + supported for this model. + + Parameters + ---------- + sequence : bytes or str + Paired VH:VL sequence to analyze. + + Returns + ------- + EmbeddingsScoreSingleSiteFuture + Future object that returns the per-variant scores of the single substitutions. + """ + return EmbeddingsScoreSingleSiteFuture.create( + session=self.session, + job=api.request_score_single_site_post( + session=self.session, + model_id=self.id, + base_sequence=sequence, + ), + ) diff --git a/openprotein/embeddings/api.py b/openprotein/embeddings/api.py index 9feabfb..72a33de 100644 --- a/openprotein/embeddings/api.py +++ b/openprotein/embeddings/api.py @@ -25,7 +25,27 @@ ScoreSingleSiteJob, ) -PATH_PREFIX = "v1/embeddings" +__all__ = [ + "get_model", + "get_request_sequences", + "list_models", + "parse_framed_npy_stream", + "request_attn_post", + "request_generate_post", + "request_get_embeddings_stream", + "request_get_generate_result", + "request_get_score_result", + "request_get_sequence_result", + "request_logits_post", + "request_post", + "request_score_indel_post", + "request_score_post", + "request_score_single_site_post", + "result_decode", +] + + +_PATH_PREFIX = "v1/embeddings" def list_models( @@ -42,7 +62,7 @@ def list_models( list[str] | list[ModelMetadata]: list of model names or metadata objects. """ - endpoint = PATH_PREFIX + "/models" + endpoint = _PATH_PREFIX + "/models" params = {} if verbose: params["verbose"] = "true" @@ -54,7 +74,7 @@ def list_models( def get_model(session: APISession, model_id: str) -> ModelMetadata: - endpoint = PATH_PREFIX + f"/models/{model_id}" + endpoint = _PATH_PREFIX + f"/models/{model_id}" response = session.get(endpoint) result = response.json() return ModelMetadata(**result) @@ -77,7 +97,6 @@ def get_request_sequences( ------- sequences : List[bytes] """ - # NOTE - allow to handle svd/embed and umap/embed directly too instead of redirect path = "v1" + job_type.value endpoint = path + f"/{job_id}/sequences" response = session.get(endpoint) @@ -106,7 +125,6 @@ def request_get_sequence_result( ------- result : bytes """ - # NOTE - allow to handle svd/embed and umap/embed directly too instead of redirect path = "v1" + job_type.value if isinstance(sequence, bytes): sequence = sequence.decode() @@ -144,7 +162,7 @@ def request_get_score_result(session: APISession, job_id: str) -> Iterator[list[ ------- csv.reader """ - endpoint = PATH_PREFIX + f"/{job_id}/scores" + endpoint = _PATH_PREFIX + f"/{job_id}/scores" response = session.get(endpoint, stream=True) return csv.parse_stream(response.iter_lines()) @@ -175,14 +193,13 @@ def request_get_embeddings_stream( Raises ------ - requests.HTTPError - If the HTTP request returns a non‐2xx status code. + openprotein.errors.HTTPError + If the request is unsuccessful. ValueError If the framed stream is malformed (e.g. incomplete header or payload). """ - endpoint = PATH_PREFIX + f"/{job_id}/stream" + endpoint = _PATH_PREFIX + f"/{job_id}/stream" response = session.get(endpoint, stream=True) - response.raise_for_status() response.raw.decode_content = True buffered = io.BufferedReader(response.raw) # type: ignore for array in parse_framed_npy_stream(buffered): @@ -255,7 +272,7 @@ def request_get_generate_result( ------- csv.reader """ - endpoint = PATH_PREFIX + f"/{job_id}/generate" + endpoint = _PATH_PREFIX + f"/{job_id}/generate" response = session.get(endpoint, stream=True) return csv.parse_stream(response.iter_lines()) @@ -288,7 +305,7 @@ def request_post( ------- job : Job """ - endpoint = PATH_PREFIX + f"/models/{model_id}/embed" + endpoint = _PATH_PREFIX + f"/models/{model_id}/embed" sequences_unicode = [(s if isinstance(s, str) else s.decode()) for s in sequences] body: dict = { @@ -335,7 +352,7 @@ def request_logits_post( ------- job : Job """ - endpoint = PATH_PREFIX + f"/models/{model_id}/logits" + endpoint = _PATH_PREFIX + f"/models/{model_id}/logits" sequences_unicode = [(s if isinstance(s, str) else s.decode()) for s in sequences] body: dict = { @@ -381,7 +398,7 @@ def request_attn_post( ------- job : Job """ - endpoint = PATH_PREFIX + f"/models/{model_id}/attn" + endpoint = _PATH_PREFIX + f"/models/{model_id}/attn" sequences_unicode = [(s if isinstance(s, str) else s.decode()) for s in sequences] body: dict = { @@ -423,7 +440,7 @@ def request_score_post( ------- job : Job """ - endpoint = PATH_PREFIX + f"/models/{model_id}/score" + endpoint = _PATH_PREFIX + f"/models/{model_id}/score" sequences_unicode = [(s if isinstance(s, str) else s.decode()) for s in sequences] body: dict = { "sequences": sequences_unicode, @@ -438,6 +455,8 @@ def request_score_post( ] if kwargs.get("decoder_type"): body["decoder_type"] = kwargs["decoder_type"] + if kwargs.get("seed") is not None: + body["seed"] = kwargs["seed"] response = session.post(endpoint, json=body) return ScoreJob.model_validate(response.json()) @@ -474,7 +493,7 @@ def request_score_indel_post( ------- job : Job """ - endpoint = PATH_PREFIX + f"/models/{model_id}/score/indel" + endpoint = _PATH_PREFIX + f"/models/{model_id}/score/indel" body: dict = { "base_sequence": ( @@ -518,8 +537,8 @@ def request_score_single_site_post( Session object for API communication. model_id : str model ID to request results from - sequences : List[bytes] - sequences to request results for + base_sequence : bytes or str + sequence whose single substitutions are scored **kwargs: Optional parameters for models, e.g. prompt_id for PoET @@ -527,7 +546,7 @@ def request_score_single_site_post( ------- job : Job """ - endpoint = PATH_PREFIX + f"/models/{model_id}/score_single_site" + endpoint = _PATH_PREFIX + f"/models/{model_id}/score_single_site" body: dict = { "base_sequence": ( @@ -546,6 +565,8 @@ def request_score_single_site_post( ] if kwargs.get("decoder_type"): body["decoder_type"] = kwargs["decoder_type"] + if kwargs.get("seed") is not None: + body["seed"] = kwargs["seed"] response = session.post(endpoint, json=body) return ScoreSingleSiteJob.model_validate(response.json()) @@ -579,7 +600,7 @@ def request_generate_post( ------- job : Job """ - endpoint = PATH_PREFIX + f"/models/{model_id}/generate" + 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.") @@ -617,14 +638,14 @@ def request_generate_post( "use_query_structure_in_decoder" ] if (ensemble_weights := kwargs.get("ensemble_weights")) is not None: - assert ( - model_id != "poet" - ), f"Model with id {model_id} does not support ensemble_weights parameter" + assert model_id != "poet", ( + f"Model with id {model_id} does not support ensemble_weights parameter" + ) body["ensemble_weights"] = list(ensemble_weights) if (ensemble_method := kwargs.get("ensemble_method")) is not None: - assert ( - model_id != "poet" - ), f"Model with id {model_id} does not support ensemble_method parameter" + assert model_id != "poet", ( + f"Model with id {model_id} does not support ensemble_method parameter" + ) body["ensemble_method"] = ensemble_method response = session.post(endpoint, json=body) return GenerateJob.model_validate(response.json()) diff --git a/openprotein/embeddings/embeddings.py b/openprotein/embeddings/embeddings.py index c92c978..c72fbfa 100644 --- a/openprotein/embeddings/embeddings.py +++ b/openprotein/embeddings/embeddings.py @@ -11,6 +11,25 @@ from .poet import PoETModel from .poet2 import PoET2Model +__all__ = ["EmbeddingsAPI"] + + +_LEGACY_MODELS: dict[str, tuple[type[EmbeddingModel], str]] = { + "poet2": (PoET2Model, "poet-2"), + "poet": (PoETModel, "poet"), + "prot_seq": (OpenProteinModel, "prot-seq"), + "rotaprot_large_uniref50w": (OpenProteinModel, "rotaprot-large-uniref50w"), + "rotaprot_large_uniref90_ft": (OpenProteinModel, "rotaprot-large-uniref90-ft"), + "ablang2": (AbLang2Model, "ablang2"), + **{name.replace("-", "_"): (ESMModel, name) for name in ESMModel.get_model()}, +} +_LEGACY_ALIASES = { + "poet_2": "poet2", + "esm1b": "esm1b_t33_650M_UR50S", + "esm1v": "esm1v_t33_650M_UR90S_1", + "esm2": "esm2_t33_650M_UR50D", +} + class EmbeddingsAPI: """ @@ -42,8 +61,7 @@ class EmbeddingsAPI: model = session.embedding.get_model('prot-seq') """ - # added for static typing, eg pylance, for autocomplete - # at init these are all overwritten. + # Static declarations for typing and autocomplete. #: PoET-2 model poet2: PoET2Model @@ -85,24 +103,33 @@ class EmbeddingsAPI: def __init__(self, session: APISession): self.session = session - # dynamically add models from api list - self._load_models() - - def _load_models(self): - # Dynamically add model instances as attributes - precludes any drift - models = self.list_models() - for model in models: - model_name = model.id.replace("-", "_") # hyphens out - setattr(self, model_name, model) - # Setup aliases safely - if getattr(self, "esm1b_t33_650M_UR50S", None): - self.esm1b = self.esm1b_t33_650M_UR50S - if getattr(self, "esm1v_t33_650M_UR90S_1", None): - self.esm1v = self.esm1v_t33_650M_UR90S_1 - if getattr(self, "esm2_t33_650M_UR50D", None): - self.esm2 = self.esm2_t33_650M_UR50D - if getattr(self, "poet_2", None): - self.poet2 = self.poet_2 + + def __getattr__(self, name: str) -> EmbeddingModel: + """Resolve a model handle under the embeddings namespace. + + Names without a typed handle resolve against :meth:`list_models`. + """ + if name.startswith("_") or "session" not in self.__dict__: + raise AttributeError(name) + canonical = _LEGACY_ALIASES.get(name, name) + if canonical not in self.__dict__: + self.__dict__[canonical] = self._resolve(canonical) + return self.__dict__[canonical] + + def _resolve(self, name: str) -> EmbeddingModel: + entry = _LEGACY_MODELS.get(name) + if entry is not None: + cls, model_id = entry + return cls(self.session, model_id) + for model in self.list_models(): + if model.id.replace("-", "_") == name: + return model + raise AttributeError(name) + + def __dir__(self): + return sorted( + set(super().__dir__()) | _LEGACY_MODELS.keys() | _LEGACY_ALIASES.keys() + ) def list_models(self) -> list[EmbeddingModel]: """list models available for creating embeddings of your sequences""" @@ -138,6 +165,8 @@ def get_model(self, name: str) -> EmbeddingModel: Raises ------ + AttributeError + If no listed model has that name. HTTPError If the GET request does not succeed. """ diff --git a/openprotein/embeddings/esm.py b/openprotein/embeddings/esm.py index e8f6d8e..8059f58 100644 --- a/openprotein/embeddings/esm.py +++ b/openprotein/embeddings/esm.py @@ -1,12 +1,19 @@ """Community-based ESM models.""" +from . import api +from .future import EmbeddingsScoreSingleSiteFuture from .models import AttnModel, EmbeddingModel +__all__ = ["ESMModel"] + class ESMModel(AttnModel, EmbeddingModel): """ Class providing inference endpoints for Facebook's ESM protein language models. + Covers ESM-1b, ESM-1v, ESM2 and ESM Cambrian (ESMC), and supports single-site + scanning with `single_site`. + Examples -------- View specific model details (inc supported tokens) with the `?` operator. @@ -15,7 +22,7 @@ class ESMModel(AttnModel, EmbeddingModel): >>> import openprotein >>> session = openprotein.connect(username="user", password="password") - >>> session.embedding.esm2_t12_35M_UR50D? + >>> session.embedding.esm1b_t33_650M_UR50S? """ model_id = [ @@ -34,3 +41,30 @@ class ESMModel(AttnModel, EmbeddingModel): "esmc-600m", "esmc-6b", ] + + def single_site(self, sequence: bytes | str) -> EmbeddingsScoreSingleSiteFuture: + """ + Score all single substitutions of a sequence. + + Masks each position in turn and scores every substitution there + against the wild-type residue. The wild type therefore scores 0, and a + positive score means the model prefers the substitution. + + Parameters + ---------- + sequence : bytes or str + Sequence to analyze. + + Returns + ------- + EmbeddingsScoreSingleSiteFuture + Future object that returns the per-variant scores of the single substitutions. + """ + return EmbeddingsScoreSingleSiteFuture.create( + session=self.session, + job=api.request_score_single_site_post( + session=self.session, + model_id=self.id, + base_sequence=sequence, + ), + ) diff --git a/openprotein/embeddings/future.py b/openprotein/embeddings/future.py index 62485d1..6d85209 100644 --- a/openprotein/embeddings/future.py +++ b/openprotein/embeddings/future.py @@ -1,29 +1,36 @@ """Future for embeddings-related jobs.""" from collections import namedtuple -from typing import Any, Generator, Iterator, TypeVar, Union +from typing import Iterator, TypeVar, Union import numpy as np from openprotein import config - -"""Embeddings results represented as futures.""" - from openprotein.base import APISession -from openprotein.jobs import Future, MappedFuture, StreamingFuture +from openprotein.jobs import MappedFuture, StreamingFuture from . import api from .schemas import ( AttnJob, EmbeddingsJob, GenerateJob, - JobType, LogitsJob, ScoreIndelJob, ScoreJob, ScoreSingleSiteJob, ) +__all__ = [ + "BaseScoreFuture", + "EmbeddingsGenerateFuture", + "EmbeddingsResultFuture", + "EmbeddingsScoreFuture", + "EmbeddingsScoreSingleSiteFuture", + "S", + "Score", + "SingleSiteScore", +] + class EmbeddingsResultFuture(MappedFuture[bytes, np.ndarray]): """Future for manipulating results for embeddings-related requests.""" @@ -38,7 +45,6 @@ def __init__( max_workers: int = config.MAX_CONCURRENT_WORKERS, ): super().__init__(session=session, job=job, max_workers=max_workers) - # ensure all list[bytes] self._sequences = ( [seq.encode() if isinstance(seq, str) else seq for seq in sequences] if sequences is not None @@ -47,7 +53,7 @@ def __init__( def stream_sync(self): """ - Stream the embeddings results synchronously using the streaming endpoint. + Stream the embeddings results synchronously. """ for i, array in enumerate( api.request_get_embeddings_stream(session=self.session, job_id=self.id) @@ -81,11 +87,16 @@ def get_item(self, sequence: str | bytes) -> np.ndarray: """ Get embedding results for specified sequence. - Args: - sequence (str | bytes): sequence to fetch results for + Parameters + ---------- + sequence : str or bytes + One of the sequences submitted with the request. - Returns: - np.ndarray: embeddings + Returns + ------- + np.ndarray + Embedding for that sequence. The shape depends on the model and on + the reduction requested at submission time. """ data = api.request_get_sequence_result( session=self.session, @@ -113,7 +124,6 @@ def __init__( sequences: list[bytes] | list[str] | None = None, ): super().__init__(session=session, job=job) - # ensure all list[bytes] self._sequences = ( [seq.encode() if isinstance(seq, str) else seq for seq in sequences] if sequences is not None diff --git a/openprotein/embeddings/models.py b/openprotein/embeddings/models.py index ca08531..4ef7367 100644 --- a/openprotein/embeddings/models.py +++ b/openprotein/embeddings/models.py @@ -4,13 +4,12 @@ from openprotein.base import APISession from openprotein.common import ( - Feature, FeatureType, ModelMetadata, Reduction, ReductionType, ) -from openprotein.data import AssayDataset, AssayMetadata, DataAPI +from openprotein.data import AssayDataset, AssayMetadata from openprotein.errors import InvalidParameterError from . import api @@ -22,6 +21,8 @@ from openprotein.svd import SVDModel from openprotein.umap import UMAPModel +__all__ = ["AttnModel", "EmbeddingModel"] + class EmbeddingModel: """Base embeddings model used to understand and provide embeddings from sequences.""" @@ -104,19 +105,19 @@ def create( ValueError If no suitable EmbeddingModel subclass is found and no default is provided. """ - # Dynamically discover all subclasses of EmbeddingModel model_classes = EmbeddingModel.__subclasses__() - # Find the EmbeddingModel class that matches the model_id for model_class in model_classes: if model_id in model_class.get_model(): - return model_class(session=session, model_id=model_id, metadata=metadata, **kwargs) - # default to ProtembedModel + return model_class( + session=session, model_id=model_id, metadata=metadata, **kwargs + ) if default is not None: try: - return default(session=session, model_id=model_id, metadata=metadata, **kwargs) + return default( + session=session, model_id=model_id, metadata=metadata, **kwargs + ) except: - # continue to throw error as unsupported pass raise ValueError(f"Unsupported model_id type: {model_id}") @@ -251,7 +252,6 @@ def fit_svd( # local import for cyclic dep from openprotein.svd import SVDAPI - # runtime check on value if isinstance(reduction, str): reduction = ReductionType(reduction) reduction = reduction.value @@ -259,7 +259,6 @@ def fit_svd( svd_api = getattr(self.session, "svd", None) assert isinstance(svd_api, SVDAPI) - # Ensure either or if (assay is None and sequences is None) or ( assay is not None and sequences is not None ): @@ -320,7 +319,6 @@ def fit_umap( "Expected reduction if using EmbeddingModel to fit UMAP" ) - # runtime check on value if isinstance(reduction, str): reduction = ReductionType(reduction) reduction = reduction.value @@ -328,14 +326,12 @@ def fit_umap( umap_api = getattr(self.session, "umap", None) assert isinstance(umap_api, UMAPAPI) - # Ensure either or if (assay is None and sequences is None) or ( assay is not None and sequences is not None ): raise InvalidParameterError( "Expected either assay or sequences to fit UMAP on!" ) - # get assay_id return umap_api.fit_umap( model=self, reduction=reduction, @@ -400,7 +396,6 @@ def fit_gp( predictor_api = getattr(self.session, "predictor", None) assert isinstance(predictor_api, PredictorAPI) - # inject into predictor api return predictor_api.fit_gp( assay=assay, properties=properties, diff --git a/openprotein/embeddings/openprotein.py b/openprotein/embeddings/openprotein.py index ffa3c5c..79755c1 100644 --- a/openprotein/embeddings/openprotein.py +++ b/openprotein/embeddings/openprotein.py @@ -2,6 +2,8 @@ from .models import AttnModel, EmbeddingModel +__all__ = ["OpenProteinModel"] + class OpenProteinModel(AttnModel, EmbeddingModel): """ @@ -18,4 +20,4 @@ class OpenProteinModel(AttnModel, EmbeddingModel): >>> session.embedding.prot_seq? """ - model_id = ["prot-seq", "rotaprot-large-uniref50w", "rotaprot_large_uniref90_ft"] + model_id = ["prot-seq", "rotaprot-large-uniref50w", "rotaprot-large-uniref90-ft"] diff --git a/openprotein/embeddings/poet.py b/openprotein/embeddings/poet.py index afcf5d3..ab8bb79 100644 --- a/openprotein/embeddings/poet.py +++ b/openprotein/embeddings/poet.py @@ -5,6 +5,7 @@ from openprotein.base import APISession from openprotein.common import ModelMetadata, Reduction, ReductionType from openprotein.data import AssayDataset, AssayMetadata +from openprotein.data.prompts import Prompt as StoredPrompt from openprotein.prompt import Prompt from . import api @@ -22,6 +23,8 @@ from openprotein.svd import SVDModel from openprotein.umap import UMAPModel +__all__ = ["PoETModel"] + class PoETModel(EmbeddingModel): """ @@ -55,7 +58,7 @@ def embed( self, sequences: list[bytes] | list[str], reduction: ReductionType | None = ReductionType.MEAN, - prompt: str | Prompt | None = None, + prompt: str | Prompt | StoredPrompt | None = None, **kwargs, ) -> EmbeddingsResultFuture: """ @@ -97,7 +100,7 @@ def embed( def logits( self, sequences: list[bytes] | list[str], - prompt: str | Prompt | None = None, + prompt: str | Prompt | StoredPrompt | None = None, **kwargs, ) -> EmbeddingsResultFuture: """ @@ -145,7 +148,7 @@ def attn(self): def score( self, sequences: list[bytes], - prompt: str | Prompt | None = None, + prompt: str | Prompt | StoredPrompt | None = None, **kwargs, ) -> EmbeddingsScoreFuture: """ @@ -183,7 +186,7 @@ def score( def indel( self, sequence: bytes, - prompt: str | Prompt | None = None, + prompt: str | Prompt | StoredPrompt | None = None, insert: str | None = None, delete: list[int] | None = None, **kwargs, @@ -236,7 +239,7 @@ def indel( def single_site( self, sequence: bytes, - prompt: str | Prompt | None = None, + prompt: str | Prompt | StoredPrompt | None = None, **kwargs, ) -> EmbeddingsScoreSingleSiteFuture: """ @@ -273,7 +276,7 @@ def single_site( def generate( self, - prompt: str | Prompt, + prompt: str | Prompt | StoredPrompt, num_samples: int = 100, temperature: float = 1.0, topk: float | None = None, @@ -335,7 +338,7 @@ def fit_svd( assay: AssayDataset | AssayMetadata | None = None, n_components: int = 1024, reduction: Reduction | ReductionType | None = None, - prompt: str | Prompt | None = None, + prompt: str | Prompt | StoredPrompt | None = None, **kwargs, ) -> "SVDModel": """ @@ -383,7 +386,7 @@ def fit_umap( assay: AssayDataset | AssayMetadata | None = None, n_components: int = 2, reduction: Reduction | ReductionType = ReductionType.MEAN, - prompt: str | Prompt | None = None, + prompt: str | Prompt | StoredPrompt | None = None, **kwargs, ) -> "UMAPModel": """ @@ -432,7 +435,7 @@ def fit_gp( reduction: ReductionType, name: str | None = None, description: str | None = None, - prompt: str | Prompt | None = None, + prompt: str | Prompt | StoredPrompt | None = None, kernel: "KernelType | str" = "rbf", period: float | None = None, alpha: float | None = None, diff --git a/openprotein/embeddings/poet2.py b/openprotein/embeddings/poet2.py index 9a601e3..6c1bdac 100644 --- a/openprotein/embeddings/poet2.py +++ b/openprotein/embeddings/poet2.py @@ -8,6 +8,8 @@ from openprotein.base import APISession from openprotein.common import ModelMetadata, ReductionType from openprotein.data import AssayDataset, AssayMetadata +from openprotein.data.prompts import Prompt as StoredPrompt +from openprotein.errors import InvalidParameterError from openprotein.molecules import Complex, Protein from openprotein.prompt import Prompt, PromptAPI, Query @@ -21,12 +23,21 @@ from .poet import PoETModel if TYPE_CHECKING: - from openprotein.predictor.schemas import KernelType from openprotein.models.structure_generation import StructureGenerationFuture from openprotein.predictor import PredictorModel + from openprotein.predictor.schemas import KernelType from openprotein.svd import SVDModel from openprotein.umap import UMAPModel +__all__ = ["PoET2Model"] + + +def _reject_mlm_decoder(decoder_type: str | None) -> None: + if decoder_type == "mlm": + raise InvalidParameterError( + "`decoder_type` cannot be `mlm` for scoring; PoET-2 scores with the `clm` decoder" + ) + class PoET2Model(PoETModel, EmbeddingModel): """ @@ -38,8 +49,6 @@ class PoET2Model(PoETModel, EmbeddingModel): -------- View specific model details (including supported tokens) with the `?` operator. - Examples - -------- .. code-block:: ipython3 >>> import openprotein @@ -62,7 +71,7 @@ def embed( self, sequences: list[bytes] | list[str], reduction: ReductionType | None = ReductionType.MEAN, - prompt: str | Prompt | None = None, + prompt: str | Prompt | StoredPrompt | None = None, query: str | bytes | Protein | Complex | Query | None = None, use_query_structure_in_decoder: bool = True, decoder_type: Literal["mlm", "clm"] | None = None, @@ -115,7 +124,7 @@ def embed( def logits( self, sequences: list[bytes] | list[str], - prompt: str | Prompt | None = None, + prompt: str | Prompt | StoredPrompt | None = None, query: str | bytes | Protein | Complex | Query | None = None, use_query_structure_in_decoder: bool = True, decoder_type: Literal["mlm", "clm"] | None = None, @@ -165,10 +174,10 @@ def logits( def score( self, sequences: list[bytes], - prompt: str | Prompt | None = None, + prompt: str | Prompt | StoredPrompt | None = None, query: str | bytes | Protein | Complex | Query | None = None, use_query_structure_in_decoder: bool = True, - decoder_type: Literal["mlm", "clm"] | None = None, + decoder_type: Literal["clm"] | None = None, **kwargs, ) -> EmbeddingsScoreFuture: """ @@ -184,8 +193,8 @@ def score( Query to use with prompt. use_query_structure_in_decoder : bool, optional Whether to use query structure in decoder. Default is True. - decoder_type : {'mlm', 'clm'} or None, optional - Decoder type. Default is None. + decoder_type : {'clm'} or None, optional + Decoder type. Scoring runs on the `clm` decoder. Default is None. **kwargs Additional keyword arguments. @@ -194,6 +203,7 @@ def score( EmbeddingsScoreFuture A future object that returns the scores of the submitted sequences. """ + _reject_mlm_decoder(decoder_type) prompt_api = getattr(self.session, "prompt", None) assert isinstance(prompt_api, PromptAPI) query_id = prompt_api._resolve_query(query=query) @@ -209,10 +219,10 @@ def score( def indel( self, sequence: bytes, - prompt: str | Prompt | None = None, + prompt: str | Prompt | StoredPrompt | None = None, query: str | bytes | Protein | Complex | Query | None = None, use_query_structure_in_decoder: bool = True, - decoder_type: Literal["mlm", "clm"] | None = None, + decoder_type: Literal["clm"] | None = None, insert: str | None = None, delete: list[int] | None = None, **kwargs, @@ -230,8 +240,8 @@ def indel( Query to use with prompt. use_query_structure_in_decoder : bool, optional Whether to use query structure in decoder. Default is True. - decoder_type : {'mlm', 'clm'} or None, optional - Decoder type. Default is None. + decoder_type : {'clm'} or None, optional + Decoder type. Scoring runs on the `clm` decoder. Default is None. insert : str or None, optional Insertion fragment at each site. delete : list of int or None, optional @@ -249,6 +259,7 @@ def indel( ValueError If neither insert nor delete is provided. """ + _reject_mlm_decoder(decoder_type) prompt_api = getattr(self.session, "prompt", None) assert isinstance(prompt_api, PromptAPI) query_id = prompt_api._resolve_query(query=query) @@ -266,10 +277,10 @@ def indel( def single_site( self, sequence: bytes, - prompt: str | Prompt | None = None, + prompt: str | Prompt | StoredPrompt | None = None, query: str | bytes | Protein | Complex | Query | None = None, use_query_structure_in_decoder: bool = True, - decoder_type: Literal["mlm", "clm"] | None = None, + decoder_type: Literal["clm"] | None = None, **kwargs, ) -> EmbeddingsScoreSingleSiteFuture: """ @@ -285,8 +296,8 @@ def single_site( Query to use with prompt. use_query_structure_in_decoder : bool, optional Whether to use query structure in decoder. Default is True. - decoder_type : {'mlm', 'clm'} or None, optional - Decoder type. Default is None. + decoder_type : {'clm'} or None, optional + Decoder type. Scoring runs on the `clm` decoder. Default is None. **kwargs Additional keyword arguments. @@ -295,6 +306,7 @@ def single_site( EmbeddingsScoreFuture A future object that returns the scores of the mutated sequence. """ + _reject_mlm_decoder(decoder_type) prompt_api = getattr(self.session, "prompt", None) assert isinstance(prompt_api, PromptAPI) query_id = prompt_api._resolve_query(query=query) @@ -309,7 +321,7 @@ def single_site( def generate( self, - prompt: str | Prompt | None, + prompt: str | Prompt | StoredPrompt | None, query: ( str | bytes @@ -414,7 +426,7 @@ def fit_svd( assay: AssayDataset | None = None, n_components: int = 1024, reduction: ReductionType | None = None, - prompt: str | Prompt | None = None, + prompt: str | Prompt | StoredPrompt | None = None, query: str | bytes | Protein | Complex | Query | None = None, use_query_structure_in_decoder: bool = True, decoder_type: Literal["mlm", "clm"] | None = None, @@ -473,7 +485,7 @@ def fit_umap( assay: AssayDataset | None = None, n_components: int = 2, reduction: ReductionType = ReductionType.MEAN, - prompt: str | Prompt | None = None, + prompt: str | Prompt | StoredPrompt | None = None, query: str | bytes | Protein | Complex | Query | None = None, use_query_structure_in_decoder: bool = True, decoder_type: Literal["mlm", "clm"] | None = None, @@ -530,7 +542,7 @@ def fit_gp( self, assay: AssayMetadata | AssayDataset | str, properties: list[str], - prompt: str | Prompt | None = None, + prompt: str | Prompt | StoredPrompt | None = None, query: str | bytes | Protein | Complex | Query | None = None, use_query_structure_in_decoder: bool = True, decoder_type: Literal["mlm", "clm"] | None = None, diff --git a/openprotein/embeddings/schemas.py b/openprotein/embeddings/schemas.py index 4f72df4..614f952 100644 --- a/openprotein/embeddings/schemas.py +++ b/openprotein/embeddings/schemas.py @@ -7,6 +7,17 @@ from openprotein.jobs import BatchJob, Job, JobType +__all__ = [ + "AttnJob", + "EmbeddedSequence", + "EmbeddingsJob", + "GenerateJob", + "LogitsJob", + "ScoreIndelJob", + "ScoreJob", + "ScoreSingleSiteJob", +] + class EmbeddedSequence(BaseModel): """ @@ -36,45 +47,38 @@ def __getitem__(self, i): class EmbeddingsJob(Job, BatchJob): - job_type: Literal[JobType.embeddings_embed, JobType.embeddings_embed_reduced] = ( Field(default=JobType.embeddings_embed) ) class AttnJob(Job, BatchJob): - job_type: Literal[JobType.embeddings_attn] = Field(default=JobType.embeddings_attn) class LogitsJob(Job, BatchJob): - job_type: Literal[JobType.embeddings_logits] = Field( default=JobType.embeddings_logits ) class ScoreJob(Job, BatchJob): - job_type: Literal[JobType.poet_score] = Field(default=JobType.poet_score) class ScoreIndelJob(Job, BatchJob): - job_type: Literal[JobType.poet_score_indel] = Field( default=JobType.poet_score_indel ) class ScoreSingleSiteJob(Job, BatchJob): - job_type: Literal[JobType.poet_single_site] = Field( default=JobType.poet_single_site ) class GenerateJob(Job, BatchJob): - job_type: Literal[JobType.poet_generate, JobType.embeddings_generate] = Field( default=JobType.poet_generate ) diff --git a/openprotein/errors.py b/openprotein/errors.py index 752344e..470ab6b 100644 --- a/openprotein/errors.py +++ b/openprotein/errors.py @@ -1,14 +1,28 @@ from pydantic import BaseModel from requests import Response -UPGRADE_MESSAGE = ( - "If this issue persists, try upgrading the client: pip install --upgrade openprotein-python" -) +__all__ = [ + "APIError", + "AuthError", + "DeprecationError", + "HTTPError", + "InvalidJob", + "InvalidParameterError", + "JobFailedException", + "JobOutputsNotReady", + "MissingParameterError", + "NoJobError", + "NotPrepared", + "RawAPIError", + "TimeoutException", +] + + +_UPGRADE_MESSAGE = "If this issue persists, try upgrading the client: pip install --upgrade openprotein-python" -# Errors for OpenProtein class InvalidParameterError(Exception): - """InvalidParameterError""" + """Raised when a parameter has an invalid value.""" def __init__(self, message="Invalid parameter"): self.message = message @@ -16,7 +30,7 @@ def __init__(self, message="Invalid parameter"): class MissingParameterError(Exception): - """MissingParameterError""" + """Raised when a required parameter is not provided.""" def __init__(self, message="Required parameter is missing"): self.message = message @@ -24,15 +38,14 @@ def __init__(self, message="Required parameter is missing"): class RawAPIError(BaseModel): - detail: str class APIError(Exception): - """APIError""" + """Raised when the API returns an error.""" def __init__(self, message: str): - self.message = f"{message}\n{UPGRADE_MESSAGE}" + self.message = f"{message}\n{_UPGRADE_MESSAGE}" super().__init__(self.message) @@ -48,8 +61,16 @@ def __init__(self, response: Response): super().__init__(message) +class JobOutputsNotReady(APIError): + """A job's named output is not complete yet.""" + + def __init__(self, message: str): + self.message = message + Exception.__init__(self, message) + + class AuthError(Exception): - """InvalidParameterError""" + """Raised when authentication fails.""" def __init__(self, message="Invalid authorization"): self.message = message @@ -57,15 +78,23 @@ def __init__(self, message="Invalid authorization"): class InvalidJob(Exception): - """InvalidParameterError""" + """Raised when a job cannot be found or is not valid for the request.""" def __init__(self, message="No such job"): self.message = message super().__init__(self.message) +class NotPrepared(Exception): + """A job's units are not listed yet.""" + + def __init__(self, job_id: str): + self.job_id = job_id + super().__init__(f"job {job_id} has not been prepared yet") + + class TimeoutException(Exception): - """InvalidParameterError""" + """Raised when waiting on a job or request times out.""" def __init__(self, message="Request timed out!"): self.message = message @@ -89,6 +118,10 @@ def __init__( super().__init__(self.message) +class NoJobError(AttributeError): + """A stored row that no job made, such as an upload, has no job fields.""" + + class DeprecationError(Exception): """DeprecationError used for flagging to the user to not use this interface anymore.""" diff --git a/openprotein/fasta.py b/openprotein/fasta.py index a999adc..0a1990a 100644 --- a/openprotein/fasta.py +++ b/openprotein/fasta.py @@ -1,5 +1,7 @@ from typing import Iterator, Sequence, overload +__all__ = ["parse", "parse_stream"] + @overload def parse_stream( @@ -22,7 +24,7 @@ def parse_stream( for line in lines: if not line: - continue # skip empty lines + continue if is_bytes := isinstance(line, bytes): line = line.decode() if line.startswith(comment): diff --git a/openprotein/fold/__init__.py b/openprotein/fold/__init__.py index cae50f4..0a5430b 100644 --- a/openprotein/fold/__init__.py +++ b/openprotein/fold/__init__.py @@ -18,11 +18,17 @@ from .future import FoldResultFuture from .minifold import MiniFoldModel from .models import FoldModel +from .opendde import ( + OpenDDEAbagModel, + OpenDDEConfidence, + OpenDDEModel, +) from .protenix import ProtenixConfidence, ProtenixModel, ProtenixV2Model from .rosettafold3 import RosettaFold3Model -from .schemas import FoldJob, FoldMetadata +from .schemas import FoldConfidence, FoldJob, FoldMetadata __all__ = [ + "FoldConfidence", "FoldJob", "FoldMetadata", "FoldModel", @@ -32,9 +38,6 @@ "ESMFold2Confidence", "MiniFoldModel", "AlphaFold2Model", - "ProtenixConfidence", - "ProtenixModel", - "ProtenixV2Model", "Boltz1Model", "Boltz1xModel", "Boltz2Model", @@ -42,7 +45,13 @@ "BoltzConfidence", "BoltzConstraint", "BoltzProperty", - "RosettaFold3Model", - "FoldResultFuture", "FoldAPI", + "FoldResultFuture", + "OpenDDEAbagModel", + "OpenDDEConfidence", + "OpenDDEModel", + "ProtenixConfidence", + "ProtenixModel", + "ProtenixV2Model", + "RosettaFold3Model", ] diff --git a/openprotein/fold/_request.py b/openprotein/fold/_request.py new file mode 100644 index 0000000..99d4c57 --- /dev/null +++ b/openprotein/fold/_request.py @@ -0,0 +1,181 @@ +"""The fold request contract: the entities of a complex and their chain wrappers. + +A fold request carries ``complexes``, a list of complexes, each a list of +chains. A chain names exactly one entity; the wrapper classes scope which +entity types a model accepts. +""" + +import re +from collections.abc import Sequence +from typing import Annotated, Any +from uuid import UUID + +from pydantic import ( + AfterValidator, + BaseModel, + ConfigDict, + Field, + field_validator, + model_validator, +) + +CHAIN_ID = re.compile(r"[A-Za-z0-9]{1,5}") + + +def _check_chain_id(value: str | list[str]) -> str | list[str]: + ids = [value] if isinstance(value, str) else value + if not ids: + raise ValueError("an entity needs at least one chain id") + for chain_id in ids: + if not CHAIN_ID.fullmatch(chain_id): + raise ValueError( + f"invalid chain id {chain_id!r}: expected one to five letters or digits" + ) + return value + + +ChainId = Annotated[ + str | list[str], + AfterValidator(_check_chain_id), + Field(description="Unique chain identifier(s); a list for identical chains."), +] + + +class _Entity(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class Protein(_Entity): + """Protein chain to fold.""" + + id: ChainId + sequence: str + + +class ProteinWithMSA(Protein): + """Protein chain to fold, with an optional MSA.""" + + msa_id: UUID | None = None + + +class DNA(_Entity): + """DNA chain to fold.""" + + id: ChainId + sequence: str + + +class RNA(_Entity): + """RNA chain to fold, with an optional MSA.""" + + id: ChainId + sequence: str + msa_id: UUID | None = None + + +class Ligand(_Entity): + """Small-molecule ligand, given as exactly one of SMILES or CCD code.""" + + id: ChainId + smiles: str | None = None + ccd: str | None = None + + @field_validator("smiles", "ccd", mode="before") + @classmethod + def _empty_string_is_absent(cls, value: Any) -> Any: + return None if value == "" else value + + @model_validator(mode="after") + def _one_of_smiles_or_ccd(self) -> "Ligand": + if (self.smiles is None) == (self.ccd is None): + raise ValueError("a ligand needs exactly one of smiles or ccd") + return self + + +Entity = Protein | DNA | RNA | Ligand + + +class _Chain(BaseModel): + model_config = ConfigDict(extra="forbid") + + @model_validator(mode="after") + def _one_entity(self) -> "_Chain": + named = [name for name in type(self).model_fields if getattr(self, name)] + if len(named) != 1: + raise ValueError("a chain names exactly one entity") + return self + + @property + def entity(self) -> Entity: + """The one entity this chain names.""" + for name in type(self).model_fields: + if (entity := getattr(self, name)) is not None: + return entity + raise AssertionError("validated chain names an entity") + + +class MsaChain(_Chain): + """A chain: protein (with MSA), ligand, DNA, or RNA.""" + + protein: ProteinWithMSA | None = None + ligand: Ligand | None = None + dna: DNA | None = None + rna: RNA | None = None + + +class NoMsaChain(_Chain): + """A chain for single-sequence models: protein (no MSA), ligand, DNA, or RNA.""" + + protein: Protein | None = None + ligand: Ligand | None = None + dna: DNA | None = None + rna: RNA | None = None + + +class ProteinChain(_Chain): + """A protein-only chain (no MSA).""" + + protein: Protein | None = None + + +class MsaProteinChain(_Chain): + """A protein-only chain, with an optional MSA.""" + + protein: ProteinWithMSA | None = None + + +class MsaProteinLigandChain(_Chain): + """A protein (with optional MSA) or ligand chain.""" + + protein: ProteinWithMSA | None = None + ligand: Ligand | None = None + + +def complex_chain_ids(chains: Sequence[_Chain]) -> list[str]: + """Return one id per chain of a complex, in request order with copies expanded. + + A complex's fold outputs name their chains with it. + + Parameters + ---------- + chains : sequence of chain + The validated chains of one complex. + + Returns + ------- + list of str + The ``chain_ids`` of the complex's fold outputs. + + Raises + ------ + ValueError + If an id repeats within the complex. + """ + ids: list[str] = [] + for chain in chains: + entity_ids = chain.entity.id + for chain_id in [entity_ids] if isinstance(entity_ids, str) else entity_ids: + if chain_id in ids: + raise ValueError(f"duplicate chain id {chain_id!r}") + ids.append(chain_id) + return ids diff --git a/openprotein/fold/alphafold2.py b/openprotein/fold/alphafold2.py index 90ffea9..7e69d1e 100644 --- a/openprotein/fold/alphafold2.py +++ b/openprotein/fold/alphafold2.py @@ -1,22 +1,24 @@ """Community-based AlphaFold 2 model running using ColabFold.""" import warnings -from typing import Sequence from openprotein.align import MSAFuture from openprotein.base import APISession from openprotein.common import ModelMetadata from openprotein.fold.common import ( + FoldInput, msa_future_to_complex, normalize_inputs, serialize_input, ) -from openprotein.molecules import DNA, RNA, Complex, Ligand, Protein +from openprotein.molecules import DNA, RNA, Ligand from . import api from .future import FoldResultFuture from .models import FoldModel +__all__ = ["AlphaFold2Model"] + class AlphaFold2Model(FoldModel): """ @@ -35,7 +37,7 @@ def __init__( def fold( self, - sequences: Sequence[Complex | Protein | str | bytes] | MSAFuture, + sequences: FoldInput | MSAFuture, num_recycles: int | None = None, num_models: int = 1, num_relax: int = 0, @@ -46,8 +48,8 @@ def fold( Parameters ---------- - sequences : Sequence[Complex | Protein | str | bytes] | MSAFuture - List of protein sequences to include in folded output. `Protein` objects must be tagged with an `msa`, which can be a `Protein.single_sequence_mode` for single sequence mode. Alternatively, supply an `MSAFuture` to use all query sequences as a multimer. + sequences : FoldInput | MSAFuture + Complexes to fold, or a lone complex/protein/sequence. `Protein` objects must be tagged with an `msa`, which can be a `Protein.single_sequence_mode` for single sequence mode. Alternatively, supply an `MSAFuture` to use all query sequences as a multimer. num_recycles : int number of times to recycle models num_models : int @@ -70,7 +72,6 @@ def fold( if sequences is None: raise TypeError("Expected 'proteins' argument") - # build the normalized_models from msa if isinstance(sequences, MSAFuture): normalized_complexes = [msa_future_to_complex(self.session, sequences)] @@ -85,7 +86,7 @@ def fold( or isinstance(chain, Ligand) ): with warnings.catch_warnings(): - warnings.simplefilter("always") # Force warning to always show + warnings.simplefilter("always") warnings.warn( "AlphaFold-2 does not support ligand/DNA/RNA input. These extra chains will be ignored in the output." ) diff --git a/openprotein/fold/api.py b/openprotein/fold/api.py index b2ea4b6..281a06f 100644 --- a/openprotein/fold/api.py +++ b/openprotein/fold/api.py @@ -17,7 +17,19 @@ if TYPE_CHECKING: import pandas as pd -PATH_PREFIX = "v1/fold" +__all__ = [ + "fold_get", + "fold_get_batch_extra_result", + "fold_get_extra_result", + "fold_get_sequence_result", + "fold_get_sequences", + "fold_model_get", + "fold_models_list_get", + "fold_models_post", +] + + +_PATH_PREFIX = "v1/fold" def fold_models_list_get(session: APISession) -> list[str]: @@ -34,7 +46,7 @@ def fold_models_list_get(session: APISession) -> list[str]: list of str List of model names. """ - endpoint = PATH_PREFIX + "/models" + endpoint = _PATH_PREFIX + "/models" response = session.get(endpoint) result = response.json() return result @@ -56,7 +68,7 @@ def fold_model_get(session: APISession, model_id: str) -> ModelMetadata: ModelMetadata Metadata for the specified model. """ - endpoint = PATH_PREFIX + f"/models/{model_id}" + endpoint = _PATH_PREFIX + f"/models/{model_id}" response = session.get(endpoint) result = response.json() return ModelMetadata(**result) @@ -78,7 +90,7 @@ def fold_get(session: APISession, job_id: str) -> FoldMetadata: FoldMetadata Metadata about the fold job. """ - endpoint = PATH_PREFIX + f"/{job_id}" + endpoint = _PATH_PREFIX + f"/{job_id}" response = session.get(endpoint) fold = FoldMetadata.model_validate(response.json()) return fold @@ -100,7 +112,7 @@ def fold_get_sequences(session: APISession, job_id: str) -> list[bytes]: list of bytes List of sequences as bytes. """ - endpoint = PATH_PREFIX + f"/{job_id}/sequences" + endpoint = _PATH_PREFIX + f"/{job_id}/sequences" response = session.get(endpoint) return TypeAdapter(list[bytes]).validate_python(response.json()) @@ -130,7 +142,7 @@ def fold_get_sequence_result( """ if isinstance(sequence_or_index, bytes): sequence_or_index = sequence_or_index.decode() - endpoint = PATH_PREFIX + f"/{job_id}/{sequence_or_index}" + endpoint = _PATH_PREFIX + f"/{job_id}/{sequence_or_index}" response = session.get(endpoint, params={"format": format}) return response.content @@ -225,7 +237,7 @@ def formatter(response): else: raise ValueError(f"Unexpected key: {key}") - endpoint = PATH_PREFIX + f"/{job_id}/{sequence_or_index}/{key}" + endpoint = _PATH_PREFIX + f"/{job_id}/{sequence_or_index}/{key}" try: response = session.get( endpoint, @@ -270,12 +282,11 @@ def fold_get_batch_extra_result( """ Fetch an extra result key stacked across every unit in a fold job. - Backed by a single server call to ``/v1/fold/{job_id}/results/{key}`` - (not N per-unit calls). For ``.npy`` keys the server pads per-unit - arrays with NaN to the per-axis max shape and stacks along a new - leading dim; for ``.json`` keys it returns a length-``N`` array where - element ``i`` is unit ``i``'s parsed JSON (``None`` if that unit's - result was missing or failed to fetch). + For ``.npy`` keys, per-unit arrays are padded with NaN to the per-axis + max shape and stacked along a new leading dim. For ``.json`` keys, the + result is a length-``N`` array where element ``i`` is unit ``i``'s + parsed JSON (``None`` if that unit's result was missing or failed to + fetch). Parameters ---------- @@ -306,7 +317,7 @@ def formatter(response): else: raise ValueError(f"Unexpected key: {key}") - endpoint = PATH_PREFIX + f"/{job_id}/results/{key}" + endpoint = _PATH_PREFIX + f"/{job_id}/results/{key}" try: response = session.get(endpoint) except HTTPError as e: @@ -319,7 +330,7 @@ def formatter(response): def fold_models_post( session: APISession, model_id: str, - sequences: Sequence[Sequence[Mapping[str, Any]]], + sequences: Sequence[Sequence[Mapping[str, Any]]] | None = None, **kwargs, ) -> FoldJob: """ @@ -334,11 +345,12 @@ def fold_models_post( Session object for API communication. model_id : str Model ID to use for prediction. - sequences : sequence of sequence of dict + sequences : sequence of sequence of dict or None Sequences/complexes to request results for. The outer list represents the batch of requests, and the inner list represents the complex, with each item in the list being an entity in that complex. A monomer would thus be a single item. + Omitted for models that derive the sequence server-side. **kwargs Additional keyword arguments to be sent with POST body. @@ -347,12 +359,11 @@ def fold_models_post( FoldJob Job object referring to this request. """ - endpoint = PATH_PREFIX + f"/models/{model_id}" + endpoint = _PATH_PREFIX + f"/models/{model_id}" - body: dict = { - "sequences": sequences, - } - # add non-None args + body: dict = {} + if sequences is not None: + body["sequences"] = sequences for k, v in kwargs.items(): if v is not None: body[k] = v diff --git a/openprotein/fold/boltz.py b/openprotein/fold/boltz.py index 96e0ba4..f892990 100644 --- a/openprotein/fold/boltz.py +++ b/openprotein/fold/boltz.py @@ -1,7 +1,7 @@ """Community-based Boltz models for complex structure prediction with ligands/dna/rna.""" import warnings -from typing import Mapping, Sequence +from collections.abc import Mapping, Sequence from pydantic import BaseModel, TypeAdapter, model_validator @@ -9,6 +9,8 @@ from openprotein.base import APISession from openprotein.common import ModelMetadata from openprotein.fold.common import ( + FoldInput, + _as_entities, msa_future_to_complex, normalize_inputs, normalize_templates, @@ -22,6 +24,21 @@ from .future import FoldResultFuture from .models import FoldModel +__all__ = [ + "AffinityProperty", + "Boltz1Model", + "Boltz1xModel", + "Boltz2Model", + "BoltzAffinity", + "BoltzConfidence", + "BoltzConstraint", + "BoltzModel", + "BoltzProperty", + "BondConstraint", + "ContactConstraint", + "PocketConstraint", +] + class BoltzModel(FoldModel): """ @@ -40,13 +57,15 @@ def __init__( def fold( self, - sequences: Sequence[Complex | Protein | str | bytes] | MSAFuture, + sequences: FoldInput | MSAFuture, diffusion_samples: int = 1, num_recycles: int = 3, num_steps: int = 200, step_scale: float = 1.638, use_potentials: bool = False, constraints: Sequence[Mapping] | None = None, + *, + seed: int | None = None, **kwargs, ) -> FoldResultFuture: """ @@ -54,8 +73,8 @@ def fold( Parameters ---------- - sequences : Sequence[Complex | Protein | str | bytes] | MSAFuture - List of protein complexes to include in folded output. `Protein` objects must be tagged with an `msa`, which can be a `Protein.single_sequence_mode` for single sequence mode. Alternatively, supply an `MSAFuture` to use all query sequences as a multimer. + sequences : FoldInput | MSAFuture + Complexes to fold, or a lone complex/protein/sequence. `Protein` objects must be tagged with an `msa`, which can be a `Protein.single_sequence_mode` for single sequence mode. Alternatively, supply an `MSAFuture` to use all query sequences as a multimer. diffusion_samples: int Number of diffusion samples to use num_recycles : int @@ -66,13 +85,17 @@ def fold( Scaling factor for diffusion steps. constraints : Optional[List[dict]] List of constraints. + seed : int | None + Seed for the prediction, from 0 to 2**31 - 1. None lets the model + pick its own, so every call is a fresh prediction. Folding the + same input with the same seed returns the same structures. Returns ------- FoldResultFuture Future for the folding complex result. """ - # migrate old parameter + # deprecated parameter names if (recycling_steps := kwargs.get("recycling_steps")) is not None: num_recycles = recycling_steps warnings.warn( @@ -83,11 +106,9 @@ def fold( warnings.warn( "`sampling_steps` has been updated to `num_steps`. The parameter will be auto-corrected for now but raise an exception in the future." ) - # validate constraints if constraints is not None: TypeAdapter(list[BoltzConstraint]).validate_python(constraints) - # build the normalized_models from msa if isinstance(sequences, MSAFuture): normalized_complexes = [msa_future_to_complex(self.session, sequences)] else: @@ -112,6 +133,7 @@ def fold( step_scale=step_scale, constraints=constraints, use_potentials=use_potentials, + seed=seed, **kwargs, ), complexes=normalized_complexes, @@ -127,7 +149,7 @@ class Boltz2Model(BoltzModel, FoldModel): def fold( self, - sequences: Sequence[Complex | Protein | str | bytes] | MSAFuture, + sequences: FoldInput | MSAFuture, diffusion_samples: int = 1, num_recycles: int = 3, num_steps: int = 200, @@ -137,6 +159,7 @@ def fold( templates: Sequence[Protein | Complex | Template] | None = None, properties: Sequence[Mapping] | None = None, method: str | None = None, + seed: int | None = None, **_, ) -> FoldResultFuture: """ @@ -144,8 +167,8 @@ def fold( Parameters ---------- - sequences : Sequence[Complex | Protein | str | bytes] | MSAFuture - List of protein sequences to include in folded output. `Protein` objects must be tagged with an `msa`, which can be a `Protein.single_sequence_mode` for single sequence mode. Alternatively, supply an `MSAFuture` to use all query sequences as a multimer. + sequences : FoldInput | MSAFuture + Complexes to fold, or a lone complex/protein/sequence. `Protein` objects must be tagged with an `msa`, which can be a `Protein.single_sequence_mode` for single sequence mode. Alternatively, supply an `MSAFuture` to use all query sequences as a multimer. diffusion_samples: int Number of diffusion samples to use num_recycles : int @@ -171,6 +194,10 @@ def fold( 'FLUORESCENCE TRANSFER', 'EPR', 'THEORETICAL MODEL', 'SOLUTION SCATTERING', 'OTHER', 'AFDB', 'BOLTZ-1'. View the documentation on Boltz for upstream details. + seed : int | None + Seed for the prediction, from 0 to 2**31 - 1. None lets the model + pick its own, so every call is a fresh prediction. Folding the + same input with the same seed returns the same structures. Returns ------- @@ -186,13 +213,12 @@ def fold( ), ) - # validate properties if properties is not None: props = TypeAdapter(list[BoltzProperty]).validate_python(properties) # Only allow affinity for ligands, and check binder refers to a ligand chain_id (str, not list) ligand_chain_ids = set() if not isinstance(sequences, MSAFuture): - for protein in sequences: + for protein in _as_entities(sequences): if isinstance(protein, Complex): complex = protein for chain_id, chain in complex.get_chains().items(): @@ -217,6 +243,7 @@ def fold( templates=template_dicts or None, properties=properties, method=method, + seed=seed, ) @@ -229,13 +256,14 @@ class Boltz1Model(BoltzModel, FoldModel): def fold( self, - sequences: Sequence[Complex | Protein | str | bytes] | MSAFuture, + sequences: FoldInput | MSAFuture, diffusion_samples: int = 1, num_recycles: int = 3, num_steps: int = 200, step_scale: float = 1.638, use_potentials: bool = False, constraints: Sequence[Mapping] | None = None, + seed: int | None = None, **_, ) -> FoldResultFuture: """ @@ -243,8 +271,8 @@ def fold( Parameters ---------- - sequences : Sequence[Complex | Protein | str | bytes] | MSAFuture - List of protein sequences to include in folded output. `Protein` objects must be tagged with an `msa`, which can be a `Protein.single_sequence_mode` for single sequence mode. Alternatively, supply an `MSAFuture` to use all query sequences as a multimer. + sequences : FoldInput | MSAFuture + Complexes to fold, or a lone complex/protein/sequence. `Protein` objects must be tagged with an `msa`, which can be a `Protein.single_sequence_mode` for single sequence mode. Alternatively, supply an `MSAFuture` to use all query sequences as a multimer. diffusion_samples: int Number of diffusion samples to use num_recycles : int @@ -257,6 +285,10 @@ def fold( Whether or not to use potentials. constraints : Optional[List[dict]] List of constraints. + seed : int | None + Seed for the prediction, from 0 to 2**31 - 1. None lets the model + pick its own, so every call is a fresh prediction. Folding the + same input with the same seed returns the same structures. Returns ------- @@ -289,6 +321,7 @@ def fold( step_scale=step_scale, use_potentials=use_potentials, constraints=constraints, + seed=seed, ) @@ -301,13 +334,14 @@ class Boltz1xModel(Boltz1Model, BoltzModel, FoldModel): def fold( self, - sequences: Sequence[Complex | Protein | str | bytes] | MSAFuture, + sequences: FoldInput | MSAFuture, diffusion_samples: int = 1, num_recycles: int = 3, num_steps: int = 200, step_scale: float = 1.638, use_potentials: bool = True, constraints: Sequence[Mapping] | None = None, + seed: int | None = None, **_, ) -> FoldResultFuture: """ @@ -315,8 +349,8 @@ def fold( Parameters ---------- - sequences : Sequence[Complex | Protein | str | bytes] | MSAFuture - List of protein sequences to include in folded output. `Protein` objects must be tagged with an `msa`, which can be a `Protein.single_sequence_mode` for single sequence mode. Alternatively, supply an `MSAFuture` to use all query sequences as a multimer. + sequences : FoldInput | MSAFuture + Complexes to fold, or a lone complex/protein/sequence. `Protein` objects must be tagged with an `msa`, which can be a `Protein.single_sequence_mode` for single sequence mode. Alternatively, supply an `MSAFuture` to use all query sequences as a multimer. diffusion_samples: int Number of diffusion samples to use num_recycles : int @@ -327,6 +361,10 @@ def fold( Scaling factor for diffusion steps. constraints : Optional[List[dict]] List of constraints. + seed : int | None + Seed for the prediction, from 0 to 2**31 - 1. None lets the model + pick its own, so every call is a fresh prediction. Folding the + same input with the same seed returns the same structures. Returns ------- @@ -344,6 +382,7 @@ def fold( step_scale=step_scale, use_potentials=True, constraints=constraints, + seed=seed, ) @@ -452,7 +491,7 @@ class BoltzProperty(BaseModel): Affinity property specification. """ - # TODO handle more than more property + # TODO handle more than one property affinity: AffinityProperty @@ -520,4 +559,4 @@ class BoltzAffinity(BaseModel): affinity_probability_binary: float class Config: - extra = "allow" # Allow extra fields + extra = "allow" diff --git a/openprotein/fold/common.py b/openprotein/fold/common.py index 093aa74..f63b24f 100644 --- a/openprotein/fold/common.py +++ b/openprotein/fold/common.py @@ -1,35 +1,60 @@ """Common utilities for creating fold jobs.""" -from typing import Any, Sequence +from collections.abc import Sequence +from typing import Any from openprotein.align import AlignAPI, MSAFuture from openprotein.base import APISession +from openprotein.data.msa import MSA +from openprotein.fold import _request as request from openprotein.fold.complex import id_generator from openprotein.molecules import DNA, RNA, Complex, Ligand, Protein from openprotein.molecules.template import Template from openprotein.prompt import PromptAPI +__all__ = [ + "FoldEntity", + "FoldInput", + "msa_future_to_complex", + "normalize_inputs", + "normalize_templates", + "resolve_templates", + "serialize_input", +] -def normalize_inputs( - proteins: Sequence[Complex | Protein | str | bytes], -): + +FoldEntity = Complex | Protein | str | bytes + +FoldInput = Sequence[FoldEntity] | FoldEntity +"""A batch of foldable entities, or a lone entity folded on its own.""" + + +def _as_entities(entities: FoldInput) -> Sequence[FoldEntity]: + """Wrap a lone entity into a one-element batch.""" + if isinstance(entities, (Complex, Protein, str, bytes)): + return [entities] + return entities + + +def normalize_inputs(proteins: FoldInput): + entities = _as_entities(proteins) normalized_complexes: list[Complex] = [] - for protein in proteins: - if isinstance(protein, Complex): - normalized_complexes.append(protein) - elif isinstance(protein, Protein): + for entity in entities: + if isinstance(entity, Complex): + normalized_complexes.append(entity) + elif isinstance(entity, Protein): # a lone protein becomes a single-chain complex id_gen = id_generator() - normalized_complexes.append(Complex(chains={next(id_gen): protein})) + normalized_complexes.append(Complex(chains={next(id_gen): entity})) else: - if isinstance(protein, bytes): - protein = protein.decode() + if isinstance(entity, bytes): + entity = entity.decode() # a ':'-delimited string is one complex, one chain per split sequence. # chain ids only need to be unique within the complex, so use a fresh # generator per complex. id_gen = id_generator() chains: dict[str, Protein] = {} - for seq in protein.split(":"): + for seq in entity.split(":"): chain = Protein(sequence=seq) # protein strings default to null msa chain.msa = Protein.NullMSA @@ -52,25 +77,41 @@ def msa_future_to_complex(session: APISession, msa: MSAFuture) -> Complex: return Complex(chains=proteins) +def _msa_id_of(msa: Any) -> str | None: + """The MSA id a protein's ``.msa`` sends, or None in single sequence mode.""" + if msa is Protein.single_sequence_mode: + return None + if isinstance(msa, str): + return msa + if isinstance(msa, (MSAFuture, MSA)): + return msa.id + raise TypeError( + "`.msa` must be an MSA id, an MSAFuture, an `openprotein.data.MSA` or " + "`Protein.single_sequence_mode`, not " + f"{type(msa).__module__}.{type(msa).__qualname__}" + ) + + def normalize_templates( session: APISession, - sequences: Sequence[Complex | Protein | str | bytes] | MSAFuture, - templates: Sequence[Protein | Complex | Template] | None = None, + sequences: FoldInput | MSAFuture, + templates: Sequence[Complex | Protein | Template] | None = None, ) -> list[Template]: """Normalize and validate template inputs for fold models.""" normalized_templates: list[Template] = [] # normalize templates attached to sequence/complex inputs if not isinstance(sequences, MSAFuture): + entities = _as_entities(sequences) first_chain_id_to_template = {} - for batch_idx, seq in enumerate(sequences): - if isinstance(seq, (str, bytes)): - seq = Protein(seq) - seq._assert_valid_templates() - if isinstance(seq, Protein): - complex = Complex({"A": seq}) + for batch_idx, entity in enumerate(entities): + if isinstance(entity, (str, bytes)): + entity = normalize_inputs(entity)[0] + entity._assert_valid_templates() + if isinstance(entity, Protein): + complex = Complex({"A": entity}) else: - complex = seq + complex = entity for chain_id, protein in complex.get_proteins().items(): if batch_idx == 0: @@ -79,7 +120,9 @@ def normalize_templates( normalized_templates.append( Template.from_obj(template, chain_id=chain_id) ) - elif first_chain_id_to_template[chain_id] != protein.templates: + elif list(first_chain_id_to_template.get(chain_id, ())) != list( + protein.templates + ): raise ValueError( "Expected same chain across batches to have the same templates" ) @@ -93,27 +136,33 @@ def normalize_templates( "Expected templates across complexes in batch to be the same" ) + for template in normalized_templates: + if template.index is None and template.index_intervals is None: + template.validate_for_target(complex) + # normalize method-level templates if templates is not None: if isinstance(sequences, MSAFuture): - validation_sequences: Sequence[Complex | Protein | str | bytes] = [ + validation_sequences: Sequence[FoldEntity] = [ msa_future_to_complex(session=session, msa=sequences) ] else: - validation_sequences = sequences + validation_sequences = _as_entities(sequences) for template in templates: template = Template.from_obj(template) - for seq in validation_sequences: - if isinstance(seq, (str, bytes)): - seq = Protein(seq) - template.validate_for_target(seq) + for entity in validation_sequences: + if isinstance(entity, (str, bytes)): + entity = normalize_inputs(entity)[0] + if isinstance(entity, Protein): + entity = Complex({"A": entity}) + template.validate_for_target(entity) normalized_templates.append(template) return normalized_templates def resolve_templates(session: APISession, templates: Sequence[Template]) -> list[dict]: - """Resolve normalized ``Template`` objects into backend API payload dictionaries.""" + """Resolve normalized ``Template`` objects into API payload dictionaries.""" prompt_api = getattr(session, "prompt", None) assert isinstance(prompt_api, PromptAPI) @@ -146,15 +195,17 @@ def resolve_templates(session: APISession, templates: Sequence[Template]) -> lis def serialize_input(session: APISession, complexes: list[Complex], needs_msa: bool): - # build the serialized input + """Return the ``complexes`` of a fold request, one validated ``MsaChain`` dump per chain. + + ``msa_id`` is sent for every protein when ``needs_msa``, null in single + sequence mode, and left out otherwise. + """ _models: list[list[dict[str, Any]]] = [] - msa_to_seed: dict[str, set[str]] = dict() for complex in complexes: _complex: list[dict[str, Any]] = [] for chain_id, chain in complex.get_chains().items(): if isinstance(chain, Protein): - # add the protein in the unified format - p: dict = { + p: dict[str, Any] = { "id": chain_id, "sequence": chain.sequence.decode(), } @@ -165,48 +216,28 @@ def serialize_input(session: APISession, complexes: list[Complex], needs_msa: bo raise ValueError( "Expected all protein sequences to have `.msa` set with an `MSAFuture` or `Protein.single_sequence_mode` for single sequence mode." ) - # convert to msa id or null for single sequence mode - msa_id = ( - msa - if isinstance(msa, str) - else msa.id - if isinstance(msa, MSAFuture) - else None - ) - # handle msa - this_msas: set[str] = set() - if msa_id is not None: - this_msas.add(msa_id) - if msa_id in msa_to_seed: - seeds = msa_to_seed[msa_id] - else: - align_api = getattr(session, "align", None) - assert isinstance(align_api, AlignAPI) - seed = align_api.get_seed(job_id=msa_id) - # need a counter so we can make sure later that the proteins make up the msa completely - seeds = set(seed.split(":")) - msa_to_seed[msa_id] = seeds - # make sure we only have one msa - # TODO: by my reading, this could never have size > 1 atm... - if len(this_msas) > 1: - raise ValueError("Expected only 1 unique msa") + msa_id = _msa_id_of(msa) p["msa_id"] = msa_id - _complex.append({"protein": p}) + entry = request.MsaChain(protein=request.ProteinWithMSA(**p)) elif isinstance(chain, Ligand): - ligand_payload: dict[str, Any] = {"id": chain_id} - if chain.smiles is not None: - ligand_payload["smiles"] = chain.smiles - if chain.ccd is not None: - ligand_payload["ccd"] = chain.ccd - _complex.append({"ligand": ligand_payload}) + ligand = {"smiles": chain.smiles, "ccd": chain.ccd} + entry = request.MsaChain( + ligand=request.Ligand( + id=chain_id, + **{k: v for k, v in ligand.items() if v is not None}, + ) + ) elif isinstance(chain, DNA): - d: dict[str, Any] = {"id": chain_id, "sequence": chain.sequence} - _complex.append({"dna": d}) + entry = request.MsaChain( + dna=request.DNA(id=chain_id, sequence=chain.sequence) + ) elif isinstance(chain, RNA): - r: dict[str, Any] = {"id": chain_id, "sequence": chain.sequence} - _complex.append({"rna": r}) + entry = request.MsaChain( + rna=request.RNA(id=chain_id, sequence=chain.sequence) + ) else: raise ValueError(f"Unexpected chain type: {chain}") + _complex.append(entry.model_dump(mode="json", exclude_unset=True)) _models.append(_complex) return _models diff --git a/openprotein/fold/complex.py b/openprotein/fold/complex.py index 3af3a2c..bf36a38 100644 --- a/openprotein/fold/complex.py +++ b/openprotein/fold/complex.py @@ -1,6 +1,9 @@ import re import string +__all__ = ["id_generator", "is_valid_id", "valid_id_pattern"] + + valid_id_pattern = re.compile(r"^[A-Z]{1,5}$|^\d{1,5}$") @@ -21,9 +24,8 @@ def id_generator(used_ids: list[str] | None = None, max_alpha_len=5, max_numeric used = set(tuple(used_ids or [])) letters = list(string.ascii_uppercase) - # --- Alphabetic IDs --- curr_len = 1 - curr_indices = [0] * curr_len # start at 'A' + curr_indices = [0] * curr_len def bump_indices(): # lexicographically increment curr_indices; return False on overflow @@ -47,7 +49,6 @@ def bump_indices(): break curr_indices = [0] * curr_len - # --- Numeric IDs --- num = 1 while num <= max_numeric: candidate = str(num) diff --git a/openprotein/fold/esmfold.py b/openprotein/fold/esmfold.py index 4fd54f8..76cb9f7 100644 --- a/openprotein/fold/esmfold.py +++ b/openprotein/fold/esmfold.py @@ -1,17 +1,18 @@ """Community-based ESMFold model.""" import warnings -from typing import Sequence from openprotein.base import APISession from openprotein.common import ModelMetadata -from openprotein.fold.common import normalize_inputs, serialize_input -from openprotein.molecules import DNA, RNA, Complex, Ligand, Protein +from openprotein.fold.common import FoldInput, normalize_inputs, serialize_input +from openprotein.molecules import DNA, RNA, Ligand from . import api from .future import FoldResultFuture from .models import FoldModel +__all__ = ["ESMFoldModel"] + class ESMFoldModel(FoldModel): """ @@ -30,7 +31,7 @@ def __init__( def fold( self, - sequences: Sequence[Complex | Protein | str | bytes], + sequences: FoldInput, num_recycles: int | None = None, **_, ) -> FoldResultFuture: @@ -39,7 +40,7 @@ def fold( Parameters ---------- - sequences : Sequence[Complex | Protein | str | bytes] + sequences : FoldInput sequences to fold num_recycles : int | None number of times to recycle models @@ -51,13 +52,9 @@ def fold( for complex in normalized_complexes: for id, chain in complex.get_chains().items(): - if ( - isinstance(chain, DNA) - or isinstance(chain, RNA) - or isinstance(chain, Ligand) - ): + if isinstance(chain, (DNA, RNA, Ligand)): with warnings.catch_warnings(): - warnings.simplefilter("always") # Force warning to always show + warnings.simplefilter("always") warnings.warn( "ESMFold does not support ligand/DNA/RNA input. These extra chains will be ignored in the output." ) diff --git a/openprotein/fold/esmfold2.py b/openprotein/fold/esmfold2.py index b584995..6a4a1c7 100644 --- a/openprotein/fold/esmfold2.py +++ b/openprotein/fold/esmfold2.py @@ -1,23 +1,25 @@ """Community-based ESMFold2 models for complex structure prediction.""" -from collections.abc import Sequence - from pydantic import BaseModel from openprotein.align import MSAFuture from openprotein.base import APISession from openprotein.common import ModelMetadata from openprotein.fold.common import ( + FoldInput, + _msa_id_of, msa_future_to_complex, normalize_inputs, serialize_input, ) -from openprotein.molecules import Complex, Protein +from openprotein.molecules import Complex from . import api from .future import FoldResultFuture from .models import FoldModel +__all__ = ["ESMFold2Confidence", "ESMFold2FastModel", "ESMFold2Model"] + class ESMFold2Confidence(BaseModel): """ @@ -49,8 +51,7 @@ def _assert_no_protein_msa(complexes: list[Complex]) -> None: """Raise if any protein chain carries an MSA reference.""" for complex in complexes: for chain_id, protein in complex.get_proteins().items(): - msa = protein.msa - if isinstance(msa, (str, MSAFuture)): + if protein.msa is not None and _msa_id_of(protein.msa) is not None: raise ValueError( f"ESMFold2-Fast is a single-sequence variant and does not " f"accept MSAs; chain {chain_id!r} has an MSA attached. " @@ -61,7 +62,7 @@ def _assert_no_protein_msa(complexes: list[Complex]) -> None: def _esmfold2_fold( session: APISession, model_id: str, - sequences: Sequence[Complex | Protein | str | bytes] | MSAFuture, + sequences: FoldInput | MSAFuture, diffusion_samples: int | None, num_recycles: int | None, num_steps: int | None, @@ -121,7 +122,7 @@ def __init__( def fold( self, - sequences: Sequence[Complex | Protein | str | bytes] | MSAFuture, + sequences: FoldInput | MSAFuture, diffusion_samples: int = 1, num_recycles: int = 3, num_steps: int = 100, @@ -133,7 +134,7 @@ def fold( Parameters ---------- - sequences : Sequence[Complex | Protein | str | bytes] | MSAFuture + sequences : FoldInput | MSAFuture List of complexes to fold. `Protein` objects must be tagged with an `msa`, which can be `Protein.single_sequence_mode` for single sequence mode. Alternatively, supply an `MSAFuture` to use all @@ -183,7 +184,7 @@ def __init__( def fold( self, - sequences: Sequence[Complex | Protein | str | bytes], + sequences: FoldInput, diffusion_samples: int = 1, num_recycles: int = 3, num_steps: int = 100, @@ -198,7 +199,7 @@ def fold( Parameters ---------- - sequences : Sequence[Complex | Protein | str | bytes] + sequences : FoldInput List of complexes to fold. `Protein` objects must be tagged with `Protein.single_sequence_mode`. diffusion_samples : int diff --git a/openprotein/fold/fold.py b/openprotein/fold/fold.py index d3b3bfb..c004b1a 100644 --- a/openprotein/fold/fold.py +++ b/openprotein/fold/fold.py @@ -9,12 +9,13 @@ from .esmfold2 import ESMFold2FastModel, ESMFold2Model from .future import FoldResultFuture from .minifold import MiniFoldModel -from .models import ( - FoldModel, -) +from .models import FoldModel +from .opendde import OpenDDEAbagModel, OpenDDEModel from .protenix import ProtenixModel, ProtenixV2Model from .rosettafold3 import RosettaFold3Model +__all__ = ["FoldAPI"] + class FoldAPI: """ @@ -44,6 +45,10 @@ class FoldAPI: esmfold2_fast: ESMFold2FastModel #: MiniFold model minifold: MiniFoldModel + #: OpenDDE model + opendde: OpenDDEModel + #: OpenDDE antibody-antigen model + opendde_abag: OpenDDEAbagModel #: Protenix model protenix: ProtenixModel #: Protenix-v2 model @@ -54,12 +59,10 @@ def __init__(self, session: APISession): self._load_models() def _load_models(self): - # Dynamically add model instances as attributes - precludes any drift models = self.list_models() for model in models: - model_name = model.id.replace("-", "_") # hyphens out + model_name = model.id.replace("-", "_") setattr(self, model_name, model) - # Setup aliases safely if getattr(self, "alphafold2", None): self.af2 = self.alphafold2 if getattr(self, "rosettafold_3", None): diff --git a/openprotein/fold/future.py b/openprotein/fold/future.py index e14f7ba..e439a73 100644 --- a/openprotein/fold/future.py +++ b/openprotein/fold/future.py @@ -21,9 +21,13 @@ if TYPE_CHECKING: from .boltz import BoltzAffinity, BoltzConfidence from .esmfold2 import ESMFold2Confidence + from .opendde import OpenDDEConfidence from .protenix import ProtenixConfidence -FoldResult: typing.TypeAlias = "Structure | np.ndarray | pd.DataFrame | BoltzAffinity | list[BoltzConfidence] | list[ProtenixConfidence] | list[ESMFold2Confidence]" +__all__ = ["FoldResult", "FoldResultFuture"] + + +FoldResult: typing.TypeAlias = "Structure | np.ndarray | pd.DataFrame | BoltzAffinity | list[BoltzConfidence] | list[OpenDDEConfidence] | list[ProtenixConfidence] | list[ESMFold2Confidence]" class FoldResultFuture( @@ -59,7 +63,6 @@ def __init__( :meta private: """ - # initialize the fold job metadata if metadata is None: if job is None or job.job_id is None: raise ValueError("Expected fold metadata or job") @@ -121,7 +124,6 @@ def complexes(self) -> list[Complex]: model = Complex(chains=proteins) complexes.append(model) else: - # collate used ids used_ids = [] for complex_dicts in self.metadata.sequences: for complex_dict in complex_dicts: @@ -207,12 +209,12 @@ def model_id(self) -> str: def __keys__(self): """ - Get the list of sequences submitted for the fold request. + The keys addressing each unit of the fold job. Returns ------- - list of bytes - List of sequences. + list[int] + Zero-based indices, one per submitted input, in submission order. """ return list(range(len(self._sequences))) @@ -251,7 +253,9 @@ def get_item( self, k: int, key: Literal["confidence"], - ) -> "list[BoltzConfidence] | list[ProtenixConfidence] | list[ESMFold2Confidence]": ... + ) -> ( + "list[BoltzConfidence] | list[ProtenixConfidence] | list[ESMFold2Confidence]" + ): ... @typing.overload def get_item( @@ -286,17 +290,24 @@ def get_item( **kwargs, ) -> FoldResult: # ty: ignore[invalid-method-override] """ - Get fold results for a specified sequence. + Get fold results for one unit of the fold job. Parameters ---------- - sequence : bytes - Sequence to fetch results for. + k : int + Zero-based index of the unit, as returned by ``__keys__``. + key : str or None, optional + Which result to fetch. ``None`` returns the predicted structure. + Otherwise one of ``"pae"``, ``"pde"``, ``"plddt"``, ``"ptm"``, + ``"ipae"``, ``"confidence"``, ``"affinity"``, ``"score"`` or + ``"metrics"``. Availability varies by model. Returns ------- - Complex - Complex containing the folded structure. + Structure or np.ndarray or pd.DataFrame or BoltzAffinity or list + The predicted structure when ``key`` is ``None``; an array for the + per-residue and per-pair metrics; a parsed affinity or per-model + confidence object for ``"affinity"`` and ``"confidence"``. """ if key is None: data = api.fold_get_sequence_result(self.session, self.job.job_id, k) @@ -309,7 +320,11 @@ def get_item( data = TypeAdapter(BoltzAffinity).validate_python(data) elif key == "confidence": - if self.model_id in {"protenix", "protenix-v2"}: + if self.model_id in {"opendde", "opendde-abag"}: + from .opendde import OpenDDEConfidence + + data = TypeAdapter(list[OpenDDEConfidence]).validate_python(data) + elif self.model_id in {"protenix", "protenix-v2"}: from .protenix import ProtenixConfidence data = TypeAdapter(list[ProtenixConfidence]).validate_python(data) @@ -481,6 +496,8 @@ def get_pae(self) -> list[np.ndarray]: "esmfold", "esmfold2", "esmfold2-fast", + "opendde", + "opendde-abag", "protenix", "protenix-v2", }: @@ -510,6 +527,8 @@ def get_pde(self) -> list[np.ndarray]: "boltz-1", "boltz-1x", "boltz-2", + "opendde", + "opendde-abag", "protenix", "protenix-v2", }: @@ -542,6 +561,8 @@ def get_plddt(self) -> list[np.ndarray]: "alphafold2", "esmfold2", "esmfold2-fast", + "opendde", + "opendde-abag", "protenix", "protenix-v2", }: @@ -681,6 +702,8 @@ def get_confidence( "boltz-1", "boltz-1x", "boltz-2", + "opendde", + "opendde-abag", "protenix", "protenix-v2", "esmfold2", @@ -722,11 +745,6 @@ def get_affinity(self) -> list["BoltzAffinity"]: self._affinity = affinity return copy.deepcopy(self._affinity) - # ------------------------------------------------------------------ # - # Batch-extras accessors: one HTTP call to the server's - # /fold/{id}/results/{key} endpoint rather than per-unit fan-out. - # ------------------------------------------------------------------ # - def get_pae_batch(self) -> np.ndarray: """ Get the Predicted Aligned Error (PAE) for every unit as a single @@ -741,6 +759,8 @@ def get_pae_batch(self) -> np.ndarray: "esmfold", "esmfold2", "esmfold2-fast", + "opendde", + "opendde-abag", "protenix", "protenix-v2", }: @@ -755,6 +775,8 @@ def get_pde_batch(self) -> np.ndarray: "boltz-1", "boltz-1x", "boltz-2", + "opendde", + "opendde-abag", "protenix", "protenix-v2", }: @@ -772,6 +794,8 @@ def get_plddt_batch(self) -> np.ndarray: "alphafold2", "esmfold2", "esmfold2-fast", + "opendde", + "opendde-abag", "protenix", "protenix-v2", }: @@ -812,18 +836,20 @@ def get_ipae_batch(self) -> np.ndarray: def get_confidence_batch( self, - ) -> "list[list[BoltzConfidence] | None] | list[list[ProtenixConfidence] | None] | list[list[ESMFold2Confidence] | None]": + ) -> "list[list[BoltzConfidence] | None] | list[list[OpenDDEConfidence] | None] | list[list[ProtenixConfidence] | None] | list[list[ESMFold2Confidence] | None]": """ Retrieve per-unit confidence objects in a single HTTP call. Returns a length-``N`` list; each entry is that unit's parsed - confidence list, or ``None`` if the server could not fetch the - result for that unit. + confidence list, or ``None`` if that unit's result could not be + fetched. """ if self.model_id not in { "boltz-1", "boltz-1x", "boltz-2", + "opendde", + "opendde-abag", "protenix", "protenix-v2", "esmfold2", @@ -833,6 +859,15 @@ def get_confidence_batch( raw = api.fold_get_batch_extra_result( self.session, self.job.job_id, "confidence" ) + if self.model_id in {"opendde", "opendde-abag"}: + from .opendde import OpenDDEConfidence + + return [ + None + if entry is None + else TypeAdapter(list[OpenDDEConfidence]).validate_python(entry) + for entry in raw + ] if self.model_id in {"protenix", "protenix-v2"}: from .protenix import ProtenixConfidence @@ -865,7 +900,7 @@ def get_affinity_batch(self) -> "list[BoltzAffinity | None]": Retrieve per-unit affinity objects in a single HTTP call. Returns a length-``N`` list; each entry is a ``BoltzAffinity`` or - ``None`` if the server could not fetch that unit's result. + ``None`` if that unit's result could not be fetched. """ if self.model_id != "boltz-2": raise AttributeError("affinity is only supported for boltz-2") diff --git a/openprotein/fold/minifold.py b/openprotein/fold/minifold.py index 6e071f8..a05111a 100644 --- a/openprotein/fold/minifold.py +++ b/openprotein/fold/minifold.py @@ -1,16 +1,15 @@ """Community-based MiniFold model.""" -from typing import Sequence - from openprotein.base import APISession from openprotein.common import ModelMetadata -from openprotein.fold.common import normalize_inputs, serialize_input -from openprotein.molecules import Complex, Protein +from openprotein.fold.common import FoldInput, normalize_inputs, serialize_input from . import api from .future import FoldResultFuture from .models import FoldModel +__all__ = ["MiniFoldModel"] + class MiniFoldModel(FoldModel): """ @@ -29,7 +28,8 @@ def __init__( def fold( self, - sequences: Sequence[Complex | Protein | str | bytes], + # NOTE: ideally we type constrain away Complex but this breaks LSP + sequences: FoldInput, num_recycles: int | None = None, **_, ) -> FoldResultFuture: @@ -38,7 +38,7 @@ def fold( Parameters ---------- - sequences : Sequence[bytes | str] + sequences : FoldInput sequences to fold num_recycles : int | None number of times to recycle models diff --git a/openprotein/fold/models.py b/openprotein/fold/models.py index 68cf053..c893f33 100644 --- a/openprotein/fold/models.py +++ b/openprotein/fold/models.py @@ -1,16 +1,42 @@ """Fold model representations which can be used directly for creating structure predictions.""" -from typing import Sequence +from collections.abc import Iterator from openprotein.base import APISession from openprotein.common import ModelMetadata from openprotein.molecules import Complex, Protein from . import api +from .common import FoldInput, _as_entities, normalize_inputs, serialize_input from .future import FoldResultFuture +__all__ = ["FoldModel"] + + +def _attaches_msa(sequences: FoldInput) -> bool: + """Whether any given protein has an MSA or single sequence mode attached.""" + for entity in _as_entities(sequences): + if isinstance(entity, Complex): + proteins = list(entity.get_proteins().values()) + elif isinstance(entity, Protein): + proteins = [entity] + else: + continue + if any(protein.msa is not None for protein in proteins): + return True + return False + + +def _subclasses(cls: type) -> Iterator[type]: + """Every subclass of ``cls``, at any depth. ``__subclasses__`` is direct only.""" + for sub in cls.__subclasses__(): + yield sub + yield from _subclasses(sub) + class FoldModel: + """A fold model that predicts a structure from sequences.""" + # overridden by subclasses # used to get correct fold model model_id: list[str] | str @@ -41,13 +67,18 @@ def get_model(cls): list of str List of model_id strings associated with this class. """ - if isinstance(cls.model_id, str): - return [cls.model_id] - return cls.model_id + model_id = cls.model_id + if isinstance(model_id, str): + return [model_id] + if isinstance(model_id, list): + return model_id + # No id declared, so this class serves nothing. + return [] @property def model_id(self) -> str: - return model_id if isinstance(model_id := self.model_id, str) else model_id[0] + # self.id, not self.model_id - that would call this property again. + return self.id @classmethod def create( @@ -58,7 +89,7 @@ def create( **kwargs, ): """ - Create and return an instance of the appropriate FoldModel subclass based on the model_id. + Create and return an instance of the subclass serving ``model_id``. Parameters ---------- @@ -81,14 +112,9 @@ def create( ValueError If no suitable FoldModel subclass is found and no default is provided. """ - # Dynamically discover all subclasses of FoldModel - model_classes = FoldModel.__subclasses__() - - # Find the FoldModel class that matches the model_id - for model_class in model_classes: + for model_class in _subclasses(FoldModel): if model_id in model_class.get_model(): return model_class(session=session, model_id=model_id, **kwargs) - # default to FoldModel if default is not None: try: return default(session=session, model_id=model_id, **kwargs) @@ -118,16 +144,19 @@ def get_metadata(self) -> ModelMetadata: def fold( self, - sequences: Sequence[Complex | Protein | str | bytes], + sequences: FoldInput, **kwargs, ) -> FoldResultFuture: """ - Fold a sequence using this model. + Fold sequences using this model. Parameters ---------- - sequences : Sequence[Complex | Protein | str | bytes] - sequences to fold + sequences : FoldInput + Sequences, proteins or complexes to fold. Every protein is sent + with an ``msa_id`` when any of them has an MSA or + ``Protein.single_sequence_mode`` attached. An empty list sends no + sequences, for models whose inputs are other parameters. **kwargs : dict, optional Additional keyword arguments to pass to the underlying `fold` request. @@ -137,11 +166,19 @@ def fold( FoldResultFuture Future object representing the fold result. """ + complexes = normalize_inputs(sequences) + serialized = ( + serialize_input(self.session, complexes, needs_msa=_attaches_msa(sequences)) + if complexes + else None + ) return FoldResultFuture.create( session=self.session, job=api.fold_models_post( session=self.session, model_id=self.model_id, + sequences=serialized, **kwargs, ), + complexes=complexes or None, ) diff --git a/openprotein/fold/opendde.py b/openprotein/fold/opendde.py new file mode 100644 index 0000000..b124156 --- /dev/null +++ b/openprotein/fold/opendde.py @@ -0,0 +1,169 @@ +"""OpenDDE all-atom co-folding model for complex structure prediction.""" + +from pydantic import BaseModel + +from openprotein.align import MSAFuture +from openprotein.fold.common import ( + FoldInput, + msa_future_to_complex, + normalize_inputs, + serialize_input, +) + +from . import api +from .future import FoldResultFuture +from .models import FoldModel + +__all__ = ["OpenDDEAbagModel", "OpenDDEConfidence", "OpenDDEModel"] + + +class OpenDDEConfidence(BaseModel): + """ + Per-sample confidence scores from an OpenDDE structure prediction. + + Attributes + ---------- + ranking_score : float + Composite ranking metric: + ``0.8 * iptm + 0.2 * ptm + 0.5 * disorder - 100 * has_clash``. + ptm : float + Predicted TM-score for the full complex. + iptm : float + Interface pTM aggregated over inter-chain residue pairs. + plddt : float + Mean per-atom pLDDT in [0, 100]. + gpde : float + Global PDE weighted by contact probabilities. + has_clash : float + Binary clash flag (1.0 if atomic clashes detected, else 0.0). + num_recycles : int + Number of recycling iterations used. + disorder : float + Disorder score (currently always 0.0). + chain_ptm : list[float] + Per-chain pTM scores, indexed by chain. + chain_iptm : list[float] + Per-chain ipTM scores. + chain_plddt : list[float] + Per-chain mean pLDDT scores. + chain_gpde : list[float] + Per-chain global PDE scores. + chain_pair_iptm : list[list[float]] + Chain-pair ipTM matrix. + chain_pair_iptm_global : list[list[float]] + Chain-pair ipTM matrix with ligand-aware weighting. + chain_pair_gpde : list[list[float]] + Chain-pair global PDE matrix. + chain_pair_plddt : list[list[float]] + Chain-pair mean pLDDT matrix. + + Notes + ----- + OpenDDE emits three further scores - ``pb_ranking_score``, + ``has_vdw_pl_clash`` and ``pb_ranking_score_vdw_penalized`` - only when a + prediction targets a specific binder chain. This API never requests that, so + they are not declared here; ``extra = "allow"`` passes them through should + that change. + """ + + ranking_score: float + ptm: float + iptm: float + plddt: float + gpde: float + has_clash: float + num_recycles: int + disorder: float + chain_ptm: list[float] + chain_iptm: list[float] + chain_plddt: list[float] + chain_gpde: list[float] + chain_pair_iptm: list[list[float]] + chain_pair_iptm_global: list[list[float]] + chain_pair_gpde: list[list[float]] + chain_pair_plddt: list[list[float]] + + class Config: + extra = "allow" + + +class OpenDDEModel(FoldModel): + """ + Class providing inference endpoints for OpenDDE structure prediction. + + OpenDDE folds protein, DNA, RNA, ligand and ion entities into a single + all-atom complex, optionally conditioned on an MSA per protein chain. + """ + + model_id: str = "opendde" + + def fold( + self, + sequences: FoldInput | MSAFuture, + diffusion_samples: int = 1, + num_recycles: int = 10, + num_steps: int = 200, + seed: int | None = None, + **_, + ) -> FoldResultFuture: + """ + Request structure prediction with OpenDDE. + + Parameters + ---------- + sequences : FoldInput | MSAFuture + List of complexes to fold. `Protein` objects must be tagged with an + `msa`, which can be `Protein.single_sequence_mode` to fold without + one. Alternatively, supply an `MSAFuture` to use all its query + sequences as a multimer. + diffusion_samples : int + Number of diffusion samples to generate per prediction. + num_recycles : int + Number of recycling iterations to run. + num_steps : int + Number of diffusion sampling steps. + seed : int | None + Seed for the diffusion sampling, from 0 to 2**32 - 1. None lets + the model pick its own, so every call is a fresh prediction. + Input preparation, ligand conformers included, is not seeded, + so folding the same input with the same seed can still give + different structures, especially for complexes with a ligand. + + Returns + ------- + FoldResultFuture + Future for the folding results. + """ + if isinstance(sequences, MSAFuture): + normalized_complexes = [msa_future_to_complex(self.session, sequences)] + else: + normalized_complexes = normalize_inputs(sequences) + _complexes = serialize_input(self.session, normalized_complexes, needs_msa=True) + + if len(_complexes) == 0: + raise ValueError("Expected non-empty sequences") + + return FoldResultFuture( + session=self.session, + job=api.fold_models_post( + session=self.session, + model_id=self.model_id, + sequences=_complexes, + diffusion_samples=diffusion_samples, + num_recycles=num_recycles, + num_steps=num_steps, + seed=seed, + ), + complexes=normalized_complexes, + ) + + +class OpenDDEAbagModel(OpenDDEModel): + """ + Class providing inference endpoints for the OpenDDE antibody-antigen model. + + Shares OpenDDE's fold API surface and confidence schema, with weights tuned + on antibody-antigen complexes. + """ + + model_id = "opendde-abag" diff --git a/openprotein/fold/protenix.py b/openprotein/fold/protenix.py index daa5ff1..f76b9a5 100644 --- a/openprotein/fold/protenix.py +++ b/openprotein/fold/protenix.py @@ -8,6 +8,7 @@ from openprotein.base import APISession from openprotein.common import ModelMetadata from openprotein.fold.common import ( + FoldInput, msa_future_to_complex, normalize_inputs, normalize_templates, @@ -20,6 +21,8 @@ from .future import FoldResultFuture from .models import FoldModel +__all__ = ["ProtenixConfidence", "ProtenixModel", "ProtenixV2Model"] + class ProtenixConfidence(BaseModel): """ @@ -96,11 +99,12 @@ def __init__( def fold( self, - sequences: Sequence[Complex | Protein | str | bytes] | MSAFuture, + sequences: FoldInput | MSAFuture, diffusion_samples: int = 1, num_recycles: int = 10, num_steps: int = 200, templates: Sequence[Protein | Complex | Template] | None = None, + seed: int | None = None, **_, ) -> FoldResultFuture: """ @@ -108,8 +112,8 @@ def fold( Parameters ---------- - sequences : Sequence[Complex | Protein | str | bytes] | MSAFuture - List of protein complexes to include in folded output. `Protein` objects must be tagged with an `msa`, which can be a `Protein.single_sequence_mode` for single sequence mode. Alternatively, supply an `MSAFuture` to use all query sequences as a multimer. + sequences : FoldInput | MSAFuture + Complexes to fold, or a lone complex/protein/sequence. `Protein` objects must be tagged with an `msa`, which can be a `Protein.single_sequence_mode` for single sequence mode. Alternatively, supply an `MSAFuture` to use all query sequences as a multimer. diffusion_samples: int Number of diffusion samples to use num_recycles : int @@ -118,6 +122,10 @@ def fold( Number of sampling steps to use templates: list[Protein | Complex | Template] | None = None List of templates to use for structure prediction. + seed : int | None + Seed for the prediction, from 0 to 2**31 - 1. None lets the model + pick its own, so every call is a fresh prediction. Folding the + same input with the same seed returns the same structures. Returns ------- @@ -152,6 +160,7 @@ def fold( num_recycles=num_recycles, num_steps=num_steps, templates=template_dicts or None, + seed=seed, ), complexes=normalized_complexes, ) @@ -161,8 +170,7 @@ class ProtenixV2Model(ProtenixModel, FoldModel): """ Class providing inference endpoints for Protenix-v2 structure prediction. - Protenix-v2 shares Protenix's fold API surface and confidence schema; only - the backend ``model_id`` differs. + Protenix-v2 shares Protenix's fold API surface and confidence schema. """ model_id = "protenix-v2" diff --git a/openprotein/fold/rosettafold3.py b/openprotein/fold/rosettafold3.py index 6fb1f81..221b20c 100644 --- a/openprotein/fold/rosettafold3.py +++ b/openprotein/fold/rosettafold3.py @@ -1,22 +1,24 @@ """Community-based RosettaFold3 models for complex structure prediction with ligands/dna/rna.""" import warnings -from typing import Sequence from openprotein.align import MSAFuture from openprotein.base import APISession from openprotein.common import ModelMetadata from openprotein.fold.common import ( + FoldInput, msa_future_to_complex, normalize_inputs, serialize_input, ) from openprotein.fold.future import FoldResultFuture -from openprotein.molecules import DNA, RNA, Complex, Protein +from openprotein.molecules import DNA, RNA from . import api from .models import FoldModel +__all__ = ["RosettaFold3Model"] + class RosettaFold3Model(FoldModel): """ @@ -35,10 +37,11 @@ def __init__( def fold( self, - sequences: Sequence[Complex | Protein | str | bytes] | MSAFuture, + sequences: FoldInput | MSAFuture, diffusion_samples: int = 1, num_recycles: int = 10, num_steps: int = 50, + seed: int | None = None, **kwargs, ) -> FoldResultFuture: """ @@ -46,14 +49,18 @@ def fold( Parameters ---------- - sequences: list[Complex | Protein | str | bytes] | MSAFuture, - List of protein sequences to include in folded output. `Protein` objects must be tagged with an `msa`, which can be a `Protein.single_sequence_mode` for single sequence mode. Alternatively, supply an `MSAFuture` to use all query sequences as a multimer. + sequences: FoldInput | MSAFuture, + Complexes to fold, or a lone complex/protein/sequence. `Protein` objects must be tagged with an `msa`, which can be a `Protein.single_sequence_mode` for single sequence mode. Alternatively, supply an `MSAFuture` to use all query sequences as a multimer. diffusion_samples: int Number of diffusion samples to use num_recycles : int Number of recycling steps to use num_steps : int Number of sampling steps to use + seed : int | None + Seed for the prediction, from 1 to 2**32 - 1. None lets the model + pick its own, so every call is a fresh prediction. Folding the + same input with the same seed returns the same structures. Returns ------- @@ -61,7 +68,6 @@ def fold( Future for the folding results. """ - # build the normalized_models from msa if isinstance(sequences, MSAFuture): normalized_complexes = [msa_future_to_complex(self.session, sequences)] @@ -72,7 +78,7 @@ def fold( for id, chain in complex.get_chains().items(): if isinstance(chain, DNA) or isinstance(chain, RNA): with warnings.catch_warnings(): - warnings.simplefilter("always") # Force warning to always show + warnings.simplefilter("always") warnings.warn( "RosettaFold-3 does not support DNA/RNA input. These extra chains will be ignored in the output." ) @@ -92,6 +98,7 @@ def fold( diffusion_samples=diffusion_samples, num_recycles=num_recycles, num_steps=num_steps, + seed=seed, **kwargs, ), complexes=normalized_complexes, diff --git a/openprotein/fold/schemas.py b/openprotein/fold/schemas.py index 51dbd18..16421d5 100644 --- a/openprotein/fold/schemas.py +++ b/openprotein/fold/schemas.py @@ -1,11 +1,13 @@ """Schema for OpenProtein fold system.""" -from typing import Any, Literal +from typing import Annotated, Any, Literal -from pydantic import BaseModel +from pydantic import BaseModel, ConfigDict, Field, StrictBool, model_validator from openprotein.jobs import BatchJob, Job, JobType +__all__ = ["FoldConfidence", "FoldJob", "FoldMetadata"] + class FoldMetadata(BaseModel): """ @@ -34,7 +36,128 @@ class FoldJob(Job, BatchJob): Attributes ---------- job_type : Literal[JobType.embeddings_fold] - The type of job, set to embeddings_fold. + Discriminator identifying a fold job. """ job_type: Literal[JobType.embeddings_fold] + + +_UnitScore = Annotated[float, Field(ge=0, le=1)] +_PlddtScore = Annotated[float, Field(ge=0, le=100)] +_Angstrom = Annotated[float, Field(ge=0)] + + +class FoldConfidence(BaseModel): + """ + Confidence scores for one sample of a fold prediction. + + The ``confidence`` output of a fold job holds, per complex, a + ``json-utf8-v1`` list with one object per sample. Every key is present in + every object, null when the model does not produce that score, so the + objects of every fold model share one layout. Numbers are finite. + + Fold outputs, per complex; a model leaves out any output it does not + produce: + + - ``structures``: one mmCIF holding all S samples as models 1..S; + ``auth_asym_id`` is the request chain id, B-factor is pLDDT 0-100. + - ``plddt``: ``[S, T]`` float32, 0-100, per token. + - ``pae``, ``pde``: ``[S, T, T]`` float32, in Å. + - ``confidence``: ``list[FoldConfidence]`` of length S. + - ``affinity`` (boltz-2): inline object, null when not requested. + + Conventions: + + - Samples are sorted by ``ranking_score``, highest first; ties and models + without a ranker keep generation order. mmCIF model k+1, array index k + and ``confidence[k]`` are one sample. + - Chains follow request order with copies expanded; every per-chain list + follows ``chain_ids``. + - Tokens follow AF3 tokenisation: one per standard residue or nucleotide, + one per heavy atom of a ligand or modified residue, in chain order then + sequence order. Protein-only models use one token per residue. + - NaN marks a token with no placed atoms and appears nowhere else. + - pLDDT-type values are 0-100 and pTM-type values 0-1. + - PAE and PDE are expectations over bin centres, + ``X[i, j] = sum_b p[i, j, b] * (b + 0.5) * width``; 64 bins over + [0, 32] Å give centres 0.25 to 31.75. ``pae[s, i, j]`` is the error at + token j aligned on token i's frame. + - ``ptm``, ``iptm``, ``ranking_score``, ``complex_plddt`` and + ``chain_pair_iptm`` are model-native; compare them within one model. + + Attributes + ---------- + chain_ids : list[str] + Request chain ids with copies expanded to distinct ids; C entries, + non-empty and unique. + ranking_score : float or None + The model's sample ranker, higher is better; None when it has none. + ptm : float or None + pTM, 0-1. + iptm : float or None + ipTM, 0-1; None when C = 1. + complex_plddt : float + Mean pLDDT, 0-100. + chain_plddt : list[float] + Mean pLDDT per chain, 0-100. + chain_ptm : list[float or None] + pTM per chain, 0-1. + chain_pair_iptm : list[list[float or None]] + C x C pairwise ipTM, 0-1; the diagonal is ``chain_ptm``. + ipae : float or None + Interface PAE in Å. With T0 the tokens of chain 0 and R all other + tokens, ``(mean(pae[s, T0, R]) + mean(pae[s, R, T0])) / 2``, NaN + skipped. None when C = 1 or the model predicts no PAE. + complex_iplddt : float or None + Interface-weighted mean pLDDT, 0-100. + complex_pde : float or None + Contact-probability-weighted mean PDE, in Å. + complex_ipde : float or None + Interface mean PDE, in Å. + protein_iptm : float or None + ipTM over protein-protein interfaces, 0-1. + ligand_iptm : float or None + ipTM over protein-ligand interfaces, 0-1. + chain_iptm : list[float] or None + ipTM per chain, 0-1. + has_clash : bool or None + Whether the sample has a steric clash. + """ + + model_config = ConfigDict(extra="forbid", strict=True, allow_inf_nan=False) + + chain_ids: list[str] = Field(min_length=1) + ranking_score: float | None + ptm: _UnitScore | None + iptm: _UnitScore | None + complex_plddt: _PlddtScore + chain_plddt: list[_PlddtScore] + chain_ptm: list[_UnitScore | None] + chain_pair_iptm: list[list[_UnitScore | None]] + ipae: _Angstrom | None + complex_iplddt: _PlddtScore | None + complex_pde: _Angstrom | None + complex_ipde: _Angstrom | None + protein_iptm: _UnitScore | None + ligand_iptm: _UnitScore | None + chain_iptm: list[_UnitScore] | None + has_clash: StrictBool | None + + @model_validator(mode="after") + def _check_layout(self) -> "FoldConfidence": + num_chains = len(self.chain_ids) + if len(set(self.chain_ids)) != num_chains: + raise ValueError("chain_ids must be unique") + for key in ("chain_plddt", "chain_ptm", "chain_iptm"): + values = getattr(self, key) + if values is not None and len(values) != num_chains: + raise ValueError(f"{key} needs one entry per chain in chain_ids") + if len(self.chain_pair_iptm) != num_chains or any( + len(row) != num_chains for row in self.chain_pair_iptm + ): + raise ValueError("chain_pair_iptm must be C x C for C chain_ids") + if num_chains == 1: + for key in ("iptm", "ipae"): + if getattr(self, key) is not None: + raise ValueError(f"{key} must be null for one chain") + return self diff --git a/openprotein/jobs/__init__.py b/openprotein/jobs/__init__.py index 3c774ad..30bde13 100644 --- a/openprotein/jobs/__init__.py +++ b/openprotein/jobs/__init__.py @@ -4,6 +4,61 @@ isort:skip_file """ -from .schemas import BatchJob, Job, JobStatus, JobType -from .futures import Future, MappedFuture, PagedFuture, StreamingFuture +from .futures import ( + AttentionFuture, + CrossvalidateFuture, + CrossvalidateResults, + EmbeddingFuture, + FitFuture, + Future, + FutureUnit, + GPFitFuture, + IndelScoreFuture, + LogitsFuture, + LogLikelihoodFuture, + MappedFuture, + PagedFuture, + PredictionFuture, + SequenceGenerationFuture, + SingleSitePredictionFuture, + SingleSiteScoreFuture, + StreamingFuture, + StructureDesignFuture, + StructurePredictionFuture, + SVDFitFuture, + UMAPFitFuture, + UnknownJobFuture, +) from .jobs import JobsAPI +from .schemas import BatchJob, Job, JobStatus, JobType + +__all__ = [ + "AttentionFuture", + "BatchJob", + "CrossvalidateFuture", + "CrossvalidateResults", + "EmbeddingFuture", + "FitFuture", + "Future", + "FutureUnit", + "GPFitFuture", + "IndelScoreFuture", + "Job", + "JobStatus", + "JobType", + "JobsAPI", + "LogLikelihoodFuture", + "LogitsFuture", + "MappedFuture", + "PagedFuture", + "PredictionFuture", + "SVDFitFuture", + "SequenceGenerationFuture", + "SingleSitePredictionFuture", + "SingleSiteScoreFuture", + "StreamingFuture", + "StructureDesignFuture", + "StructurePredictionFuture", + "UMAPFitFuture", + "UnknownJobFuture", +] diff --git a/openprotein/jobs/_api.py b/openprotein/jobs/_api.py new file mode 100644 index 0000000..abed6fe --- /dev/null +++ b/openprotein/jobs/_api.py @@ -0,0 +1,125 @@ +"""Wire calls for job updates, lookups, outputs and units.""" + +from typing import Any + +from pydantic import TypeAdapter + +from openprotein.base import APISession +from openprotein.errors import HTTPError, JobOutputsNotReady + +from .api import job_get +from .schemas import Job, _UnitRecord + + +def operation_job( + session: APISession, body: dict[str, Any], id_key: str +) -> dict[str, Any]: + """The job an operation submitted: its body, or a read of the id it names.""" + if "job_type" in body: + return body + return job_get(session, job_id=body[id_key]).model_dump() + + +def job_update( + session: APISession, + job_id: str, + name: str | None = None, + description: str | None = None, +) -> Job: + """ + Update a job's name and description. + + Parameters + ---------- + session : APISession + The current API session for communication with the server. + job_id : str + The job to update. + name : str, optional + New name for the job. Left unchanged when None. + description : str, optional + New description for the job. Left unchanged when None. + + Returns + ------- + Job + The updated job. + """ + endpoint = f"v1/jobs/{job_id}" + + body = {} + if name is not None: + body["name"] = name + if description is not None: + body["description"] = description + + response = session.put(endpoint, json=body) + return TypeAdapter(Job).validate_python(response.json()) + + +def job_output_page( + session: APISession, + job_id: str, + output_name: str | None, + cursor: str | None = None, + limit: int | None = None, +) -> dict[str, Any]: + """Fetch one page of an output collection in position order. + + ``output_name=None`` reads the bare route, which serves the method's + default output and names it in the page's ``output``. + """ + endpoint = f"v1/data/results/{job_id}" + if output_name is not None: + endpoint = f"{endpoint}/{output_name}" + params: dict[str, Any] = {} + if cursor is not None: + params["cursor"] = cursor + if limit is not None: + params["limit"] = limit + kwargs: dict[str, Any] = {"params": params} if params else {} + try: + response = session.get(endpoint, **kwargs) + except HTTPError as exc: + if exc.status_code != 409: + raise + raise JobOutputsNotReady( + f"output {output_name or ''!r} of job {job_id} is not complete yet" + ) from exc + if response.status_code == 409: + raise JobOutputsNotReady( + f"output {output_name or ''!r} of job {job_id} is not complete yet" + ) + return dict(response.json()) + + +def job_default_output(session: APISession, job_id: str) -> str: + """The name of the job's default output, from the bare results route.""" + page = job_output_page(session, job_id, None, limit=1) + name = page.get("output") + if not isinstance(name, str) or not name: + raise ValueError(f"results of job {job_id} do not name their output") + return name + + +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}") + return dict(response.json()) + + +def job_unit_page( + session: APISession, job_id: str, *, position: int | None = None +) -> dict[str, Any]: + kwargs: dict[str, Any] = ( + {} if position is None else {"params": {"after_position": position}} + ) + return dict(session.get(f"v1/jobs/{job_id}/units", **kwargs).json()) + + +def get_unit(session: APISession, job_id: str, position: int) -> _UnitRecord: + """Read one unit's record.""" + response = session.get(f"v1/jobs/{job_id}/units/{position}") + return _UnitRecord.model_validate(response.json()) diff --git a/openprotein/jobs/_decode.py b/openprotein/jobs/_decode.py new file mode 100644 index 0000000..a549b29 --- /dev/null +++ b/openprotein/jobs/_decode.py @@ -0,0 +1,29 @@ +"""Decode a stored ``Value`` by the codec its ``Ref`` names.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from openprotein import codecs + +from ._storage import ArtifactStorage, verified_artifact + + +def decode_value(value: Any, storage: ArtifactStorage) -> Any: + """Return an inline value as stored, or a ref's verified bytes decoded by its codec. + + A null codec, or one this process has not registered, returns the bytes. + """ + if not isinstance(value, Mapping) or set(value) not in ({"inline"}, {"ref"}): + raise ValueError("stored value must contain exactly one of inline or ref") + if "inline" in value: + return value["inline"] + reference = value["ref"] + if not isinstance(reference, Mapping): + raise TypeError("stored value ref must be an object") + with verified_artifact(storage, reference) as source: + data = source.read() + name = reference.get("codec") + codec = codecs.get(name) if isinstance(name, str) else None + return data if codec is None else codec.decode(data) diff --git a/openprotein/jobs/_dispatch.py b/openprotein/jobs/_dispatch.py new file mode 100644 index 0000000..9f2e49b --- /dev/null +++ b/openprotein/jobs/_dispatch.py @@ -0,0 +1,126 @@ +"""Select supported models-task result contracts.""" + +import re +from functools import cache +from typing import TYPE_CHECKING, Any + +from openprotein.base import APISession + +from . import futures +from .futures import Future, _Submission +from .schemas import Job + +if TYPE_CHECKING: + from openprotein.models.schemas import MethodDescriptor + +_TASKS: dict[str, type[Future]] = { + "batch/embeddings": futures.EmbeddingFuture, + "batch/logits": futures.LogitsFuture, + "batch/attn": futures.AttentionFuture, + "batch/loglikelihood": futures.LogLikelihoodFuture, + "single-site/scores": futures.SingleSiteScoreFuture, + "indel/scores": futures.IndelScoreFuture, + "generate/sequences": futures.SequenceGenerationFuture, + "generate/structures": futures.StructureDesignFuture, + "batch/structures": futures.StructurePredictionFuture, + "batch/predictions": futures.PredictionFuture, + "single-site/predictions": futures.SingleSitePredictionFuture, +} + + +@cache +def _fit_futures() -> dict[str, type[Future]]: + from .futures import GPFitFuture, SVDFitFuture, UMAPFitFuture + + return {cls._family: cls for cls in (GPFitFuture, SVDFitFuture, UMAPFitFuture)} + + +_METHOD_SUFFIXES = tuple( + sorted((*_TASKS, "fit", "crossvalidate"), key=len, reverse=True) +) + + +def _encoded_identity(job: Job) -> tuple[str | None, str | None]: + if not job.job_type.startswith("/models/"): + return None, None + encoded = job.job_type.removeprefix("/models/") + for path in _METHOD_SUFFIXES: + suffix = "/" + path + if encoded.endswith(suffix): + provider = encoded[: -len(suffix)] + if provider: + return provider, path + return None, None + + +def identity(job: Job) -> tuple[str | None, str | None]: + """The job's provider and path, from its job type.""" + return _encoded_identity(job) + + +def _supported(provider: str | None, path: str | None) -> bool: + family = provider.partition("/")[0] if provider else None + return path in _TASKS or (path == "fit" and family in _fit_futures()) + + +def recognizes(job: Job) -> bool: + """Whether the job type names a supported models task.""" + return _supported(*identity(job)) + + +def create( + session: APISession, + job: Job, + *, + descriptor: "MethodDescriptor | None" = None, + submission: _Submission | None = None, + **kwargs: Any, +) -> Future: + """Create the future for a models task, or a plain ``Future``. + + The submission, else the job type, selects the contract; an unresolved + identity is tracked through ``Future``. + """ + if submission is not None: + provider: str | None = submission.model_id + path: str | None = submission.path.strip("/") + usable = bool(provider and path) + else: + provider, path = identity(job) + usable = bool(provider and path) + + future_type: type[Future] | None = None + if usable and provider is not None and path is not None: + if path == "fit": + future_type = _fit_futures().get(provider.partition("/")[0]) + else: + future_type = _TASKS.get(path) + + selected = future_type or Future + future = selected(session, job, **kwargs) + future._resolved_descriptor = descriptor + future._submission = submission + return future + + +_MODELS_JOB_TYPE = re.compile(r"^/models(/[^/]+/[^/]+(/[^/]+)?)?$") + + +def is_models_job(job: Job) -> bool: + """Whether the job uses task-output reads, by its job type.""" + return ( + bool(_MODELS_JOB_TYPE.match(job.job_type)) or job.job_type == "/search/mmseqs2" + ) + + +_PROMPT_SAMPLING_JOB_TYPE = "/prompt/sample_msa" + + +def serves_outputs(job: Job) -> bool: + """Whether the job's outputs are served by the data routes, by its job type.""" + return is_models_job(job) or recognizes(job) or is_prompt_sampling(job) + + +def is_prompt_sampling(job: Job) -> bool: + """Whether the job is a prompt sampling, by its job type.""" + return job.job_type == _PROMPT_SAMPLING_JOB_TYPE diff --git a/openprotein/jobs/_storage.py b/openprotein/jobs/_storage.py new file mode 100644 index 0000000..8caf9fa --- /dev/null +++ b/openprotein/jobs/_storage.py @@ -0,0 +1,150 @@ +"""Direct artifact reads; platform authentication is never sent to object storage.""" + +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 + +#: 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 + + +class ArtifactStorage(Protocol): + """Injectable backend boundary for authorized stored-value references.""" + + def iter_bytes(self, reference: Mapping[str, Any]) -> Iterator[bytes]: ... + + +class DirectArtifactStorage: + """Download authorized signed URLs or S3 references with ambient credentials. + + HTTP downloads use a separate requests session, never the platform's bearer + token or user headers. + """ + + def __init__( + self, + s3_client: Any = None, + *, + chunk_size: int = 1024 * 1024, + http: requests.Session | None = None, + ): + if chunk_size <= 0: + raise ValueError("chunk_size must be positive") + self.s3_client = s3_client + 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() + + +@contextmanager +def verified_artifact( + storage: ArtifactStorage, reference: Mapping[str, Any] +) -> 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. + """ + size, digest = reference.get("byte_length"), reference.get("sha256") + if type(size) is not int or size < 0: + raise ValueError("job output ref has an invalid byte_length") + if not isinstance(digest, str) or not re.fullmatch(r"[0-9a-f]{64}", digest): + raise ValueError("job output ref has an invalid sha256") + actual_size = 0 + hasher = hashlib.sha256() + with tempfile.TemporaryFile(mode="w+b") as spool: + for chunk in storage.iter_bytes(reference): + actual_size += len(chunk) + if actual_size > size: + raise ValueError( + "downloaded job output size does not match its reference" + ) + hasher.update(chunk) + spool.write(chunk) + if actual_size != size: + raise ValueError("downloaded job output size does not match its reference") + if hasher.hexdigest() != digest: + raise ValueError( + "downloaded job output digest does not match its reference" + ) + 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/_submission.py b/openprotein/jobs/_submission.py new file mode 100644 index 0000000..2de6f6c --- /dev/null +++ b/openprotein/jobs/_submission.py @@ -0,0 +1,42 @@ +"""Shared submission retry: a 425 answer is resubmitted, body and key unchanged.""" + +import time +from typing import Any + +from requests import Response + +from openprotein import config +from openprotein.base import APISession +from openprotein.errors import HTTPError + +MAX_425_RETRIES = 5 + + +def post_with_retry( + session: APISession, + url: str, + *, + json: dict[str, Any], + headers: dict[str, str], + max_retries: int = MAX_425_RETRIES, +) -> Response: + """POST once, then resubmit the identical body and headers while the answer is 425.""" + attempt = 0 + while True: + try: + return session.post(url, json=json, headers=headers) + except HTTPError as error: + if error.status_code != 425 or attempt >= max_retries: + raise + time.sleep(_retry_after(error)) + attempt += 1 + + +def _retry_after(error: HTTPError) -> float: + header = error.response.headers.get("Retry-After") + if header is None: + return config.POLLING_INTERVAL + try: + return float(header) + except ValueError: + return config.POLLING_INTERVAL diff --git a/openprotein/jobs/api.py b/openprotein/jobs/api.py index e5515a1..be4b8a6 100644 --- a/openprotein/jobs/api.py +++ b/openprotein/jobs/api.py @@ -1,25 +1,44 @@ """Jobs and job-centric flows.""" -from typing import List - from pydantic import TypeAdapter from openprotein.base import APISession from .schemas import Job +__all__ = ["job_args_get", "job_get", "jobs_list"] + def job_args_get(session: APISession, job_id: str) -> dict: """Get job.""" endpoint = f"v1/jobs/{job_id}/args" response = session.get(endpoint) - return dict(**response.json()) + return dict(response.json() or {}) -def job_get(session: APISession, job_id: str) -> Job: - """Get job.""" +def job_get(session: APISession, job_id: str, timeout: float | None = None) -> Job: + """ + Get a job. + + Parameters + ---------- + session : APISession + The API session. + job_id : str + The job identifier. + timeout : float | None, optional + Seconds the request may take. When omitted, the session timeout applies. + + Returns + ------- + Job + The job record. + """ endpoint = f"v1/jobs/{job_id}" - response = session.get(endpoint) + if timeout is None: + response = session.get(endpoint) + else: + response = session.get(endpoint, timeout=timeout) return TypeAdapter(Job).validate_python(response.json()) @@ -32,7 +51,9 @@ def jobs_list( limit: int | None = None, page_size: int | None = None, page_offset: int | None = None, -) -> List[Job]: + *, + name: str | None = None, +) -> list[Job]: """ Retrieve a list of jobs filtered by specific criteria. @@ -54,6 +75,8 @@ def jobs_list( Maximum number of jobs to return per page. page_offset : int, optional Number of jobs to skip from the start of the result set. + name : str, optional + Filter by the job's name, matched exactly. If None, jobs of all names are retrieved. Default is None. Returns ------- @@ -69,6 +92,8 @@ def jobs_list( params["job_type"] = job_type if assay_id is not None: params["assay_id"] = assay_id + if name is not None: + params["name"] = name if more_recent_than is not None: params["more_recent_than"] = more_recent_than if limit is not None: @@ -80,4 +105,4 @@ def jobs_list( response = session.get(endpoint, params=params) # return jobs, not futures - return TypeAdapter(List[Job]).validate_python(response.json()) + return TypeAdapter(list[Job]).validate_python(response.json()) diff --git a/openprotein/jobs/futures.py b/openprotein/jobs/futures.py index bb02b8c..b0d8995 100644 --- a/openprotein/jobs/futures.py +++ b/openprotein/jobs/futures.py @@ -2,13 +2,18 @@ import concurrent.futures import inspect +import io import logging +import math import time from abc import ABC, abstractmethod +from dataclasses import dataclass, field from datetime import datetime from types import UnionType from typing import ( + TYPE_CHECKING, Any, + ClassVar, Collection, Generator, Generic, @@ -17,18 +22,76 @@ Set, Type, TypeVar, + cast, + overload, ) +import numpy as np +import pandas as pd +import requests import tqdm from requests import Response from typing_extensions import Self from openprotein import config from openprotein.base import APISession -from openprotein.errors import APIError, JobFailedException, TimeoutException -from openprotein.jobs.schemas import Job, JobStatus +from openprotein.errors import ( + APIError, + HTTPError, + JobFailedException, + TimeoutException, +) +from openprotein.jobs.schemas import Job, JobStatus, _UnitRecord +from openprotein.molecules import Complex, Structure + +from . import _api, api +from .api import job_args_get + +if TYPE_CHECKING: + from openprotein.data.assaydataset import AssayDataset + from openprotein.models.gp import GPModel + from openprotein.models.schemas import MethodDescriptor + from openprotein.models.svd import SVDModel + from openprotein.models.umap import UMAPModel + + from .jobs import JobsAPI + +__all__ = [ + "AttentionFuture", + "CrossvalidateFuture", + "CrossvalidateResults", + "EmbeddingFuture", + "F", + "FitFuture", + "Future", + "FutureUnit", + "GPFitFuture", + "IndelScoreFuture", + "InvalidFutureError", + "K", + "LogLikelihoodFuture", + "LogitsFuture", + "MappedFuture", + "PagedFuture", + "PredictionFuture", + "SVDFitFuture", + "SequenceGenerationFuture", + "SingleSitePredictionFuture", + "SingleSiteScoreFuture", + "StreamingFuture", + "StructureDesignFuture", + "StructurePredictionFuture", + "UMAPFitFuture", + "UnknownJobFuture", + "V", +] + + +def _jobs_api_for(session: APISession) -> "JobsAPI": + from .jobs import JobsAPI + + return JobsAPI(session) -from . import api logger = logging.getLogger(__name__) @@ -36,16 +99,36 @@ V = TypeVar("V") # Concrete unit value returned by the future K = TypeVar("K") # Key that is connected to the value +_UNREAD = object() + class Future(ABC, Generic[V]): - """ - Base class for all Futures returning results from a job. + """Handle on a job: its identity, status and waiting, and its stored outputs. + + A job submitted through the models API, and any job whose type names a + models task or a prompt sampling, stores outputs by unit position. + ``units``, ``outputs``, ``unit``, ``get_item`` and ``stream`` read them, + decoded by the codec each stored value names. Reads go to the data routes by + output name; an unnamed output is the default the bare results route names. + ``outputs`` come from the submitting method, else the model listing. For any + other job these raise an `APIError`. + + ``dataset`` is the assay its sequences came from: as set, the one a future it + is set to carries, or else the one its args name. """ # NOTE: This base class should be directly inherited for class discovery by the factory `create` method. session: APISession job: Job + _units: "list[FutureUnit] | None" = None + _resolved_descriptor: "MethodDescriptor | None" = None + _resolved_output: str | None = None + _fetched_args: dict[str, Any] | None = None + _submission: "_Submission | None" = None + _dataset: "AssayDataset | Future | None | object" = _UNREAD + _raises_when_canceled: ClassVar[bool] = False + def __init__(self, session: APISession, job: Job): self.session = session self.job = job @@ -83,25 +166,29 @@ def create( ------ ValueError If `job_id`, `job`, and `response` are all None. - ValueError - If an appropriate Future subclass cannot be found for the job type. :meta private: """ - # parse job - # default to use job_id first if job_id is not None: - # get job job = api.job_get(session=session, job_id=job_id) - # set obj to parse using job or response obj = job or response if obj is None: raise ValueError("Expected job_id, job or response") - # parse specific job job = Job.create(obj, **kwargs) - # Dynamically discover all subclasses of FutureBase + from . import _dispatch + + if type(job) is Job and ( + _dispatch.is_models_job(job) or _dispatch.recognizes(job) + ): + return cast(Self, _dispatch.create(session, job, **kwargs)) + + if _dispatch.is_prompt_sampling(job): + from openprotein.data.prompts import Prompt + + return cast(Self, Prompt._from_job(session, job)) + def all_subclasses(cls: Type[F]) -> Set[Type[F]]: result = set() for sub in cls.__subclasses__(): @@ -109,34 +196,58 @@ def all_subclasses(cls: Type[F]) -> Set[Type[F]]: result.update(all_subclasses(sub)) return result - future_classes = all_subclasses(Future) + future_classes = all_subclasses(Future) - {UnknownJobFuture} - # Find the Future class that matches the job - for future_class in future_classes: + matches = [] + for future_class in sorted( + future_classes, key=lambda item: (item.__module__, item.__qualname__) + ): + future_type = future_class.__annotations__.get("job") if ( - type(job) is (future_type := future_class.__annotations__.get("job")) + type(job) is future_type or isinstance(future_type, UnionType) and type(job) in future_type.__args__ ): - assert not inspect.isabstract(future_class), ( - "Expected concrete class implementation!" - ) - # instantiate the matched concrete future - if isinstance(future_class.__dict__.get("create"), classmethod): - # use the concrete factory create method if available - future = future_class.create(session=session, job=job, **kwargs) - else: - # else just init - future = future_class(session=session, job=job, **kwargs) - return future # type: ignore - needed since type checker doesnt know subclass + matches.append(future_class) + + if len(matches) > 1: + logger.warning( + "multiple future owners for %r: %s; selecting %s", + job.job_type, + ", ".join(f"{item.__module__}.{item.__qualname__}" for item in matches), + f"{matches[0].__module__}.{matches[0].__qualname__}", + ) - raise ValueError(f"Unsupported job type: {job.job_type}") + if matches: + future_class = matches[0] + assert not inspect.isabstract(future_class), ( + "Expected concrete class implementation!" + ) + if isinstance(future_class.__dict__.get("create"), classmethod): + future = future_class.create(session=session, job=job, **kwargs) + else: + future = future_class(session=session, job=job, **kwargs) + return future # type: ignore - needed since type checker doesnt know subclass + + # A job type with no typed Future resolves to one that reports its status. + logger.info( + "no typed future for job type %s; returning %s", + job.job_type, + UnknownJobFuture.__name__, + ) + return UnknownJobFuture(session=session, job=job) # type: ignore[return-value] + + def __repr__(self) -> str: + inline = getattr(self.job, "args", None) + args = inline if inline is not None else self._fetched_args + shown = _compact(args) if args is not None else "" + return ( + f"{type(self).__name__}(job_id={self.job_id!r}, status={self.status.value!r}, " + f"args={shown})" + ) def __str__(self) -> str: - return str(self.job) - - def __repr__(self): - return repr(self.job) + return repr(self) @property def id(self) -> str: @@ -150,6 +261,16 @@ def job_type(self) -> str: """The type of the job.""" return self.job.job_type + @property + def name(self) -> str | None: + """The job's name, or its job id if the job has no name.""" + return self.job.name + + @property + def description(self) -> str | None: + """The job's description, or an empty string if the job has none.""" + return self.job.description + @property def status(self) -> JobStatus: """The current status of the job.""" @@ -177,8 +298,185 @@ def progress_counter(self) -> int: @property def args(self) -> dict[str, Any]: - """The registered job arguments.""" - return api.job_args_get(self.session, job_id=self.job_id) + """The job's validated request, loaded on first access.""" + inline = getattr(self.job, "args", None) + if inline is not None: + return inline + if self._fetched_args is None: + if self.job is None: + raise APIError(f"{self.id} has no job to read args from") + self._fetched_args = job_args_get(self.session, job_id=self.job_id) or {} + return self._fetched_args + + @property + def dataset(self) -> "AssayDataset | None": + """The assay the job's sequences came from, or None; read on first access.""" + if isinstance(self._dataset, Future): + self._dataset = self._dataset.dataset + elif self._dataset is _UNREAD: + from openprotein.models._inputs import as_dataset + + args = self.args + assay_id = args.get("assay_id") or (args.get("training_dataset") or {}).get( + "assay_id" + ) + self._dataset = as_dataset(self.session, assay_id) if assay_id else None + return cast("AssayDataset | None", self._dataset) + + @dataset.setter + def dataset(self, dataset: "AssayDataset | Future | None") -> None: + self._dataset = dataset + + def _require_outputs(self) -> None: + """Raise unless this job's outputs are stored and read by position. + + A job submitted through the models API has them, as does a job whose + type names a models job, a supported models task or a prompt sampling. + """ + from . import _dispatch + + if self.job is None or not _dispatch.serves_outputs(self.job): + raise APIError(f"job {self.id} has no stored outputs to read") + + def _method(self) -> tuple[str, str]: + self._require_outputs() + if self._submission is not None: + return self._submission.model_id, self._submission.path.strip("/") + + from . import _dispatch + + provider, path = _dispatch.identity(self.job) + if not provider or not path: + self.refresh() + provider, path = _dispatch.identity(self.job) + if not provider or not path: + raise ValueError( + f"job {self.id} does not name a model and method in its job type" + ) + return provider, path + + @property + def _model_id(self) -> str: + return self._method()[0] + + @property + def _path(self) -> str: + """The method's path on its model's card, e.g. ``batch/embeddings``.""" + if self._resolved_descriptor is not None: + return self._resolved_descriptor.path + return self._method()[1].strip("/") + + @property + def units(self) -> "list[FutureUnit]": + """One handle per submitted unit, in position order. + + Each handle holds the record the listing returned as its snapshot and + selects the default output. The list is loaded on first access and read + again after the job is polled. + """ + self._require_outputs() + if self._units is None: + records = sorted( + _jobs_api_for(self.session)._iter_job_units(self.job_id), + key=lambda record: record.position, + ) + self._units = [] + for record in records: + unit = FutureUnit(self, record.position) + unit._record = record + self._units.append(unit) + return self._units + + @property + def _descriptor(self) -> "MethodDescriptor": + """This job's method, from the submitting method or else the model listing.""" + if self._resolved_descriptor is None: + model_id, path = self._method() + from openprotein.models import _api as _models_api + + metadata = _models_api.get_model(self.session, model_id) + for method in metadata.methods: + if method.path == path.strip("/"): + self._resolved_descriptor = method + break + else: + raise ValueError(f"Model {model_id!r} has no method {path}") + return self._resolved_descriptor + + @property + def outputs(self) -> list[str]: + """Output names of the submitted method, else of the model listing. + + A prompt sampling job lists the one output its results route names. + """ + self._require_outputs() + if self._resolved_descriptor is not None: + return list(self._resolved_descriptor.outputs) + from . import _dispatch + + assert self.job is not None + if _dispatch.is_prompt_sampling(self.job): + return [self._output_name(None)] + return list(self._descriptor.outputs) + + @property + def _default_output(self) -> str: + """Default output of this job's method.""" + return self._descriptor.default_output + + def unit(self, position: int, output: str | None = None) -> "FutureUnit": + """Handle on one unit's selected output. + + Creating the handle makes no request; ``None`` selects the default + output. + """ + self._require_outputs() + return FutureUnit(self, position, output) + + def _positions(self) -> list[int]: + return list(dict.fromkeys(sorted(unit.position for unit in self.units))) + + def _output_name(self, output: str | None) -> str: + self._require_outputs() + if output is not None: + return output + if self._resolved_output is None: + self._resolved_output = _api.job_default_output(self.session, self.job_id) + return self._resolved_output + + 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.""" + self._require_outputs() + name = self._output_name(output) + entry = _jobs_api_for(self.session)._get_job_output(self.job_id, position, name) + return self._convert_output(name, entry.position, entry.value) + + def stream( + self, + output: str | None = None, + *, + follow: bool = False, + interval: float = config.POLLING_INTERVAL, + ) -> Iterator[Any]: + """Stream decoded outputs in position order; ``None`` is the default output. + + An emitted output grows while the job runs. ``follow`` keeps reading, + every ``interval`` seconds, until it is complete. + """ + self._require_outputs() + + def _stream() -> Iterator[Any]: + name = self._output_name(output) + entries = _jobs_api_for(self.session)._iter_job_outputs( + self.job_id, name, follow=follow, interval=interval + ) + for entry in entries: + yield self._convert_output(name, entry.position, entry.value) + + return _stream() def done(self) -> bool: """Check if the job has completed. @@ -217,7 +515,6 @@ def _update_progress(self, job: Job) -> int: """ progress = job.progress_counter - # if progress is not None: # Check None before comparison if progress is None: if job.status == JobStatus.PENDING: progress = 5 @@ -225,11 +522,16 @@ def _update_progress(self, job: Job) -> int: progress = 25 if job.status in [JobStatus.SUCCESS, JobStatus.FAILURE]: progress = 100 - return progress or 0 # never None + return progress or 0 - def _refresh_job(self) -> Job: + def _refresh_job(self, timeout: float | None = None) -> Job: """Refresh and return the internal job object. + Parameters + ---------- + timeout : float | None, optional + Seconds the request may take. Defaults to the session timeout. + Returns ------- Job @@ -240,28 +542,57 @@ def _refresh_job(self) -> Job: kwargs = { k: v for k, v in self.job.model_dump().items() if k not in Job.model_fields } + poll = {} if timeout is None else {"timeout": timeout} job = Job.create( - api.job_get(session=self.session, job_id=self.job_id), **kwargs + api.job_get(session=self.session, job_id=self.job_id, **poll), **kwargs ) return job def refresh(self): """Refresh the job status and internal job object.""" self.job = self._refresh_job() + self._units = None - @abstractmethod - def _get(self, verbose: bool = False, **kwargs) -> V: + def rename(self, name: str | None = None, description: str | None = None): + """Set this job's name and description. + + Only the arguments given are sent, so renaming leaves the description + alone. Extra fields carried on the job are preserved, as on refresh. """ - Return the results from this job. + # dump extra kwargs to keep on rename + kwargs = { + k: v for k, v in self.job.model_dump().items() if k not in Job.model_fields + } + self.job = Job.create( + _api.job_update( + session=self.session, + job_id=self.job_id, + name=name, + description=description, + ), + **kwargs, + ) + + def _get(self, verbose: bool = False, **kwargs) -> V: + """Return every position of the selected output. Parameters ---------- verbose : bool, optional - Flag to enable verbose output, by default False. + If True, display a progress bar. Defaults to False. **kwargs - Additional keyword arguments. + Keyword arguments passed to `stream`, such as ``output``. """ - raise NotImplementedError() + generator = self.stream(**kwargs) + if verbose: + generator = tqdm.tqdm( + generator, + desc="Retrieving", + total=len(self.units), + position=0, + mininterval=1.0, + ) + return cast(V, list(generator)) def get(self, verbose: bool = False, **kwargs) -> V: if self.status == JobStatus.FAILURE: @@ -270,7 +601,7 @@ def get(self, verbose: bool = False, **kwargs) -> V: ) try: return self._get(verbose=verbose, **kwargs) - except APIError: + except (APIError, JobFailedException): raise except Exception as e: raise APIError(f"Failed to retrieve results: {e}") from e @@ -290,7 +621,9 @@ def _wait_job( Defaults to `config.POLLING_INTERVAL`. timeout : int | None, optional Maximum time in seconds to wait before raising an error. - Defaults to None (unlimited). + Defaults to None (unlimited). The timeout is checked between + polls, and a stalled poll is retried before it fails, so the + wait can run past it. verbose : bool, optional If True, print status updates. Defaults to False. @@ -307,40 +640,54 @@ def _wait_job( """ start_time = time.time() + def remaining() -> float | None: + if timeout is None: + return None + elapsed_time = time.time() - start_time + if elapsed_time >= timeout: + raise TimeoutException( + f"Wait time exceeded timeout {timeout}, waited {elapsed_time}" + ) + return timeout - elapsed_time + + def poll() -> Job: + budget = remaining() + if budget is None: + return self._refresh_job() + session_timeout = self.session.timeout + if isinstance(session_timeout, (int, float)): + budget = min(budget, session_timeout) + try: + return self._refresh_job(timeout=budget) + except requests.exceptions.RequestException as e: + if timeout is None or time.time() - start_time < timeout: + raise + raise TimeoutException( + f"Wait time exceeded timeout {timeout} while polling job {self.job_id}" + ) from e + def is_done(job: Job): - if timeout is not None: - elapsed_time = time.time() - start_time - if elapsed_time >= timeout: - raise TimeoutException( - f"Wait time exceeded timeout {timeout}, waited {elapsed_time}" - ) + remaining() return job.status.done() pbar = None if verbose: pbar = tqdm.tqdm(total=100, desc="Waiting", position=0) - job = self._refresh_job() + job = poll() while not is_done(job): if pbar is not None: - # pbar.update(1) - # pbar.set_postfix({"status": job.status}) progress = self._update_progress(job) pbar.n = progress pbar.set_postfix({"status": job.status}) - # pbar.refresh() - # print(f'Retry {retries}, status={self.job.status}, time elapsed {time.time() - start_time:.2f}') - time.sleep(interval) - job = self._refresh_job() + budget = remaining() + time.sleep(interval if budget is None else min(interval, budget)) + job = poll() if pbar is not None: - # pbar.update(1) - # pbar.set_postfix({"status": job.status}) - progress = self._update_progress(job) pbar.n = progress pbar.set_postfix({"status": job.status}) - # pbar.refresh() return job @@ -357,22 +704,27 @@ def wait_until_done( interval : float, optional Time in seconds between polling. Defaults to `config.POLLING_INTERVAL`. timeout : int, optional - Maximum time in seconds to wait. Defaults to None. + Maximum time in seconds to wait. Defaults to None. The timeout is + checked between polls, and a stalled poll is retried before it + fails, so the wait can run past it. verbose : bool, optional Verbosity flag. Defaults to False. Returns ------- bool - True if the job completed successfully. + True if the job reached a terminal status (success, failure or cancellation). Notes ----- - This method does not fetch the job results, unlike `wait()`. + This method refreshes the stored job but does not fetch results, unlike + `wait()`. Check `status` for success or failure. A polling timeout raises + `TimeoutException`. """ job = self._wait_job(interval=interval, timeout=timeout, verbose=verbose) self.job = job + self._units = None return self.done() def wait( @@ -380,6 +732,7 @@ def wait( interval: int = config.POLLING_INTERVAL, timeout: int | None = None, verbose: bool = False, + **kwargs, ) -> V: """Wait for the job to complete, then fetch results. @@ -388,27 +741,75 @@ def wait( interval : int, optional Time in seconds between polling. Defaults to `config.POLLING_INTERVAL`. timeout : int | None, optional - Maximum time in seconds to wait. Defaults to None. + Maximum time in seconds to wait. Defaults to None. The timeout is + checked between polls, and a stalled poll is retried before it + fails, so the wait can run past it. verbose : bool, optional Verbosity flag. Defaults to False. + **kwargs + Keyword arguments passed to `get`. Returns ------- Any The results of the job. + Raises + ------ + TimeoutException + If polling exceeds the timeout. + JobFailedException + If the job was canceled and is a result future or stores outputs. + A failed job raises on the read. + + Notes + ----- + A terminal status does not necessarily mean success. This method + updates the stored job and calls ``get``, whose errors depend on the + result reader. """ - time.sleep(1) # buffer for BE to register job + time.sleep(1) # allow the job to register before polling job = self._wait_job(interval=interval, timeout=timeout, verbose=verbose) self.job = job - return self.get() + self._units = None + if self.job is not None and self.status is JobStatus.CANCELED: + from . import _dispatch + + if self._raises_when_canceled or _dispatch.serves_outputs(self.job): + raise JobFailedException(self.job_id, "the job was canceled") + return self.get(**kwargs) + + +class UnknownJobFuture(Future[None]): + """A job whose type no installed Future claims. + + Identity, status and waiting work, so a caller can track the job. ``get`` + and ``wait`` report that this client has no typed support for the job type. + The reads of stored outputs (``units``, ``get_item``, ``stream`` and the + like) work when the job type stores outputs and raise an `APIError` + otherwise. + """ + + job: Job + + def get(self, verbose: bool = False, **kwargs) -> None: + """Report that this client cannot type this job's result.""" + raise NotImplementedError( + f"no typed result support for job type {self.job.job_type!r}; " + "upgrade openprotein-python to read it" + ) + + def _get(self, verbose: bool = False, **kwargs) -> None: + return self.get(verbose=verbose, **kwargs) class StreamingFuture(Future[list[V]], ABC, Generic[V]): """Abstract base class for Futures that support streaming results.""" @abstractmethod - def stream(self, **kwargs) -> Iterator[V]: + def stream( # ty: ignore[invalid-method-override] + self, **kwargs + ) -> Iterator[V]: """Return the results from this job as a generator. Parameters @@ -421,11 +822,6 @@ def stream(self, **kwargs) -> Iterator[V]: Generator A generator that yields job results. - Raises - ------ - NotImplementedError - This is an abstract method and must be implemented by a subclass. - """ raise NotImplementedError() @@ -460,8 +856,9 @@ def wait( interval: int = config.POLLING_INTERVAL, timeout: int | None = None, verbose: bool = False, + **kwargs, ) -> list[V]: - return super().wait(interval, timeout, verbose) + return super().wait(interval, timeout, verbose, **kwargs) class MappedFuture(StreamingFuture[tuple[K, V]], ABC, Generic[K, V]): @@ -495,25 +892,19 @@ def __init__( Use `max_workers` > 0 to enable concurrent retrieval. """ - self.session = session - self.job = job + super().__init__(session, job) self.max_workers = max_workers self._cache = {} @abstractmethod def __keys__(self) -> KeysView[K]: - """Return the keys for the mapped results. - - Raises - ------ - NotImplementedError - This is an abstract method and must be implemented by a subclass. - - """ + """Return the keys for the mapped results.""" raise NotImplementedError() @abstractmethod - def get_item(self, k: K, **kwargs) -> V: + def get_item( # ty: ignore[invalid-method-override] + self, k: K, **kwargs + ) -> V: """Retrieve a single item by its key. Parameters @@ -521,11 +912,6 @@ def get_item(self, k: K, **kwargs) -> V: k The key of the item to retrieve. - Raises - ------ - NotImplementedError - This is an abstract method and must be implemented by a subclass. - """ raise NotImplementedError() @@ -586,8 +972,9 @@ def wait( interval: int = config.POLLING_INTERVAL, timeout: int | None = None, verbose: bool = False, + **kwargs, ) -> list[tuple[K, V]]: - return super().wait(interval, timeout, verbose) + return super().wait(interval, timeout, verbose, **kwargs) def __getitem__(self, k: K, **kwargs) -> V: """Get an item by key, using the cache if available. @@ -682,11 +1069,6 @@ def get_slice(self, start: int, end: int, **kwargs) -> Collection[V]: Collection A collection of results for the specified slice. - Raises - ------ - NotImplementedError - This is an abstract method and must be implemented by a subclass. - """ raise NotImplementedError() @@ -718,12 +1100,6 @@ def stream_parallel(self) -> Generator[V, None, None]: Any Individual results from the paged endpoint. - Notes - ----- - The number of results should be checked, or stored somehow, so that - we don't need to check the number of returned entries to see if we're - finished (very awkward when using concurrency). - :meta private: """ step = self.page_size @@ -806,3 +1182,835 @@ def __init__(self, future: Future, expected: type[Future]): self.expected = future self.message = f"Expected future of type {expected}, got {type(future)}" super().__init__(self.message) + + +class FutureUnit(Generic[V]): + """One ``(job, position, output)`` of a job that stores its outputs by position. + + A unit finishes on its own: its output is readable as soon as it is stored, + whether or not its job's other units are done. ``job_id`` and ``position`` + need no request, nor does a named ``output``; the default output is resolved + on first access. + + ``unit_id``, ``status`` and ``error`` are a snapshot: the record a listing + returned, or one read of this position on first access. `refresh` reads the + record again; reading the snapshot makes no request. A unit reports its + ``status`` as a `JobStatus`. + """ + + def __init__( + self, + future: "Future", + position: int, + output: str | None = None, + ) -> None: + self._future = future + self._position = position + self._output = output + self._record: _UnitRecord | None = None + + def __repr__(self) -> str: + output = "" if self._output is None else self._output + return ( + f"FutureUnit(job_id={self.job_id!r}, position={self._position}, " + f"output={output!r})" + ) + + @property + def job_id(self) -> str: + """Identifier of the job containing this unit.""" + return self._future.job_id + + @property + def position(self) -> int: + """Zero-based position of this unit within the job.""" + return self._position + + @property + def output(self) -> str: + """Name of the output selected for this unit.""" + if self._output is None: + self._output = self._future._output_name(None) + return self._output + + @property + def unit_id(self) -> str: + """The immutable authored identity of this submitted unit.""" + return self._snapshot().unit_id + + @property + def status(self) -> JobStatus: + """The unit's status in the snapshot.""" + return self._snapshot().status + + @property + def error(self) -> dict[str, Any] | None: + """The unit's error in the snapshot, or None.""" + return self._snapshot().error + + def _snapshot(self) -> _UnitRecord: + if self._record is None: + self.refresh() + assert self._record is not None + return self._record + + def refresh(self) -> None: + """Read this position's record again.""" + self._record = _api.get_unit(self._future.session, self.job_id, self._position) + + def done(self) -> bool: + """Whether the unit has finished, as the snapshot reports it. + + Returns + ------- + bool + True for a unit that succeeded, failed or was canceled. + """ + return self.status.done() + + def _raise_if_unsuccessful(self) -> None: + """Raise `JobFailedException` when the snapshot is failed or canceled.""" + record = self._record + if record is None: + return + if record.status is JobStatus.FAILURE: + message = (record.error or {}).get("message") + raise JobFailedException( + self.job_id, + f"unit {self._position} failed: {message}" + if message + else f"unit {self._position} failed", + ) + if record.status is JobStatus.CANCELED: + raise JobFailedException(self.job_id, f"unit {self._position} was canceled") + + def get(self) -> V: + """Fetch and decode this unit's selected output. + + Raises + ------ + JobFailedException + If the unit failed or was canceled, as the snapshot reports or as a + refresh after a missing output shows. + """ + self._raise_if_unsuccessful() + try: + return self._future.get_item(self._position, output=self.output) + except HTTPError as error: + if error.status_code != 404: + raise + try: + self.refresh() + except Exception as refresh_error: + raise error from refresh_error + self._raise_if_unsuccessful() + raise + + def wait( + self, + interval: float = config.POLLING_INTERVAL, + timeout: int | None = None, + verbose: bool = False, + ) -> V: + """Block until this unit is done, then return its output. + + Parameters + ---------- + interval : float, optional + Time in seconds between reads. Defaults to `config.POLLING_INTERVAL`. + timeout : int | None, optional + Maximum time in seconds to wait. Defaults to None (unlimited). + verbose : bool, optional + If True, print the unit's status on each read. Defaults to False. + + Returns + ------- + Any + The unit's decoded output. + + Raises + ------ + TimeoutException + If the unit is unfinished after ``timeout`` seconds. + JobFailedException + If the unit failed or was canceled. + """ + deadline = None if timeout is None else time.time() + timeout + while True: + self.refresh() + status = self.status + self._raise_if_unsuccessful() + if status is JobStatus.SUCCESS: + return self.get() + if verbose: + print(f"Waiting on unit {self._position}: {status.value}") + remaining = None if deadline is None else deadline - time.time() + if remaining is not None and remaining <= 0: + raise TimeoutException( + f"unit {self._position} of job {self.job_id} is " + f"{status.value} after {timeout}s" + ) + time.sleep(interval if remaining is None else min(interval, remaining)) + + +_M = TypeVar("_M") + + +@dataclass(frozen=True) +class _Submission: + """The model, method path and params a job was submitted with.""" + + model_id: str + path: str + params: dict[str, Any] = field(default_factory=dict) + + +class FitFuture(Future, Generic[_M]): + """Handle on a job that fits a model; ``wait`` returns the fitted model. + + A fit has no model card method; each fit future lists its own outputs. + """ + + _family: ClassVar[str] + _fit_outputs: ClassVar[tuple[str, ...]] = () + _raises_when_canceled = True + + @property + def _descriptor(self) -> "MethodDescriptor": + raise ValueError(f"fit job {self.id} has no model method; see outputs") + + @property + def outputs(self) -> list[str]: + """Output names of this kind of fit.""" + self._require_outputs() + return list(self._fit_outputs) + + @property + def _default_output(self) -> str: + """The fit's first output.""" + if not self.outputs: + raise ValueError(f"fit job {self.id} has no outputs") + return self.outputs[0] + + def _fitted(self) -> _M: + raise NotImplementedError + + @overload + def get(self, verbose: bool = False, output: None = None, **kwargs: Any) -> _M: ... + + @overload + def get( + self, verbose: bool = False, output: str | None = None, **kwargs: Any + ) -> list[Any]: ... + + def get(self, verbose: bool = False, output: str | None = None, **kwargs) -> Any: + """Read the fitted model, or a named output of its fit.""" + return super().get(verbose=verbose, output=output, **kwargs) + + @overload + def wait( + self, + interval: float = config.POLLING_INTERVAL, + timeout: int | None = None, + verbose: bool = False, + output: None = None, + **kwargs: Any, + ) -> _M: ... + + @overload + def wait( + self, + interval: float = config.POLLING_INTERVAL, + timeout: int | None = None, + verbose: bool = False, + output: str | None = None, + **kwargs: Any, + ) -> list[Any]: ... + + def wait( + self, + interval: float = config.POLLING_INTERVAL, + timeout: int | None = None, + verbose: bool = False, + output: str | None = None, + **kwargs: Any, + ) -> Any: + """Wait for the fit, then read the fitted model, or a named output of its fit.""" + self.wait_until_done(interval=interval, timeout=timeout, verbose=verbose) + if self.status is not JobStatus.SUCCESS: + raise JobFailedException(self.job_id, self.job.failure_message) + return self.get(verbose=verbose, output=output, **kwargs) + + def _get(self, verbose: bool = False, **kwargs) -> Any: + """The fitted model, or with ``output`` that output of the fit job.""" + if kwargs.get("output") is not None: + return super()._get(verbose=verbose, **kwargs) + return self._fitted() + + +def _compact(value: Any) -> str: + """A one-line view of job args that counts lists and elides long strings.""" + if isinstance(value, dict): + items = ", ".join(f"{key!r}: {_compact(item)}" for key, item in value.items()) + return "{" + items + "}" + if isinstance(value, (list, tuple)): + return f"<{len(value)} items>" + if isinstance(value, str) and len(value) > 32: + return f"" + return repr(value) + + +_V = TypeVar("_V") +_Scores = float | list[float] | np.ndarray +_Predictions = dict[str, Any] +#: JSON has no non-finite numbers, so the API spells them out. +_NON_FINITE = {"nan": math.nan, "inf": math.inf, "-inf": -math.inf} + + +def _numbers(value: Any) -> Any: + """``value`` with the spelt-out non-finite numbers read as floats.""" + if isinstance(value, str): + return _NON_FINITE.get(value, value) + if isinstance(value, list): + return [_numbers(item) for item in value] + if isinstance(value, dict): + return {key: _numbers(item) for key, item in value.items()} + return value + + +#: structure outputs stored as CSV text, read as one table per position +_TABLE_OUTPUTS = frozenset({"score", "metrics"}) + + +def _as_structure(value: Any) -> Structure: + if isinstance(value, Structure): + structure = value + elif isinstance(value, Complex): + structure = Structure([value]) + elif isinstance(value, (str, bytes)): + structure = Structure.from_string(value, format="cif", verbose=False) + else: + raise TypeError( + "structure output must be mmCIF, Complex or Structure; " + f"received {type(value).__name__}" + ) + + if not len(structure) or any( + not structure[i].get_chains() for i in range(len(structure)) + ): + raise ValueError("structure output contains no molecular chains") + return structure + + +def _as_table(value: str | bytes) -> pd.DataFrame: + text = value.decode() if isinstance(value, bytes) else value + return pd.read_csv(io.StringIO(text)) + + +def _as_complex(value: Any) -> Complex: + if isinstance(value, Complex): + if not value.get_chains(): + raise ValueError("structure output contains no molecular chains") + return value + structure = _as_structure(value) + if len(structure) != 1: + raise ValueError("a design position must contain exactly one complex") + return structure[0] + + +class _ResultFuture(Future[list[_V]], Generic[_V]): + """Positional results whose bare reads select the task's primary output. + + Bare reads use the task's named output rather than the job's default + output; pass ``output=`` to read another name in ``outputs``. + """ + + _primary_output: ClassVar[str] + _raises_when_canceled = True + + def __init__(self, session: APISession, job: Job): + super().__init__(session, job) + self._cache: dict[Any, Any] = {} + + def __keys__(self) -> KeysView[int]: + return dict.fromkeys(self._positions()).keys() + + def __len__(self) -> int: + return len(self.__keys__()) + + def _output_name(self, output: str | None) -> str: + return super()._output_name(self._primary_output if output is None else output) + + @overload + def get( + self, verbose: bool = False, output: None = None, **kwargs: Any + ) -> list[_V]: ... + + @overload + def get( + self, verbose: bool = False, output: str | None = None, **kwargs: Any + ) -> list[Any]: ... + + def get( + self, verbose: bool = False, output: str | None = None, **kwargs: Any + ) -> Any: + """Read every position of the selected output.""" + return super().get(verbose=verbose, output=output, **kwargs) + + @overload + def wait( + self, + interval: int = config.POLLING_INTERVAL, + timeout: int | None = None, + verbose: bool = False, + *, + output: None = None, + **kwargs: Any, + ) -> list[_V]: ... + + @overload + def wait( + self, + interval: int = config.POLLING_INTERVAL, + timeout: int | None = None, + verbose: bool = False, + *, + output: str | None = None, + **kwargs: Any, + ) -> list[Any]: ... + + def wait( + self, + interval: int = config.POLLING_INTERVAL, + timeout: int | None = None, + verbose: bool = False, + *, + output: str | None = None, + **kwargs: Any, + ) -> Any: + """Wait for completion and read the selected output.""" + return super().wait( + interval=interval, + timeout=timeout, + verbose=verbose, + output=output, + **kwargs, + ) + + @overload + def get_item(self, position: int, output: None = None) -> _V: ... + + @overload + def get_item(self, position: int, output: str | None = None) -> Any: ... + + def get_item(self, position: int, output: str | None = None) -> Any: + """Read one submitted position of the selected output.""" + return super().get_item(position, output=output) + + @overload + def stream( + self, + output: None = None, + *, + follow: bool = False, + interval: float = config.POLLING_INTERVAL, + ) -> Iterator[_V]: ... + + @overload + def stream( + self, + output: str | None = None, + *, + follow: bool = False, + interval: float = config.POLLING_INTERVAL, + ) -> Iterator[Any]: ... + + def stream( + self, + output: str | None = None, + *, + follow: bool = False, + interval: float = config.POLLING_INTERVAL, + ) -> Iterator[Any]: + """Yield selected values in submitted position order.""" + return super().stream(output=output, follow=follow, interval=interval) + + @property + def units(self) -> list[FutureUnit[_V]]: + """One handle per submitted unit, in position order.""" + return super().units + + @overload + def unit(self, position: int, output: None = None) -> FutureUnit[_V]: ... + + @overload + def unit(self, position: int, output: str | None = None) -> FutureUnit[Any]: ... + + def unit(self, position: int, output: str | None = None) -> FutureUnit[Any]: + """Handle on one unit's selected output.""" + return super().unit(position, output=output) + + @overload + def __getitem__(self, k: int) -> _V: ... + + @overload + def __getitem__(self, k: int, **kwargs: Any) -> Any: ... + + def __getitem__(self, k: int, **kwargs: Any) -> Any: + """Read one position, caching the value per position and keyword arguments.""" + key = ( + (k, *(f"{name}={value}" for name, value in kwargs.items())) if kwargs else k + ) + if key not in self._cache: + self._cache[key] = self.get_item(k, **kwargs) + return self._cache[key] + + def __iter__(self) -> Iterator[_V]: + return self.stream() + + +class EmbeddingFuture(_ResultFuture[np.ndarray]): + """Embedding arrays, one per submitted position. + + Bare reads return the ``embeddings`` output; pass ``output=`` to read another + name in ``outputs``. + """ + + _primary_output = "embeddings" + + +class LogitsFuture(_ResultFuture[np.ndarray]): + """Per-position logit arrays. + + Bare reads return the ``logits`` output; pass ``output=`` to read another + name in ``outputs``. + """ + + _primary_output = "logits" + + +class AttentionFuture(_ResultFuture[np.ndarray]): + """Attention arrays with the model's head and residue dimensions. + + Bare reads return the ``attn`` output; pass ``output=`` to read another + name in ``outputs``. + """ + + _primary_output = "attn" + + +class LogLikelihoodFuture(_ResultFuture[_Scores]): + """Sequence log-likelihoods, one per submitted sequence in the order submitted. + + A score is a float, or one float per prompt replicate when the prompt has + several: ``np.asarray(future.get(), dtype=float)`` has shape ``(n,)`` or + ``(n, replicates)``. + + Bare reads return the ``loglikelihood`` output; pass ``output=`` to read another + name in ``outputs``. + """ + + _primary_output = "loglikelihood" + + def _convert_output(self, output: str, position: int, value: Any) -> Any: + return _numbers(value) + + +class SingleSiteScoreFuture(_ResultFuture[_Scores]): + """Scores of every single-site substitution of the base sequence. + + Positions run in sequence order. At each position the substitutions run in + the order of ``openprotein.utils.sequence.AMINO_ACIDS``, the position's own + residue included, so a scanned position has 20 scores. Chain breaks (``:``) + and gaps (``-``) are not scanned; with PoET's ``include_gaps``, gaps are + scanned too and ``-`` is a 21st substitution. A score is a float, or one + float per prompt replicate. + + Bare reads return the ``score`` output; pass ``output=`` to read another + name in ``outputs``. + """ + + _primary_output = "score" + + def _convert_output(self, output: str, position: int, value: Any) -> Any: + return _numbers(value) + + +class IndelScoreFuture(_ResultFuture[_Scores]): + """Scores of the base sequence, then of each insertion or deletion. + + The first score is the base sequence's. With ``delete``, each size follows + in the order given, at every start from the first residue, with ``insert`` + in place of the deleted fragment when both are given. With ``insert`` + alone, the insertion follows at every site, from before the first residue + to after the last. A score is a float, or one float per prompt replicate. + + Bare reads return the ``score`` output; pass ``output=`` to read another + name in ``outputs``. + """ + + _primary_output = "score" + + def _convert_output(self, output: str, position: int, value: Any) -> Any: + return _numbers(value) + + +class SequenceGenerationFuture(_ResultFuture[str]): + """Generated sequence strings in sample order. + + Bare reads return the ``sequences`` output; pass ``output=`` to read another + name in ``outputs``. + """ + + _primary_output = "sequences" + + def _convert_output(self, output: str, position: int, value: Any) -> Any: + return _numbers(value) if output == "loglikelihood" else value + + +class PredictionFuture(_ResultFuture[_Predictions]): + """Property-keyed predictions, one dictionary per position. + + Bare reads return the ``predictions`` output; pass ``output=`` to read another + name in ``outputs``. + """ + + _primary_output = "predictions" + + def _convert_output(self, output: str, position: int, value: Any) -> Any: + return _numbers(value) + + +class SingleSitePredictionFuture(_ResultFuture[_Predictions]): + """Property-keyed predictions in single-site mutation order. + + Bare reads return the ``predictions`` output; pass ``output=`` to read another + name in ``outputs``. + """ + + _primary_output = "predictions" + + def _convert_output(self, output: str, position: int, value: Any) -> Any: + return _numbers(value) + + +class StructureDesignFuture(_ResultFuture[Complex]): + """Generated complexes, one per design position. + + Bare reads return the ``structures`` output; pass ``output=`` to read another + name in ``outputs``. + """ + + _primary_output = "structures" + + def _convert_output(self, output: str, position: int, value: Any) -> Any: + if output != "structures": + return value + try: + return _as_complex(value) + except (TypeError, ValueError) as error: + raise type(error)(f"job {self.id} position {position}: {error}") from error + + +class StructurePredictionFuture(_ResultFuture[Structure]): + """Predicted structure collections, one per submitted input. + + Bare reads return the ``structures`` output; pass ``output=`` to read another + name in ``outputs``. RoseTTAFold3's ``score`` and ``metrics`` read as one + ``pandas.DataFrame`` per input. + """ + + _primary_output = "structures" + + def _convert_output(self, output: str, position: int, value: Any) -> Any: + try: + if output == "structures": + return _as_structure(value) + if output in _TABLE_OUTPUTS and isinstance(value, (str, bytes)): + return _as_table(value) + except (TypeError, ValueError) as error: + raise type(error)(f"job {self.id} position {position}: {error}") from error + return value + + +@dataclass +class CrossvalidateResults: + """Cross-validation results as parallel arrays, one per sequence x measurement. + + Attributes + ---------- + row_index : np.ndarray + Position in the uploaded assay of the row each evaluation came from. This is + the index the ``folds`` argument of `crossvalidate` is given in. + sequence : np.ndarray + Sequence for each evaluation. + measurement_name : np.ndarray + Measurement/property name for each evaluation. + fold : np.ndarray or None + Held-out test fold the row was scored in, or -1 if the row was excluded, in + which case ``y_mu`` and ``y_var`` are NaN. None for a crossvalidation the + service reported without fold assignments. + y : np.ndarray + Observed value. + y_mu : np.ndarray + Cross-validated predicted mean. + y_var : np.ndarray + Cross-validated predicted variance. + """ + + row_index: np.ndarray + sequence: np.ndarray + measurement_name: np.ndarray + fold: np.ndarray | None + y: np.ndarray + y_mu: np.ndarray + y_var: np.ndarray + + +def _reject_output(future: Future, output: str | None) -> None: + """Raise for an output name on a future that has one result.""" + if output is not None: + raise ValueError( + f"{type(future).__name__} has one result; call get() without output" + ) + + +class CrossvalidateFuture(Future): + """Handle on a cross-validation job; its id is the evaluation's. + + ``get`` and ``wait`` return its `CrossvalidateResults`. The run's statistics are read + with ``GPModel.evaluations``. A reloaded cross-validation job loads as + ``CVResultFuture`` instead. + """ + + _raises_when_canceled = True + + def __init__(self, session: APISession, job: Job, gp: "GPModel"): + super().__init__(session, job) + self._gp = gp + + def get( + self, verbose: bool = False, output: str | None = None, **kwargs: Any + ) -> CrossvalidateResults: + """Read the cross-validated prediction of each assay row. + + Raises + ------ + ValueError + If ``output`` is given; the future has one result. + """ + _reject_output(self, output) + return super().get(verbose=verbose, output=output, **kwargs) + + def wait( + self, + interval: int = config.POLLING_INTERVAL, + timeout: int | None = None, + verbose: bool = False, + **kwargs: Any, + ) -> CrossvalidateResults: + """Wait for cross-validation and read its predictions. + + Raises + ------ + ValueError + If ``output`` is given; the future has one result. + """ + _reject_output(self, kwargs.get("output")) + return super().wait( + interval=interval, timeout=timeout, verbose=verbose, **kwargs + ) + + def _get(self, verbose: bool = False, **kwargs: Any) -> Any: + rows = self._gp.evaluations(self.id)["rows"] + folds = [row.get("fold") for row in rows] + + def measured(name: str) -> np.ndarray: + return np.array( + [np.nan if row[name] is None else row[name] for row in rows], + dtype=float, + ) + + return CrossvalidateResults( + row_index=np.array([row["row_index"] for row in rows], dtype=int), + sequence=np.array([row["sequence"] for row in rows], dtype=object), + measurement_name=np.array([row["property"] for row in rows], dtype=object), + fold=None + if any(fold is None for fold in folds) + else np.array(folds, dtype=int), + y=measured("y"), + y_mu=measured("mean"), + y_var=measured("variance"), + ) + + +class GPFitFuture(FitFuture["GPModel"]): + """Handle on a GP's training job. + + ``wait`` returns the fitted ``GPModel``. A reloaded training job loads as + ``PredictorModel`` instead. + """ + + _family = "gp" + + def _fitted(self) -> "GPModel": + from openprotein.models.gp import _load + + return _load(self.session, self.id) + + +class SVDFitFuture(FitFuture["SVDModel"]): + """Handle on an SVD fit job. + + Its output is the fit's source sequences. + """ + + _family = "svd" + _fit_outputs = ("sequences",) + + def _fitted(self) -> "SVDModel": + from openprotein.models.svd import _load + + return _load(self.session, self.id) + + def transform( + self, data: "list[str] | list[bytes] | AssayDataset" + ) -> EmbeddingFuture: + """Project sequences, or an assay's, through this fit. + + The projection is submitted now and runs once the fit has finished. + """ + from openprotein.models.model import _project + + return _project(self, data) + + def embed(self, data: "list[str] | list[bytes] | AssayDataset") -> EmbeddingFuture: + """Same as ``transform``.""" + return self.transform(data) + + +class UMAPFitFuture(FitFuture["UMAPModel"]): + """Handle on a UMAP fit job; its outputs are the fit set's projections.""" + + _family = "umap" + _fit_outputs = ("sequences", "embeddings") + + def _fitted(self) -> "UMAPModel": + from openprotein.models.umap import _load + + return _load(self.session, self.id) + + def transform( + self, data: "list[str] | list[bytes] | AssayDataset" + ) -> EmbeddingFuture: + """Map sequences, or an assay's, through this fit. + + The projection is submitted now and runs once the fit has finished. + """ + from openprotein.models.model import _project + + return _project(self, data) + + def embed(self, data: "list[str] | list[bytes] | AssayDataset") -> EmbeddingFuture: + """Same as ``transform``.""" + return self.transform(data) diff --git a/openprotein/jobs/jobs.py b/openprotein/jobs/jobs.py index 010bfef..cce3670 100644 --- a/openprotein/jobs/jobs.py +++ b/openprotein/jobs/jobs.py @@ -1,12 +1,33 @@ +from __future__ import annotations + +import builtins +import time +from collections import deque +from collections.abc import Iterator +from concurrent.futures import Future as Pending +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass from datetime import datetime from typing import Any from openprotein import config from openprotein.base import APISession +from openprotein.errors import JobFailedException -from . import api +from . import _api, _decode, _storage, api from .futures import Future -from .schemas import Job, JobStatus, JobType +from .schemas import Job, JobStatus, JobType, _UnitRecord + +__all__ = ["JobsAPI"] + + +@dataclass(frozen=True, slots=True) +class _JobOutput: + """One decoded canonical output at its original position.""" + + position: int + unit_id: str + value: Any class JobsAPI: @@ -14,28 +35,31 @@ class JobsAPI: def __init__(self, session: APISession): self.session = session + self._storage = _storage.DirectArtifactStorage() - # `list` shadows the builtin, so the return annotation is quoted to keep it - # resolving to the builtin (not this method) under PEP 649 deferred evaluation. + # Qualify `list` because the method name shadows the builtin in annotations. def list( self, status: JobStatus | None = None, - job_type: JobType | None = None, + job_type: str | JobType | None = None, assay_id: str | None = None, more_recent_than: datetime | str | None = None, page_size: int | None = None, page_offset: int | None = None, limit: int | None = None, - ) -> "list[Job]": + *, + name: str | None = None, + ) -> builtins.list[Job]: """List jobs. + `name` matches a job's name exactly; set one with `update`. Names are + not unique, so the result stays a list. + Pass `page_size` / `page_offset` to paginate. `limit` is a deprecated alias for `page_size` — pass one, not both. """ if limit is not None and page_size is not None: - raise ValueError( - "Pass either page_size or limit (deprecated), not both" - ) + raise ValueError("Pass either page_size or limit (deprecated), not both") if page_size is None: page_size = limit if limit is not None else 100 more_recent_than_str = ( @@ -50,6 +74,7 @@ def list( status=status, job_type=job_type, assay_id=assay_id, + name=name, more_recent_than=more_recent_than_str, page_size=page_size, page_offset=page_offset, @@ -59,22 +84,147 @@ def list( def get_job(self, job_id: str) -> Job: return api.job_get(session=self.session, job_id=job_id) + def _iter_job_outputs( + self, + job_id: str, + output_name: str | None, + *, + follow: bool = False, + interval: float = config.POLLING_INTERVAL, + ) -> Iterator[_JobOutput]: + """Stream decoded outputs in submission order, retaining duplicate positions. + + 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. + + 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) + pending: deque[Pending[_JobOutput]] = deque() + try: + for 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: + yield pending.popleft().result() + if not values: + while pending: + yield pending.popleft().result() + while pending: + yield pending.popleft().result() + finally: + pool.shutdown(cancel_futures=True) + + def _iter_output_pages( + self, + job_id: str, + 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.""" + 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 + next_cursor = page.get("next_cursor") + if not next_cursor: + return + if not values and next_cursor == cursor: + if not follow: + return + time.sleep(interval) + cursor = next_cursor + + def _decode_job_output(self, job_id: str, 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") + if entry.get("value") is None and entry.get("error") is not None: + raise JobFailedException( + job_id, f"output at position {position} failed: {entry['error']}" + ) + return _JobOutput( + position=position, + unit_id=str(entry["unit_id"]), + value=_decode.decode_value(entry.get("value"), self._storage), + ) + + def _get_job_output( + self, job_id: str, position: int, output_name: str + ) -> _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) + ) + + def _iter_job_units(self, job_id: str) -> Iterator[_UnitRecord]: + """Read the job's unit records in position order, without waiting for outputs.""" + position: int | None = None + while True: + page = _api.job_unit_page(self.session, job_id, position=position) + for item in page.get("units", []): + yield _UnitRecord.model_validate(item) + next_position = page.get("next_position") + if next_position is None: + return + if ( + type(next_position) is not int + or next_position < 0 + or (position is not None and next_position <= position) + ): + raise ValueError("invalid unit metadata pagination position") + position = next_position + def get_job_args(self, job_id: str) -> dict[str, Any]: return api.job_args_get(session=self.session, job_id=job_id) - def get(self, job_id: str, verbose: bool = False) -> Future: # Job: + def update( + self, + job_id: str, + name: str | None = None, + description: str | None = None, + ) -> Job: + """Set a job's name and description. + + Only the arguments given are sent, so renaming a job leaves its + description alone. + """ + return _api.job_update( + session=self.session, + job_id=job_id, + name=name, + description=description, + ) + + def get(self, job_id: str, verbose: bool = False) -> Future: """ Get job by ID. Notes ----- This retrieves the job and loads it as a future so you can do `wait` and `get`. + + Supported models-task records load their typed result future. Records + owned by compatibility schemas retain their compatibility future, including + when they carry provider and method metadata. GP training loads + `PredictorModel`, GP cross-validation loads `CVResultFuture`, and prompt + sampling loads the `Prompt` it samples, which is a stored prompt and not + a `Future`. Each class documents its result contract. An unresolved + models identity remains a generic, trackable `Future`. """ return self.__load(job_id=job_id) - # return Job.create(job.job_get(session=self.session, job_id=job_id)) def __load(self, job_id: str) -> Future: - """Loads a job by ID and returns the future.""" return Future.create(session=self.session, job_id=job_id) def wait( diff --git a/openprotein/jobs/schemas.py b/openprotein/jobs/schemas.py index e3cd992..677310c 100644 --- a/openprotein/jobs/schemas.py +++ b/openprotein/jobs/schemas.py @@ -1,12 +1,22 @@ import logging from datetime import datetime from enum import Enum -from typing import Union - -from pydantic import BaseModel, ConfigDict, TypeAdapter +from types import UnionType +from typing import Any, Literal, Union, get_args, get_origin + +from pydantic import ( + BaseModel, + ConfigDict, + TypeAdapter, + ValidationError, + model_validator, +) from requests import Response from typing_extensions import Self +__all__ = ["BatchJob", "Job", "JobStatus", "JobType"] + + logger = logging.getLogger(__name__) @@ -14,7 +24,10 @@ class JobType(str, Enum): """ Type of job. - Describes the types of jobs that can be done. + The job types this client has names for. ``Job.job_type`` is a plain string + and the server adds types on its own release cycle, so this is a vocabulary + for readability, for filtering, and for the ``Literal`` discriminators on + typed ``Job`` subclasses. Membership is not a validity check. """ stub = "stub" @@ -69,8 +82,11 @@ class JobType(str, Enum): # designer designer = "/design" + models = "/models" + class JobStatus(str, Enum): + CREATED = "CREATED" PENDING = "PENDING" RUNNING = "RUNNING" SUCCESS = "SUCCESS" @@ -81,7 +97,7 @@ class JobStatus(str, Enum): def done(self): return ( (self is self.SUCCESS) or (self is self.FAILURE) or (self is self.CANCELED) - ) # noqa: E501 + ) def cancelled(self): return self is self.CANCELED @@ -89,7 +105,6 @@ def cancelled(self): class Job(BaseModel): job_id: str - # new emb service get doesnt have job_type job_type: str status: JobStatus created_date: datetime @@ -100,22 +115,53 @@ class Job(BaseModel): progress_counter: int | None = None sequence_length: int | None = None failure_message: str | None = None + name: str | None = None + description: str | None = None + metadata: dict[str, Any] | None = None + + @classmethod + def _typed_job_types(cls) -> set[str]: + """Job type values that a typed subclass declares a ``Literal`` for.""" + claimed: set[str] = set() + for sub in Job.__subclasses__(): + field = sub.model_fields.get("job_type") + if field is None: + continue + annotation = field.annotation + members = ( + get_args(annotation) + if get_origin(annotation) in (Union, UnionType) + else (annotation,) + ) + for member in members: + if get_origin(member) is Literal: + claimed.update( + arg.value if isinstance(arg, Enum) else str(arg) + for arg in get_args(member) + ) + return claimed @classmethod def create(cls, obj: "Job | Response | dict", **kwargs) -> Self: - # parse specific child Job from base Job or Response + d = ( + obj.json() + if isinstance(obj, Response) + else obj.model_dump() + if isinstance(obj, Job) + else obj + ) + payload = d | kwargs + job_classes = Job.__subclasses__() try: - # try to parse as subclass job - # get dict form - d = ( - obj.json() - if isinstance(obj, Response) - else obj.model_dump() if isinstance(obj, Job) else obj - ) - job_classes = Job.__subclasses__() - job = TypeAdapter(Union[tuple(job_classes)]).validate_python(d | kwargs) # type: ignore - except Exception as e: - job = Job.model_validate(d | kwargs) + job = TypeAdapter(Union[tuple(job_classes)]).validate_python(payload) # noqa: UP007 + except ValidationError: + # A subclass declaring this job type means the payload disagrees with + # a schema this client has, which is a bug worth surfacing. Any other + # type is one the server added, and parses as a plain job. + if payload.get("job_type") in cls._typed_job_types(): + raise + logger.info("no typed schema for job type %s", payload.get("job_type")) + job = Job.model_validate(payload) return job # type: ignore - static checker cannot know runtime type # hide extra allowed fields @@ -137,3 +183,38 @@ def __repr_args__(self): class BatchJob(BaseModel): num_records: int | None = None + + +_UNIT_STATUS_ALIASES = {"FAILED": "FAILURE", "READY": "PENDING"} + + +class _UnitRecord(BaseModel): + """A unit's position, identity, status and error, as one unit read returns them. + + The status comes from the record's ``status`` key when it has a value, else + its ``state`` key, in the vocabulary of `JobStatus`: ``FAILED`` reads as + ``FAILURE`` and a unit ready to run reads as ``PENDING``. Other keys are + ignored. + """ + + position: int + unit_id: str + status: JobStatus + error: dict[str, Any] | None = None + + @model_validator(mode="before") + @classmethod + def _read_status(cls, data: Any) -> Any: + if not isinstance(data, dict): + return data + status = data.get("status") + if status is None: + status = data.get("state") + if isinstance(status, str): + status = _UNIT_STATUS_ALIASES.get(status, status) + return { + "position": data.get("position"), + "unit_id": data.get("unit_id"), + "status": status, + "error": data.get("error"), + } diff --git a/openprotein/models/__init__.py b/openprotein/models/__init__.py index 25b2bbe..0d3dcca 100644 --- a/openprotein/models/__init__.py +++ b/openprotein/models/__init__.py @@ -1,27 +1,187 @@ """Make the ModelsAPI class available on the package.""" -# Reference other modules -from ..embeddings import ESMModel, OpenProteinModel, PoET2Model, PoETModel -from ..fold import ( - AlphaFold2Model, - Boltz1Model, - Boltz1xModel, - Boltz2Model, - ESMFold2FastModel, - ESMFold2Model, - ESMFoldModel, - MiniFoldModel, - ProtenixModel, - ProtenixV2Model, - RosettaFold3Model, +import importlib +from typing import Any + +from openprotein import _deprecation + +from .ensemble import ( + AlphaFlow, + AlphaFlowInput, + BioEmu, + BioEmuInput, + ESMFlow, + ESMFlowInput, + StructureEnsemblePredictionModel, +) +from .estimators import GP, SVD, UMAP +from .folding import ( + AlphaFold2, + Boltz1, + Boltz2, + ESMFold, + ESMFold2, + MiniFold, + OpenDDE, + Protenix, + ProtenixV2, + RosettaFold3, + StructurePredictionModel, ) -from .foundation.boltzgen import BoltzGenFuture, BoltzGenModel -from .foundation.esmif1 import ESMIF1Model -from .foundation.proteinmpnn import ProteinMPNNModel -from .foundation.rfdiffusion import RFdiffusionFuture, RFdiffusionModel -from .foundation.solublempnn import SolubleMPNNModel +from .foundational import ( + ESM1, + ESM2, + ESMC, + ESMIF1, + AbLang2, + PoET, + PoET2, + ProteinLanguageModel, + ProteinMPNN, + ProtSeq, + ProtT5, + RotaProt, +) +from .generative import BoltzGen, RFdiffusion, StructureGenerativeModel +from .gp import GPModel +from .kernels import ( + LinearKernel, + Matern12Kernel, + Matern32Kernel, + Matern52Kernel, + PeriodicKernel, + RationalQuadraticKernel, + RBFKernel, + TrainedKernel, +) +from .model import Model from .models import ModelsAPI +from .schemas import ( + MethodDescriptor, + ModelDescription, + ModelMetadata, +) from .structure_generation import ( + BoltzGenFuture, + RFdiffusionFuture, StructureGenerationFuture, StructureGenerationJob, ) +from .svd import SVDModel +from .umap import UMAPModel + +__all__ = [ + "ESM1", + "ESM2", + "ESMC", + "ESMIF1", + "GP", + "SVD", + "UMAP", + "AbLang2", + "AlphaFlow", + "AlphaFlowInput", + "AlphaFold2", + "BioEmu", + "BioEmuInput", + "Boltz1", + "Boltz2", + "BoltzGen", + "BoltzGenFuture", + "ESMFlow", + "ESMFlowInput", + "ESMFold", + "ESMFold2", + "GPModel", + "LinearKernel", + "Matern12Kernel", + "Matern32Kernel", + "Matern52Kernel", + "MethodDescriptor", + "MiniFold", + "Model", + "ModelDescription", + "ModelMetadata", + "ModelsAPI", + "OpenDDE", + "PeriodicKernel", + "PoET", + "PoET2", + "ProtSeq", + "ProtT5", + "ProteinLanguageModel", + "ProteinMPNN", + "Protenix", + "ProtenixV2", + "RBFKernel", + "RFdiffusion", + "RFdiffusionFuture", + "RationalQuadraticKernel", + "RosettaFold3", + "RotaProt", + "SVDModel", + "StructureEnsemblePredictionModel", + "StructureGenerationFuture", + "StructureGenerationJob", + "StructureGenerativeModel", + "StructurePredictionModel", + "TrainedKernel", + "UMAPModel", +] + +_RENAMED = { + "BoltzGenModel": "BoltzGen", + "ESMIF1Model": "ESMIF1", + "ProteinMPNNModel": "ProteinMPNN", + "RFdiffusionModel": "RFdiffusion", +} +_MOVED = { + **dict.fromkeys( + ( + "AlphaFold2Model", + "Boltz1Model", + "Boltz1xModel", + "Boltz2Model", + "ESMFold2FastModel", + "ESMFold2Model", + "ESMFoldModel", + "MiniFoldModel", + "ProtenixModel", + "ProtenixV2Model", + "RosettaFold3Model", + ), + "openprotein.fold", + ), + **dict.fromkeys( + ("ESMModel", "OpenProteinModel", "PoET2Model", "PoETModel"), + "openprotein.embeddings", + ), +} + + +def __getattr__(name: str) -> Any: + if name == "SolubleMPNNModel": + _deprecation.warn_deprecated( + "openprotein.models.SolubleMPNNModel", + "`session.models.solublempnn`", + since="0.18.0", + removed_in="0.19.0", + ) + from .foundational.proteinmpnn import _SolubleMPNN + + return _SolubleMPNN + if name in _RENAMED: + new = _RENAMED[name] + module = "openprotein.models" + elif name in _MOVED: + new = name + module = _MOVED[name] + else: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + _deprecation.warn_deprecated( + f"openprotein.models.{name}", + f"`{module}.{new}`", + since="0.18.0", + removed_in="0.19.0", + ) + return getattr(importlib.import_module(module), new) diff --git a/openprotein/models/_api.py b/openprotein/models/_api.py new file mode 100644 index 0000000..93c5ab5 --- /dev/null +++ b/openprotein/models/_api.py @@ -0,0 +1,131 @@ +"""Wire calls for the models API.""" + +from typing import Any +from uuid import uuid4 + +from pydantic import TypeAdapter + +from openprotein.base import _IDEMPOTENCY_KEY_HEADER, APISession +from openprotein.data._reads import read +from openprotein.jobs import Job +from openprotein.jobs._submission import post_with_retry + +from .schemas import ModelMetadata + +PATH_PREFIX = "v1/models" +JOBS_PATH_PREFIX = "v1/jobs" +_LIST_PAGE = 1000 + + +def list_models( + session: APISession, + verbose: bool = False, + *, + path: list[str] | None = None, +) -> list[str] | list[ModelMetadata]: + """List system model ids, or full metadata with ``verbose``, narrowed by capability. + + A ``path`` value matches any method path containing it, case-insensitively. + """ + params: dict[str, Any] = {"scope": "system", "limit": _LIST_PAGE} + if verbose: + params["verbose"] = "true" + if path: + params["path"] = path + result: list[Any] = [] + while True: + page = session.get(PATH_PREFIX, params={**params, "offset": len(result)}).json() + result += page + if len(page) < _LIST_PAGE: + break + if verbose: + return TypeAdapter(list[ModelMetadata]).validate_python(result) + return result + + +def get_model(session: APISession, model_id: str) -> ModelMetadata: + response = session.get(f"{PATH_PREFIX}/{model_id}", timeout=session.timeout) + return ModelMetadata.model_validate(response.json()) + + +def get_method_params(session: APISession, model_id: str, path: str) -> dict[str, Any]: + """Return a method's request params as a JSON Schema.""" + response = session.get(f"{PATH_PREFIX}/{model_id}/{path}/params") + return response.json() + + +def run_method( + session: APISession, + model_id: str, + path: str, + params: dict[str, Any], +) -> Job: + """Submit one method call, returning the job. + + The body is the params the method's schema describes. + """ + response = post_with_retry( + session, + f"{PATH_PREFIX}/{model_id}/{path}", + json=params, + headers={_IDEMPOTENCY_KEY_HEADER: str(uuid4())}, + ) + return Job.create(response.json()) + + +def bare_id(family: str, model_id: str) -> str: + """The fitted model's id without its ``family/`` prefix.""" + return model_id.removeprefix(f"{family}/") + + +def fitted_path(family: str, model_id: str | None = None) -> str: + """The family's route, or one fitted model's, from its bare or prefixed id.""" + route = f"{PATH_PREFIX}/{family}" + return route if model_id is None else f"{route}/{bare_id(family, model_id)}" + + +def create_fit( + session: APISession, family: str, request: dict[str, Any] +) -> dict[str, Any]: + """Submit a fit; returns the fit job, or a body naming only its ``id``.""" + response = post_with_retry( + session, + fitted_path(family), + json=request, + headers={_IDEMPOTENCY_KEY_HEADER: str(uuid4())}, + ) + return response.json() + + +def list_fitted( + session: APISession, + family: str, + limit: int | None = None, + offset: int | None = None, +) -> list[dict[str, Any]]: + """The caller's fitted models of ``family`` as served, newest first. + + Every page is read, up to ``limit`` models, starting at ``offset``. + """ + params: dict[str, Any] = {"scope": "mine", "type": family, "verbose": "true"} + start = offset or 0 + cards: list[dict[str, Any]] = [] + while limit is None or len(cards) < limit: + size = _LIST_PAGE if limit is None else min(_LIST_PAGE, limit - len(cards)) + page = session.get( + PATH_PREFIX, + params={**params, "limit": size, "offset": start + len(cards)}, + ).json() + cards += page + if len(page) < size: + break + return cards + + +def get_fitted(session: APISession, family: str, model_id: str) -> dict[str, Any]: + """The fitted model's card as served; raises a 404 unless its fit succeeded.""" + return read(session, fitted_path(family, model_id)).json() + + +def delete_fitted(session: APISession, family: str, model_id: str) -> None: + session.delete(fitted_path(family, model_id)) diff --git a/openprotein/models/_folds.py b/openprotein/models/_folds.py new file mode 100644 index 0000000..2f6c3c3 --- /dev/null +++ b/openprotein/models/_folds.py @@ -0,0 +1,55 @@ +"""Checks on the custom folds of a cross-validation.""" + +import numbers +from collections.abc import Sequence + +from openprotein.errors import InvalidParameterError + +MIN_NUM_FOLDS = 2 +MAX_NUM_FOLDS = 10 +EXCLUDED_FOLD = -1 + + +def validate_folds(folds: Sequence[int], num_assay_rows: int) -> list[int]: + """``folds`` as ints, after the checks the API applies to them.""" + out: list[int] = [] + for i, f in enumerate(folds): + if isinstance(f, bool) or not isinstance(f, numbers.Integral): + raise InvalidParameterError( + f"folds must all be integers, got {f!r} at row {i}" + ) + out.append(int(f)) + if len(out) != num_assay_rows: + raise InvalidParameterError( + f"expected one fold per row of the training assay ({num_assay_rows}), " + f"got {len(out)}" + ) + counts: dict[int, int] = {} + for i, f in enumerate(out): + if f < EXCLUDED_FOLD: + raise InvalidParameterError( + f"fold must be {EXCLUDED_FOLD} to exclude a row or >= 0, " + f"got {f} at row {i}" + ) + if f != EXCLUDED_FOLD: + counts[f] = counts.get(f, 0) + 1 + k = len(counts) + if not MIN_NUM_FOLDS <= k <= MAX_NUM_FOLDS: + raise InvalidParameterError( + f"expected between {MIN_NUM_FOLDS} and {MAX_NUM_FOLDS} folds, got {k}" + ) + missing = [f for f in range(k) if f not in counts] + if missing: + raise InvalidParameterError( + f"folds must be labelled 0..{k - 1} with none empty, but no row is in " + f"fold {missing[0]}" + ) + return out + + +def check_exclusive(n_splits: int | None, folds: Sequence[int] | None) -> None: + if n_splits is not None and folds is not None: + raise InvalidParameterError( + "n_splits and folds are mutually exclusive; folds already defines the " + "number of folds" + ) diff --git a/openprotein/models/_inputs.py b/openprotein/models/_inputs.py new file mode 100644 index 0000000..bc9e5ca --- /dev/null +++ b/openprotein/models/_inputs.py @@ -0,0 +1,247 @@ +"""SDK objects a verb takes, converted to the values its card's params name.""" + +from collections.abc import Callable +from typing import Any + +from openprotein.base import APISession +from openprotein.data.assaydataset import AssayDataset +from openprotein.data.schemas import AssayMetadata +from openprotein.jobs.futures import Future +from openprotein.molecules import Complex, Protein +from openprotein.prompt import Prompt, PromptAPI, Query +from openprotein.prompt.api import _assert_protein_only, _coerce_sequence +from openprotein.utils.uuid import _as_id + +from .structure_generation import StructureGenerationFuture + +QueryInput = str | bytes | Protein | Complex | Query +DesignInput = Future + + +def _type_name(value: Any) -> str: + return type(value).__name__ + + +def _check_prompt(prompt: Any, name: str = "prompt") -> None: + from openprotein.data.prompts.prompts import Prompt as StoredPrompt + + if not isinstance(prompt, (str, Prompt, StoredPrompt)): + raise TypeError( + f"{name} must be a Prompt or a prompt id, not {_type_name(prompt)}" + ) + + +def _check_query(query: Any, name: str = "query") -> None: + if isinstance(query, list) and not query: + raise ValueError(f"{name} has no entries; pass {name}=None to omit it") + for entry in query if isinstance(query, list) else [query]: + if not isinstance(entry, QueryInput): + raise TypeError( + f"{name} must be a str, bytes, Protein, Complex, Query or a list of " + f"these, not {_type_name(entry)}" + ) + _check_query_entries(query if isinstance(query, list) else [query], []) + + +def prompt_id(prompt: Any) -> str | None: + """A prompt's id, from the prompt or the id itself.""" + if prompt is None: + return None + _check_prompt(prompt) + return prompt if isinstance(prompt, str) else prompt.id + + +def query_id( + session: APISession, query: Any, force_structure: bool = False +) -> str | list[str] | None: + """The query's id, creating a query from a sequence, protein or complex. + + A list gives one id per entry. + """ + if query is None: + return None + _check_query(query) + return PromptAPI(session)._resolve_query( + query=query, force_structure=force_structure + ) + + +def _check_design(design: Any, name: str = "design") -> None: + from openprotein.jobs import _dispatch + + if isinstance(design, str) and _as_id(design) is not None: + return + if isinstance(design, StructureGenerationFuture): + return + if ( + isinstance(design, DesignInput) + and design.job is not None + and _dispatch.serves_outputs(design.job) + ): + _, path = _dispatch.identity(design.job) + if path and path.strip("/") != "generate/structures": + raise TypeError( + f"{name} job {design.id} is {path.strip('/')}, not generate/structures" + ) + return + raise TypeError( + f"{name} must be a StructureDesignFuture, a generate/structures " + f"Future, a StructureGenerationFuture or a design job's id, not " + f"{_type_name(design)}" + ) + + +def design_id(design: Any) -> str | None: + """A design job's id, from the job or the id itself.""" + if design is None: + return None + _check_design(design) + return _as_id(design) if isinstance(design, str) else design.id + + +def check_one_structure_source(params: dict[str, Any], query: Any, design: Any) -> None: + """Refuse a query and a design together, before anything is uploaded.""" + has_query = query is not None or params.get("query_id") is not None + has_design = design is not None or params.get("design_id") is not None + if has_query and has_design: + raise TypeError("pass query or design, not both") + + +def _check_query_entries(queries: list[Any], complexes: list[Complex]) -> None: + """Run the checks query creation runs, on every entry, before any is uploaded.""" + for entry in [*queries, *complexes]: + if isinstance(entry, (str, bytes)) and _as_id(entry) is None: + entry = _coerce_sequence("query", entry) + if isinstance(entry, Complex): + _assert_protein_only(entry) + + +def query_ids( + session: APISession, + query: Any = None, + force_structure: bool = False, + many: bool = False, +) -> str | list[str] | None: + """``query_id`` from a query or a list of them. + + One id is sent bare, several as a list. Unless ``many``, more than one is + refused before any query is created. A list that holds nothing is refused. + """ + if query is not None: + _check_query(query) + count = len(query) if isinstance(query, list) else int(query is not None) + if count > 1 and not many: + raise ValueError(f"this method takes one query, not {count}") + resolved = query_id(session, query, force_structure=force_structure) + if resolved is None: + return None + if isinstance(resolved, list): + return resolved[0] if len(resolved) == 1 else resolved + return resolved + + +def takes_list(schema: dict[str, Any], name: str) -> bool: + """Whether the params ``schema`` lets ``name`` be a list. + + A param the schema doesn't declare is left for the models API to refuse. + """ + properties = schema.get("properties", {}) + if name not in properties: + return True + param = properties[name] + return any(arm.get("type") == "array" for arm in param.get("anyOf", [param])) + + +def _check_assay(assay: Any, name: str = "assay") -> None: + if not isinstance(assay, (str, AssayMetadata, AssayDataset)): + raise TypeError( + f"{name} must be an assay dataset, its metadata or its id, " + f"not {_type_name(assay)}" + ) + + +#: Each SDK object a verb takes: its type check, and the param it converts to. +_INPUTS: dict[str, tuple[Callable[[Any, str], None], str | None]] = { + "prompt": (_check_prompt, "prompt_id"), + "query": (_check_query, "query_id"), + "design": (_check_design, "design_id"), + "assay": (_check_assay, None), +} + + +def check_inputs(params: dict[str, Any], **objects: Any) -> None: + """Refuse a wrong SDK-object type, or an object passed with its param. + + Verbs call this before converting anything, so nothing is uploaded or + submitted for a call that fails. + """ + for name, value in objects.items(): + if value is None: + continue + check, param = _INPUTS[name] + check(value, name) + if param is not None and params.get(param) is not None: + raise TypeError(f"pass {name} or {param}, not both") + + +def check_fit_source(sequences: Any, assay: Any) -> None: + """Refuse a fit given neither or both of ``sequences`` and ``assay``.""" + if (sequences is None) == (assay is None): + raise ValueError("pass one of sequences or assay") + + +def assay_id(assay: Any) -> str: + """An assay's id, given the assay or its id.""" + _check_assay(assay) + if isinstance(assay, AssayMetadata): + return assay.assay_id + if isinstance(assay, AssayDataset): + return assay.id + return assay + + +def model_id(model: Any) -> str: + """The models API id of a model id or a ``get_model`` handle, fitted SVDs included.""" + from .model import Model + + if isinstance(model, str): + return model + if isinstance(model, Model): + return model.id + raise TypeError( + "model must be a model id, a model from get_model or a fitted svd, " + f"not {_type_name(model)}" + ) + + +def as_dataset(session: APISession, assay: Any) -> AssayDataset: + """The assay dataset, given the dataset, its metadata or its id.""" + _check_assay(assay) + if isinstance(assay, str): + return AssayDataset._for(session)(id=assay) + if isinstance(assay, AssayMetadata): + return AssayDataset._for(session)(session, assay) + return assay + + +def assay_sequences(session: APISession, assay: Any) -> list[str]: + """The sequences of an assay, given the assay or its id. + + A page that fails to load raises. + """ + dataset = as_dataset(session, assay) + sequences: list[str] = [] + while True: + page = dataset.get_slice(len(sequences), len(sequences) + dataset.page_size) + sequences += [str(sequence) for sequence in page["sequence"]] + if len(page) < dataset.page_size: + return sequences + + +def with_param(params: dict[str, Any], name: str, value: Any, given_as: str) -> None: + """Set ``params[name]`` from a converted SDK object, refusing both forms.""" + if value is None: + return + if params.get(name) is not None: + raise TypeError(f"pass {given_as} or {name}, not both") + params[name] = value diff --git a/openprotein/models/base.py b/openprotein/models/base.py deleted file mode 100644 index 15b0911..0000000 --- a/openprotein/models/base.py +++ /dev/null @@ -1,63 +0,0 @@ -"""Base protein models for working with proteins.""" - -from openprotein.base import APISession -from openprotein.common import ModelMetadata -from openprotein.jobs import Future - - -class ProteinModel: - def __init__( - self, - session: APISession, - model_id: str, - metadata: ModelMetadata | None = None, - ): - self.session = session - self.id = model_id - self._metadata = metadata - self.__doc__ = self.__fmt_doc() - - def __fmt_doc(self): - summary = str(self.metadata.description.summary) - return f"""\t{summary} - \t max_sequence_length = {self.metadata.max_sequence_length} - \t supported outputs = {self.metadata.output_types} - \t supported tokens = {self.metadata.input_tokens} - """ - - def __str__(self) -> str: - return self.id - - def __repr__(self) -> str: - return self.id - - @property - def metadata(self): - """ - ModelMetadata for this model. - - Returns - ------- - ModelMetadata - The metadata associated with this model. - """ - if self._metadata is None: - self._metadata = self.get_metadata() - return self._metadata - - def get_metadata(self) -> ModelMetadata: - """ - Get model metadata for this model. - - Returns - ------- - ModelMetadata - The metadata associated with this model. - """ - raise NotImplementedError("`get_metadata` not implemented for this model") - - def predict(self, *args, **kwargs) -> Future: - """ - Alias for the `design` method to conform to the base ProteinModel. - """ - raise NotImplementedError("`predict` not implemented for this model") diff --git a/openprotein/models/ensemble/__init__.py b/openprotein/models/ensemble/__init__.py new file mode 100644 index 0000000..92bca34 --- /dev/null +++ b/openprotein/models/ensemble/__init__.py @@ -0,0 +1,16 @@ +"""Structure ensemble models.""" + +from .alphaflow import AlphaFlow, AlphaFlowInput +from .base import StructureEnsemblePredictionModel +from .bioemu import BioEmu, BioEmuInput +from .esmflow import ESMFlow, ESMFlowInput + +__all__ = [ + "AlphaFlow", + "AlphaFlowInput", + "BioEmu", + "BioEmuInput", + "ESMFlow", + "ESMFlowInput", + "StructureEnsemblePredictionModel", +] diff --git a/openprotein/models/ensemble/_inputs.py b/openprotein/models/ensemble/_inputs.py new file mode 100644 index 0000000..e22c2a9 --- /dev/null +++ b/openprotein/models/ensemble/_inputs.py @@ -0,0 +1,163 @@ +"""Ensemble inputs converted to request fields.""" + +from collections.abc import Sequence +from typing import Any, TypeVar + +from openprotein.fold.common import _msa_id_of +from openprotein.molecules import Complex, Protein, Structure + +_T = TypeVar("_T") + + +def input_list(inputs: Any, input_type: type[_T]) -> list[_T]: + if isinstance(inputs, (str, bytes)) or not isinstance(inputs, Sequence): + raise TypeError(f"inputs must be a list of {input_type.__name__}") + if not inputs: + raise ValueError("inputs must contain at least one input") + for index, value in enumerate(inputs): + if not isinstance(value, input_type): + raise TypeError( + f"inputs[{index}] must be a {input_type.__name__}, " + f"not {type(value).__name__}" + ) + return list(inputs) + + +def sequence_text(value: Any, field: str) -> str: + if isinstance(value, Protein): + value = value.sequence + if isinstance(value, bytes): + value = value.decode() + if not isinstance(value, str): + raise TypeError( + f"{field} must be a Protein or sequence text, not {type(value).__name__}" + ) + if not value: + raise ValueError(f"{field} is empty") + if ":" in value: + raise ValueError(f"{field} holds several chains; pass one protein chain") + return value + + +def msa_id(value: Any, field: str, *, required: bool) -> str | None: + resolved = None if value is None else _msa_id_of(value) + if required and resolved is None: + raise ValueError( + f"{field} is required; pass an MSA whose query is the sequence" + ) + return resolved + + +def protein_complex(sequence: str, msa: str | None, *, takes_msa: bool) -> list: + protein: dict[str, Any] = {"id": "A", "sequence": sequence} + if takes_msa: + protein["msa_id"] = msa + return [{"protein": protein}] + + +def _text(value: str | bytes, field: str) -> str: + text = value.decode() if isinstance(value, bytes) else value + if not text.strip(): + raise ValueError(f"{field} is empty") + return text + + +def _parse_pdb(value: str | bytes, field: str) -> Structure: + text = _text(value, field) + if any( + line.lstrip().startswith(("data_", "_atom_site.")) for line in text.splitlines() + ): + raise ValueError( + f"{field} requires PDB text; parse mmCIF into a Protein, " + "Complex or Structure before passing it" + ) + try: + return Structure.from_string(text, format="pdb", verbose=False) + except ValueError as error: + raise ValueError( + f"{field} must contain a supported protein structure: {error}" + ) from error + + +def _reference_complex(value: Any, field: str, *, single_chain: bool) -> Complex: + if isinstance(value, Structure): + if not len(value): + raise ValueError(f"{field} contains no structure") + value = value[0] + if isinstance(value, Protein): + value = Complex({"A": value}) + if not isinstance(value, Complex): + raise TypeError( + f"{field} must be structure text, Protein, Complex or Structure" + ) + + proteins = value.get_proteins() + if not proteins: + raise ValueError(f"{field} contains no protein chain") + nonprotein = [ + chain_id + for chain_id, chain in value.get_chains().items() + if not isinstance(chain, Protein) + ] + if nonprotein: + raise ValueError( + f"{field} contains non-protein chains: {', '.join(nonprotein)}" + ) + if single_chain and len(proteins) != 1: + raise ValueError(f"{field} requires exactly one protein chain") + for chain_id, protein in proteins.items(): + if protein.get_structure_mask().all(): + raise ValueError(f"{field} chain {chain_id!r} has no coordinates") + return value + + +def _check_matches(reference: str, sequence: str, field: str) -> None: + if len(reference) != len(sequence): + raise ValueError( + f"{field} has {len(reference)} residues and the sequence has " + f"{len(sequence)}; they must be the same protein, residue for residue" + ) + for position, (ours, theirs) in enumerate(zip(reference, sequence), start=1): + if ours != theirs and "X" not in (ours, theirs): + raise ValueError( + f"{field} differs from the sequence at position {position}: " + f"{ours} in the reference, {theirs} in the sequence" + ) + + +def flow_reference(value: Any, sequence: str, field: str) -> str: + """``value`` as PDB text of one fully modelled chain matching ``sequence``.""" + if isinstance(value, (str, bytes)): + value = _parse_pdb(value, field) + complex = _reference_complex(value, field, single_chain=True) + (protein,) = complex.get_proteins().values() + if protein.get_structure_mask().any(): + raise ValueError( + f"{field} contains unmodelled residues; trim them from both " + "the reference and the sequence, for example " + "protein[~protein.get_structure_mask()]" + ) + _check_matches(protein.sequence.decode(), sequence, field) + return complex.to_string(format="pdb") + + +def flow_references( + references: list[Any], sequences: list[str] +) -> list[dict[str, str]] | None: + """One reference record per input, or None when no input has a reference.""" + given = [reference is not None for reference in references] + if not any(given): + return None + if not all(given): + raise ValueError( + "give every input a reference_structure, or none of them; " + f"inputs[{given.index(False)}] has none" + ) + return [ + { + "structure_file": flow_reference( + reference, sequence, f"inputs[{index}].reference_structure" + ) + } + for index, (reference, sequence) in enumerate(zip(references, sequences)) + ] diff --git a/openprotein/models/ensemble/alphaflow.py b/openprotein/models/ensemble/alphaflow.py new file mode 100644 index 0000000..fe017c5 --- /dev/null +++ b/openprotein/models/ensemble/alphaflow.py @@ -0,0 +1,148 @@ +"""AlphaFlow.""" + +from collections.abc import Sequence +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any + +from openprotein.jobs import futures + +from . import _inputs +from .base import StructureEnsemblePredictionModel + +if TYPE_CHECKING: + from openprotein.align import MSAFuture + from openprotein.data.msa import MSA + from openprotein.molecules import Complex, Protein, Structure + +__all__ = ["AlphaFlow", "AlphaFlowInput"] + + +@dataclass(frozen=True) +class AlphaFlowInput: + """One AlphaFlow ensemble: a protein chain, its MSA and an optional reference. + + Attributes + ---------- + sequence : Protein, str or bytes + The protein chain to sample. + msa : str, MSAFuture or MSA + An MSA whose query is ``sequence``. + reference_structure : str, bytes, Protein, Complex, Structure or None + A structure to sample around, as PDB text or a molecule holding one + protein chain. Its residues must all be modelled and match + ``sequence``. + """ + + sequence: "Protein | str | bytes" + msa: "str | MSAFuture | MSA" + reference_structure: "str | bytes | Protein | Complex | Structure | None" = None + + +class AlphaFlow(StructureEnsemblePredictionModel): + """AlphaFlow samples protein ensembles from a sequence and its MSA. + + A call currently takes one MSA, shared by every input, so a call samples + one protein. A reference structure, given for every input or none, draws + each ensemble around it. Its checkpoints are ``alphaflow-md-base-v1``, the + default, and ``alphaflow-md-distilled-v1``, which samples each conformation + in one step. + """ + + Input = AlphaFlowInput + _default_id = "alphaflow-md-base-v1" + + def sample( + self, + inputs: Sequence[AlphaFlowInput], + num_samples: int = 1, + num_steps: int = 10, + tmax: float = 1.0, + msa_subsample: int | None = None, + self_cond: bool | None = None, + resample: bool | None = None, + random_seed: int | None = None, + ) -> futures.StructurePredictionFuture: + """Sample one ensemble per input. + + Parameters + ---------- + inputs : sequence of AlphaFlowInput + One entry per ensemble. + num_samples : int + Conformations to sample per input. + num_steps : int + Integration steps per conformation. A distilled checkpoint samples + each conformation in one step and ignores it. + tmax : float + Noise level the flow starts from, in (0, 1]. A distilled + checkpoint ignores it. + msa_subsample : int or None + Cap on the MSA depth the model reads. ``None`` keeps the + checkpoint's setting. + self_cond : bool or None + Feed each step's prediction back in as the next step's input. + ``None`` keeps the checkpoint's setting. + resample : bool or None + Redraw the MSA clusters for each conformation. ``None`` keeps the + checkpoint's setting. + random_seed : int or None + Random seed. ``None`` lets the model pick its own, so every call + is a fresh sample. + + Returns + ------- + StructurePredictionFuture + One ensemble per input, in input order. ``plddt`` and + ``confidence`` outputs are read with ``get(output=...)``. + + Examples + -------- + >>> alphaflow = session.models.alphaflow + >>> future = alphaflow.sample( + ... [ + ... alphaflow.Input( + ... sequence=sequence, msa=msa, reference_structure=reference + ... ) + ... ], + ... num_samples=10, + ... num_steps=10, + ... ) + >>> ensembles = future.get() + >>> plddt = future.get(output="plddt") + + The distilled checkpoint samples each conformation in one step: + + >>> distilled = session.models.alphaflow_md_distilled_v1 + >>> future = distilled.sample( + ... [distilled.Input(sequence=sequence, msa=msa)], num_samples=10 + ... ) + """ + entries = _inputs.input_list(inputs, AlphaFlowInput) + sequences = [ + _inputs.sequence_text(entry.sequence, f"inputs[{i}].sequence") + for i, entry in enumerate(entries) + ] + complexes = [ + _inputs.protein_complex( + sequence, + _inputs.msa_id(entry.msa, f"inputs[{i}].msa", required=True), + takes_msa=True, + ) + for i, (entry, sequence) in enumerate(zip(entries, sequences)) + ] + references = _inputs.flow_references( + [entry.reference_structure for entry in entries], sequences + ) + params: dict[str, Any] = {"complexes": complexes} + if references is not None: + params["reference_structures"] = references + return self._sample( + **params, + num_samples=num_samples, + num_steps=num_steps, + tmax=tmax, + msa_subsample=msa_subsample, + self_cond=self_cond, + resample=resample, + random_seed=random_seed, + ) diff --git a/openprotein/models/ensemble/base.py b/openprotein/models/ensemble/base.py new file mode 100644 index 0000000..7138862 --- /dev/null +++ b/openprotein/models/ensemble/base.py @@ -0,0 +1,25 @@ +"""The base handle of the structure-ensemble models.""" + +from typing import Any, cast + +from openprotein.jobs import futures + +from ..model import Model + +__all__ = ["StructureEnsemblePredictionModel"] + + +class StructureEnsemblePredictionModel(Model): + """A model that samples conformational ensembles. + + Each model's ``sample`` takes its own input type, available on the handle + as ``Input``, one input per ensemble. It returns a + ``StructurePredictionFuture`` whose ``get()`` gives one ``Structure`` per + input, holding its sampled conformations. + """ + + def _sample(self, **params: Any) -> futures.StructurePredictionFuture: + return cast( + futures.StructurePredictionFuture, + self._run("sample", "batch/structures", **params), + ) diff --git a/openprotein/models/ensemble/bioemu.py b/openprotein/models/ensemble/bioemu.py new file mode 100644 index 0000000..299a7d5 --- /dev/null +++ b/openprotein/models/ensemble/bioemu.py @@ -0,0 +1,109 @@ +"""BioEmu.""" + +from collections.abc import Sequence +from dataclasses import dataclass +from typing import TYPE_CHECKING, Literal + +from openprotein.jobs import futures + +from . import _inputs +from .base import StructureEnsemblePredictionModel + +if TYPE_CHECKING: + from openprotein.align import MSAFuture + from openprotein.data.msa import MSA + from openprotein.molecules import Protein + +__all__ = ["BioEmu", "BioEmuInput"] + + +@dataclass(frozen=True) +class BioEmuInput: + """One BioEmu ensemble: a protein chain and, optionally, its MSA. + + Attributes + ---------- + sequence : Protein, str or bytes + The protein chain to sample. + msa : str, MSAFuture, MSA or None + An MSA whose query is ``sequence``. ``None`` or + ``Protein.single_sequence_mode`` samples from the sequence alone. + """ + + sequence: "Protein | str | bytes" + msa: "str | MSAFuture | MSA | type[Protein.NullMSA] | None" + + +class BioEmu(StructureEnsemblePredictionModel): + """BioEmu samples protein ensembles from a sequence and, optionally, its MSA. + + A call currently takes one MSA or none, shared by every input, so a call + with an MSA samples one protein. Its checkpoint is ``bioemu-v1-1``. + """ + + Input = BioEmuInput + _default_id = "bioemu-v1-1" + + def sample( + self, + inputs: Sequence[BioEmuInput], + num_samples: int = 1, + denoiser: Literal["dpm", "heun", "physical"] = "dpm", + filter_samples: bool = True, + random_seed: int | None = None, + ) -> futures.StructurePredictionFuture: + """Sample one ensemble per input. + + Parameters + ---------- + inputs : sequence of BioEmuInput + One entry per ensemble. + num_samples : int + Conformations to sample per input. + denoiser : {"dpm", "heun", "physical"} + Sampler for the reverse diffusion. + filter_samples : bool + Drop samples that fail BioEmu's physicality checks, so an ensemble + can hold fewer than ``num_samples`` conformations. + random_seed : int or None + Random seed. ``None`` lets the model pick its own, so every call + is a fresh sample. + + Returns + ------- + StructurePredictionFuture + One ensemble per input, in input order. + + Examples + -------- + One protein with its MSA: + + >>> bioemu = session.models.bioemu + >>> future = bioemu.sample( + ... [bioemu.Input(sequence=sequence, msa=msa)], + ... num_samples=10, + ... ) + >>> ensembles = future.get() + + Several proteins without an MSA: + + >>> future = bioemu.sample( + ... [bioemu.Input(sequence=s, msa=None) for s in sequences], + ... num_samples=10, + ... ) + """ + complexes = [ + _inputs.protein_complex( + _inputs.sequence_text(entry.sequence, f"inputs[{i}].sequence"), + _inputs.msa_id(entry.msa, f"inputs[{i}].msa", required=False), + takes_msa=True, + ) + for i, entry in enumerate(_inputs.input_list(inputs, BioEmuInput)) + ] + return self._sample( + complexes=complexes, + num_samples=num_samples, + denoiser=denoiser, + filter_samples=filter_samples, + random_seed=random_seed, + ) diff --git a/openprotein/models/ensemble/esmflow.py b/openprotein/models/ensemble/esmflow.py new file mode 100644 index 0000000..b4965ff --- /dev/null +++ b/openprotein/models/ensemble/esmflow.py @@ -0,0 +1,122 @@ +"""ESMFlow.""" + +from collections.abc import Sequence +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any + +from openprotein.jobs import futures + +from . import _inputs +from .base import StructureEnsemblePredictionModel + +if TYPE_CHECKING: + from openprotein.molecules import Complex, Protein, Structure + +__all__ = ["ESMFlow", "ESMFlowInput"] + + +@dataclass(frozen=True) +class ESMFlowInput: + """One ESMFlow ensemble: a protein chain and an optional reference. + + Attributes + ---------- + sequence : Protein, str or bytes + The protein chain to sample. + reference_structure : str, bytes, Protein, Complex, Structure or None + A structure to sample around, as PDB text or a molecule holding one + protein chain. Its residues must all be modelled and match + ``sequence``. + """ + + sequence: "Protein | str | bytes" + reference_structure: "str | bytes | Protein | Complex | Structure | None" = None + + +class ESMFlow(StructureEnsemblePredictionModel): + """ESMFlow samples protein ensembles from a sequence alone. + + A reference structure, given for every input or none, draws each ensemble + around it. Its checkpoints are ``esmflow-md-base-v1``, the default, and + ``esmflow-md-distilled-v1``, which samples each conformation in one step. + """ + + Input = ESMFlowInput + _default_id = "esmflow-md-base-v1" + + def sample( + self, + inputs: Sequence[ESMFlowInput], + num_samples: int = 1, + num_steps: int = 10, + tmax: float = 1.0, + self_cond: bool | None = None, + random_seed: int | None = None, + ) -> futures.StructurePredictionFuture: + """Sample one ensemble per input. + + Parameters + ---------- + inputs : sequence of ESMFlowInput + One entry per ensemble. + num_samples : int + Conformations to sample per input. + num_steps : int + Integration steps per conformation. A distilled checkpoint samples + each conformation in one step and ignores it. + tmax : float + Noise level the flow starts from, in (0, 1]. A distilled + checkpoint ignores it. + self_cond : bool or None + Feed each step's prediction back in as the next step's input. + ``None`` keeps the checkpoint's setting. + random_seed : int or None + Random seed. ``None`` lets the model pick its own, so every call + is a fresh sample. + + Returns + ------- + StructurePredictionFuture + One ensemble per input, in input order. ``plddt`` and + ``confidence`` outputs are read with ``get(output=...)``. + + Examples + -------- + >>> esmflow = session.models.esmflow + >>> future = esmflow.sample( + ... [esmflow.Input(sequence=sequence, reference_structure=reference)], + ... num_samples=10, + ... ) + >>> ensembles = future.get() + + Several proteins in one call, on the distilled checkpoint: + + >>> distilled = session.models.esmflow_md_distilled_v1 + >>> future = distilled.sample( + ... [distilled.Input(sequence=s) for s in sequences], num_samples=10 + ... ) + """ + entries = _inputs.input_list(inputs, ESMFlowInput) + sequences = [ + _inputs.sequence_text(entry.sequence, f"inputs[{i}].sequence") + for i, entry in enumerate(entries) + ] + params: dict[str, Any] = { + "complexes": [ + _inputs.protein_complex(sequence, None, takes_msa=False) + for sequence in sequences + ] + } + references = _inputs.flow_references( + [entry.reference_structure for entry in entries], sequences + ) + if references is not None: + params["reference_structures"] = references + return self._sample( + **params, + num_samples=num_samples, + num_steps=num_steps, + tmax=tmax, + self_cond=self_cond, + random_seed=random_seed, + ) diff --git a/openprotein/models/estimators.py b/openprotein/models/estimators.py new file mode 100644 index 0000000..791831c --- /dev/null +++ b/openprotein/models/estimators.py @@ -0,0 +1,400 @@ +"""Estimators on ``session.models``: fit on an embeddings job or on a model's embeddings.""" + +from __future__ import annotations + +import builtins +from collections.abc import Callable +from typing import Any, ClassVar, Generic, TypeVar, cast, overload + +from typing_extensions import Self + +from openprotein.base import APISession +from openprotein.data import AssayMetadata +from openprotein.data.assaydataset import AssayDataset +from openprotein.jobs import Future +from openprotein.jobs.futures import ( + FitFuture, + GPFitFuture, + SVDFitFuture, + UMAPFitFuture, +) + +from . import _api, _inputs, gp, svd, umap +from .gp import GPModel +from .model import Model, _texts +from .svd import SVDModel +from .umap import UMAPModel + +__all__ = ["GP", "SVD", "UMAP"] + + +_F = TypeVar("_F", bound=FitFuture) +_H = TypeVar("_H") + + +def _describe(x: Any) -> str: + """How an error names ``x``.""" + if isinstance(x, AssayDataset): + return f"assay {x.id}" + if isinstance(x, Model): + return f"model {x.id}" + if isinstance(x, Future): + return f"job {x.id}" + return type(x).__name__ + + +def _job_id(X: Any) -> str: + """The id ``X`` is sent as ``embeddings_job_id``: a job's, or a fitted SVD's.""" + if isinstance(X, str): + return _api.bare_id("svd", X) + if isinstance(X, SVDModel): + return _api.bare_id("svd", X.id) + if isinstance(X, Future): + return X.id + raise TypeError( + f"{_describe(X)} isn't an embeddings job; X is a job, a fitted SVD or its " + "id. Pass a model as model= and an assay as assay=" + ) + + +def _check_source( + X: Any, model: Any, sequences: Any, assay: Any, params: dict[str, Any] +) -> None: + """Refuse a fit on both or neither of ``X`` and ``model``, or on inputs it can't take.""" + if (X is None) == (model is None): + raise TypeError("pass X, an embeddings job, or model= with sequences or assay") + if X is not None and (sequences is not None or assay is not None or params): + raise TypeError( + "X names the sequences it embedded; sequences, assay and embedding " + "params go with model=" + ) + if model is not None and (sequences is None) == (assay is None): + raise ValueError("pass one of sequences or assay with model=") + + +def _feature_model(session: APISession, model: Any, params: dict[str, Any]) -> Model: + """The handle ``model=`` names; a handle is used as is, an id is looked up.""" + if "model_id" in params: + raise TypeError("model_id is not an embedding param; pass the model as model=") + if isinstance(model, str): + from .models import ModelsAPI + + return ModelsAPI(session).get_model(model) + _inputs.model_id(model) + return model + + +def _carried(x: Any) -> AssayDataset | Future | None: + """What a fit on ``x`` takes its ``dataset`` from; a future is read when asked.""" + return x if isinstance(x, Future) else _dataset_of(x) + + +def _dataset_of(x: Any) -> AssayDataset | None: + """The assay ``x`` is, or the one its sequences came from.""" + if isinstance(x, AssayDataset): + return x + dataset = getattr(x, "dataset", None) + return dataset if isinstance(dataset, AssayDataset) else None + + +class _Estimator(Generic[_F, _H]): + """Hyperparameters to fit with. + + ``session.models`` hands out each estimator class bound to its session. + Calling it makes an estimator, and ``id=`` alone loads a fitted model. + ``fit`` returns the fit's future, whose ``wait`` returns the fitted model. + """ + + session: ClassVar[APISession] + + @classmethod + def _bind(cls, session: APISession) -> type[Self]: + """This estimator class, fitting and loading through ``session``.""" + attrs = { + "session": session, + "__module__": cls.__module__, + "__qualname__": cls.__qualname__, + "__doc__": cls.__doc__, + } + return cast("type[Self]", type(cls.__name__, (cls,), attrs)) + + @classmethod + def _bound(cls) -> APISession: + session = getattr(cls, "session", None) + if session is None: + raise TypeError( + f"{cls.__name__} needs a session; use session.models.{cls.__name__}" + ) + return session + + @classmethod + def _create( + cls, id: str | None, given: bool, load: Callable[[APISession, str], _H] + ) -> Self | _H: + """A new estimator, or with ``id`` the fitted model ``load`` reads.""" + session = cls._bound() + if id is None: + return object.__new__(cls) + if given: + raise TypeError("pass id alone to load a fitted model") + return load(session, id) + + +class SVD(_Estimator[SVDFitFuture, SVDModel]): + """An SVD to fit on a system model's embeddings.""" + + @overload + def __new__(cls, *, id: str) -> SVDModel: ... + + @overload + def __new__( + cls, n_components: int | None = None, seed: int | None = None + ) -> Self: ... + + def __new__(cls, *args: Any, id: str | None = None, **kwargs: Any) -> Any: + return cls._create(id, bool(args or kwargs), svd._load) + + def __init__(self, n_components: int | None = None, seed: int | None = None): + self.n_components = n_components + self.seed = seed + + def fit( + self, + X: Any = None, + *, + model: Any = None, + sequences: builtins.list[str] | builtins.list[bytes] | None = None, + assay: Any = None, + **params: Any, + ) -> SVDFitFuture: + """Fit on ``X``, an embeddings job or a fitted SVD, and the sequences it embedded. + + Or fit on ``model``'s embeddings of ``sequences`` or an ``assay``'s, + with ``params`` its embedding params such as ``reduction``. + """ + _check_source(X, model, sequences, assay, params) + if model is not None: + return svd._fit( + self.session, + _feature_model(self.session, model, params), + sequences=None if sequences is None else _texts(sequences), + assay=assay, + n_components=self.n_components, + seed=self.seed, + **params, + ) + request: dict[str, Any] = { + "embeddings_job_id": _job_id(X), + "output": "embeddings", + } + for key, value in (("n_components", self.n_components), ("seed", self.seed)): + if value is not None: + request[key] = value + future = svd._submit(self.session, request) + future.dataset = _carried(X) + return future + + def fit_transform(self, X: Any = None, **kwargs: Any) -> SVDFitFuture: + """``fit``; a fit that names an ``embeddings`` output holds its sequences projected.""" + return self.fit(X, **kwargs) + + @classmethod + def list( + cls, limit: int | None = None, offset: int | None = None + ) -> builtins.list[SVDModel]: + """The caller's SVDs from every page, newest first, at most ``limit``.""" + return svd._page(cls._bound(), limit, offset) + + +class UMAP(_Estimator[UMAPFitFuture, UMAPModel]): + """A UMAP to fit on pooled embeddings or an SVD's projections.""" + + @overload + def __new__(cls, *, id: str) -> UMAPModel: ... + + @overload + def __new__( + cls, + n_components: int | None = None, + n_neighbors: int | None = None, + min_dist: float | None = None, + ) -> Self: ... + + def __new__(cls, *args: Any, id: str | None = None, **kwargs: Any) -> Any: + return cls._create(id, bool(args or kwargs), umap._load) + + def __init__( + self, + n_components: int | None = None, + n_neighbors: int | None = None, + min_dist: float | None = None, + ): + self.n_components = n_components + self.n_neighbors = n_neighbors + self.min_dist = min_dist + + def fit( + self, + X: Any = None, + *, + model: Any = None, + sequences: builtins.list[str] | builtins.list[bytes] | None = None, + assay: Any = None, + **params: Any, + ) -> UMAPFitFuture: + """Fit on ``X``, an embeddings job or a fitted SVD, and the sequences it embedded. + + Or fit on ``model``'s features of ``sequences`` or an ``assay``'s, with + ``params`` its embedding params such as ``reduction``. ``model`` is a + system model or a fitted SVD. + """ + _check_source(X, model, sequences, assay, params) + if model is not None: + future = umap._fit( + self.session, + _feature_model(self.session, model, params), + sequences=None if sequences is None else _texts(sequences), + assay=assay, + n_components=self.n_components, + n_neighbors=self.n_neighbors, + min_dist=self.min_dist, + **params, + ) + return future + request: dict[str, Any] = {"embeddings_job_id": _job_id(X)} + for key, value in ( + ("n_components", self.n_components), + ("n_neighbors", self.n_neighbors), + ("min_dist", self.min_dist), + ): + if value is not None: + request[key] = value + future = umap._submit(self.session, request) + future.dataset = _carried(X) + return future + + def fit_transform(self, X: Any = None, **kwargs: Any) -> UMAPFitFuture: + """``fit``; the fit's outputs are its sequences mapped.""" + return self.fit(X, **kwargs) + + @classmethod + def list( + cls, limit: int | None = None, offset: int | None = None + ) -> builtins.list[UMAPModel]: + """The caller's UMAPs from every page, newest first, at most ``limit``.""" + return umap._page(cls._bound(), limit, offset) + + +def _training( + session: APISession, X: Any, assay: Any, property: str | None +) -> tuple[str, str]: + """The assay id and property a GP trains on; reads the assay only to pick its property.""" + if assay is None: + dataset = _dataset_of(X) + elif property is not None: + return _inputs.assay_id(assay), property + else: + dataset = _inputs.as_dataset(session, assay) + if dataset is None: + raise ValueError(f"{_describe(X)} carries no assay; pass assay to train on") + if property is not None: + return dataset.id, property + names = list(dataset.measurement_names) + if len(names) != 1: + raise ValueError( + f"assay {dataset.id} has measurements {', '.join(names)}; " + "pass property to pick one" + ) + return dataset.id, names[0] + + +class GP(_Estimator[GPFitFuture, GPModel]): + """A Gaussian process to train on one assay property.""" + + @overload + def __new__(cls, *, id: str) -> GPModel: ... + + @overload + def __new__( + cls, + kernel: str = "rbf", + period: float | None = None, + alpha: float | None = None, + name: str | None = None, + description: str | None = None, + ) -> Self: ... + + def __new__(cls, *args: Any, id: str | None = None, **kwargs: Any) -> Any: + return cls._create(id, bool(args or kwargs), gp._load) + + def __init__( + self, + kernel: str = "rbf", + period: float | None = None, + alpha: float | None = None, + name: str | None = None, + description: str | None = None, + ): + self.kernel = kernel + self.period = period + self.alpha = alpha + self.name = name + self.description = description + + def fit( + self, + X: Any = None, + *, + model: Any = None, + assay: Any = None, + property: str | None = None, + **params: Any, + ) -> GPFitFuture: + """Train on one assay ``property``. + + The features are ``X``, an embeddings job or a fitted SVD, on the assay + ``X`` embedded unless ``assay`` is given. Or ``model``'s features of + ``assay``, with ``params`` its embedding params such as ``reduction``. + Or, with ``assay`` alone, one-hot features. ``property`` may be omitted + when the assay has one measurement. + """ + if X is not None and model is not None: + raise TypeError("pass X or model=, not both") + if params and model is None: + raise TypeError("embedding params go with model=") + if X is None and assay is None: + raise ValueError("pass X, or assay to train on") + feature_model = ( + None if model is None else _feature_model(self.session, model, params) + ) + trained_on, trained = _training(self.session, X, assay, property) + kernel: dict[str, Any] = {"type": self.kernel} + for key, value in (("period", self.period), ("alpha", self.alpha)): + if value is not None: + kernel[key] = value + request: dict[str, Any] = { + "kernel": kernel, + "training_dataset": {"assay_id": trained_on, "properties": [trained]}, + } + if X is not None: + request["embeddings_job_id"] = _job_id(X) + elif feature_model is not None: + request["features"] = {"model_id": feature_model.id, **params} + else: + request["features"] = {} + for key, value in (("name", self.name), ("description", self.description)): + if value is not None: + request[key] = value + future = gp._submit(self.session, request) + if assay is None: + future.dataset = _carried(X) + elif isinstance(assay, (AssayDataset, AssayMetadata)): + future.dataset = _inputs.as_dataset(self.session, assay) + return future + + @classmethod + def list( + cls, limit: int | None = None, offset: int | None = None + ) -> builtins.list[GPModel]: + """The caller's GPs from every page, newest first, at most ``limit``.""" + return gp._page(cls._bound(), limit, offset) diff --git a/openprotein/models/folding/__init__.py b/openprotein/models/folding/__init__.py new file mode 100644 index 0000000..962ce7a --- /dev/null +++ b/openprotein/models/folding/__init__.py @@ -0,0 +1,27 @@ +"""Structure prediction models.""" + +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 + +__all__ = [ + "AlphaFold2", + "Boltz1", + "Boltz2", + "ESMFold", + "ESMFold2", + "MiniFold", + "OpenDDE", + "Protenix", + "ProtenixV2", + "RosettaFold3", + "StructurePredictionModel", +] diff --git a/openprotein/models/folding/alphafold2.py b/openprotein/models/folding/alphafold2.py new file mode 100644 index 0000000..a234910 --- /dev/null +++ b/openprotein/models/folding/alphafold2.py @@ -0,0 +1,14 @@ +"""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/base.py b/openprotein/models/folding/base.py new file mode 100644 index 0000000..1dfe5d4 --- /dev/null +++ b/openprotein/models/folding/base.py @@ -0,0 +1,188 @@ +"""Structure-prediction handle, shaped by the model's card and params.""" + +import copy +import warnings +from collections.abc import Sequence +from typing import Any + +from openprotein.align import MSAFuture +from openprotein.fold.common import ( + _msa_id_of, + msa_future_to_complex, + normalize_inputs, + normalize_templates, + resolve_templates, + serialize_input, +) +from openprotein.jobs import futures +from openprotein.molecules import DNA, RNA, Complex, Ligand, Protein + +from ..model import Model + +__all__ = ["StructurePredictionModel"] + + +_CHAIN_TYPES: dict[str, type] = { + "protein": Protein, + "dna": DNA, + "rna": RNA, + "ligand": Ligand, +} + + +def _is_serialized(complexes: Any) -> bool: + return ( + isinstance(complexes, (list, tuple)) + and len(complexes) > 0 + and all(isinstance(c, (list, tuple)) for c in complexes) + ) + + +def _without(complex: Complex, drops: tuple[type, ...], model_id: str) -> Complex: + kept = {k: c for k, c in complex.get_chains().items() if not isinstance(c, drops)} + if len(kept) == len(complex.get_chains()): + return complex + warnings.warn( + f"{model_id} does not support " + f"{'/'.join(t.__name__ for t in drops)} input; those chains are left out." + ) + trimmed = copy.copy(complex) + trimmed._chains = kept + return trimmed + + +def _declares(schema: Any, name: str) -> bool: + """Whether any object in ``schema`` declares the property ``name``.""" + if isinstance(schema, dict): + properties = schema.get("properties") + if isinstance(properties, dict) and name in properties: + return True + return any(_declares(value, name) for value in schema.values()) + if isinstance(schema, list): + return any(_declares(value, name) for value in schema) + return False + + +def _needs_msa(schema: Any) -> bool: + """Whether a protein in ``schema`` requires a non-null ``msa_id``.""" + if isinstance(schema, dict): + properties = schema.get("properties") + msa_id = properties.get("msa_id") if isinstance(properties, dict) else None + if isinstance(msa_id, dict) and "msa_id" in schema.get("required", []): + arms = msa_id.get("anyOf", [msa_id]) + if not any(arm.get("type") == "null" for arm in arms): + return True + return any(_needs_msa(value) for value in schema.values()) + if isinstance(schema, list): + return any(_needs_msa(value) for value in schema) + return False + + +def _has_msa(protein: Protein) -> bool: + return protein.msa is not None and _msa_id_of(protein.msa) is not None + + +class StructurePredictionModel(Model): + """A structure-prediction model. + + ``fold`` takes a sequence, ``Protein``, ``Complex``, a list of these, or + an ``MSAFuture`` as one multichain complex, and sends them as + ``complexes``. Chains outside the card's ``input_types`` are left out, + and a card that isn't ``multichain`` folds one protein per complex. + MSAs and templates, given as ``templates`` or attached to the inputs, + 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: + """Predict structures of complexes (``batch/structures``).""" + if not _is_serialized(complexes) and not isinstance(complexes, MSAFuture): + entities = ( + complexes if isinstance(complexes, (list, tuple)) else [complexes] + ) + for entity in entities: + if not isinstance(entity, (Complex, Protein, str, bytes)): + raise TypeError( + "complexes must be a str, bytes, Protein, Complex, a list of " + f"these or an MSAFuture, not {type(entity).__name__}" + ) + if not entities: + raise ValueError("Expected at least one complex to fold") + schema = self._params_schema("batch/structures") + takes_templates = "templates" in schema.get("properties", {}) + if templates is not None and not takes_templates: + raise ValueError(f"model {self.id!r} takes no templates") + + if _is_serialized(complexes): + if templates is not None: + params["templates"] = templates + return super().fold(list(complexes), **params) + + if isinstance(complexes, MSAFuture): + normalized = [msa_future_to_complex(self.session, complexes)] + else: + normalized = normalize_inputs(complexes) + if not normalized: + raise ValueError("Expected at least one complex to fold") + + card = self.metadata + if card.multichain is False: + for complex in normalized: + if len(complex.get_proteins()) > 1: + raise ValueError(f"{self.id} only supports monomers") + if len(complex.get_chains()) != len(complex.get_proteins()): + raise ValueError(f"{self.id} only supports proteins") + if card.input_types is not None: + drops = tuple( + chain_type + for name, chain_type in _CHAIN_TYPES.items() + if name not in card.input_types + ) + if drops: + normalized = [_without(c, drops, self.id) for c in normalized] + for index, complex in enumerate(normalized): + if not complex.get_chains(): + raise ValueError( + f"complex {index} has no chain {self.id} can fold" + ) + takes_msa = _declares(schema, "msa_id") + if _needs_msa(schema): + without_msa = [ + chain_id + for complex in normalized + for chain_id, protein in complex.get_proteins().items() + if not _has_msa(protein) + ] + if without_msa: + raise ValueError( + f"{self.id} needs an MSA for every protein; chain " + f"{without_msa[0]!r} has none. Attach one with " + "`protein.msa = msa`." + ) + if not takes_msa: + with_msa = [ + chain_id + for complex in normalized + for chain_id, protein in complex.get_proteins().items() + if _has_msa(protein) + ] + if with_msa: + raise ValueError( + f"{self.id} is a single-sequence model; chain " + f"{with_msa[0]!r} has an MSA attached. Set " + "`protein.msa = Protein.single_sequence_mode`." + ) + + normalized_templates = ( + normalize_templates(self.session, complexes, templates) + if takes_templates + else [] + ) + serialized = serialize_input(self.session, normalized, takes_msa) + if normalized_templates: + params["templates"] = resolve_templates(self.session, normalized_templates) + return super().fold(serialized, **params) diff --git a/openprotein/models/folding/boltz1.py b/openprotein/models/folding/boltz1.py new file mode 100644 index 0000000..0ad4720 --- /dev/null +++ b/openprotein/models/folding/boltz1.py @@ -0,0 +1,15 @@ +"""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 new file mode 100644 index 0000000..79acfc4 --- /dev/null +++ b/openprotein/models/folding/boltz2.py @@ -0,0 +1,15 @@ +"""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 new file mode 100644 index 0000000..6840013 --- /dev/null +++ b/openprotein/models/folding/esmfold.py @@ -0,0 +1,14 @@ +"""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 new file mode 100644 index 0000000..65ac190 --- /dev/null +++ b/openprotein/models/folding/esmfold2.py @@ -0,0 +1,15 @@ +"""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 new file mode 100644 index 0000000..fc14ca4 --- /dev/null +++ b/openprotein/models/folding/minifold.py @@ -0,0 +1,14 @@ +"""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 new file mode 100644 index 0000000..9136651 --- /dev/null +++ b/openprotein/models/folding/opendde.py @@ -0,0 +1,15 @@ +"""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 new file mode 100644 index 0000000..4c1e540 --- /dev/null +++ b/openprotein/models/folding/protenix.py @@ -0,0 +1,14 @@ +"""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 new file mode 100644 index 0000000..221870f --- /dev/null +++ b/openprotein/models/folding/protenix_v2.py @@ -0,0 +1,15 @@ +"""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 new file mode 100644 index 0000000..01cd3fd --- /dev/null +++ b/openprotein/models/folding/rosettafold3.py @@ -0,0 +1,15 @@ +"""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/boltzgen.py b/openprotein/models/foundation/boltzgen.py deleted file mode 100644 index f8b9b5f..0000000 --- a/openprotein/models/foundation/boltzgen.py +++ /dev/null @@ -1,298 +0,0 @@ -"""BoltzGen model for protein structure and sequence design.""" - -import base64 -import gzip -import io -import tarfile -import warnings -from typing import Any, BinaryIO - -from pydantic import BaseModel - -from openprotein.base import APISession -from openprotein.common import ModelMetadata -from openprotein.models.base import ProteinModel -from openprotein.models.structure_generation import ( - StructureGenerationFuture, - StructureGenerationJob, -) -from openprotein.molecules import Complex, Protein -from openprotein.prompt import PromptAPI, Query -from openprotein.scaffolds import Scaffolds - -from .boltzgen_schema import BoltzGenDesignSpec - - -def _create_assets_archive( - scaffolds: dict[str, str | bytes | BinaryIO] | None = None, - extra_files: dict[str, str | bytes | BinaryIO] | None = None, -) -> bytes | None: - """ - Create a gzipped tar archive from scaffolds and extra files. - - Returns base64-encoded gzipped tar bytes, or None if no files provided. - """ - if not scaffolds and not extra_files: - return None - - # Create in-memory tar.gz - tar_buffer = io.BytesIO() - - with gzip.GzipFile(fileobj=tar_buffer, mode="wb") as gz: - with tarfile.open(fileobj=gz, mode="w") as tar: - # Add scaffolds - if scaffolds: - for filename, content in scaffolds.items(): - # Read content - if isinstance(content, bytes): - data = content - elif isinstance(content, str): - # Assume it's a file path - with open(content, "rb") as f: - data = f.read() - else: - # BinaryIO - data = content.read() - - # Add to tar - info = tarfile.TarInfo(name=f"scaffolds/{filename}") - info.size = len(data) - tar.addfile(info, io.BytesIO(data)) - - # Add extra files - if extra_files: - for filename, content in extra_files.items(): - # Read content - if isinstance(content, bytes): - data = content - elif isinstance(content, str): - with open(content, "rb") as f: - data = f.read() - else: - data = content.read() - - # Add to tar - info = tarfile.TarInfo(name=f"extra/{filename}") - info.size = len(data) - tar.addfile(info, io.BytesIO(data)) - - # Get the gzipped tar bytes - tar_buffer.seek(0) - return tar_buffer.read() - - -class BoltzGenRequest(BaseModel): - "Specification for an BoltzGen request." - - N: int = 1 - query_id: str | None = None - design_spec: BoltzGenDesignSpec | dict[str, Any] | None = None - structure_text: str | None = None - diffusion_batch_size: int | None = None - step_scale: float | None = None - noise_scale: float | None = None - assets: str | None = None # base64-encoded gzipped tar - scaffold_set: str | None = None - - -class BoltzGenFuture(StructureGenerationFuture): - """Deprecated alias for :class:`StructureGenerationFuture`.""" - - def __init__(self, *args, **kwargs): - warnings.warn( - "BoltzGenFuture is deprecated; use StructureGenerationFuture instead.", - DeprecationWarning, - stacklevel=2, - ) - super().__init__(*args, **kwargs) - - -def _boltzgen_api_post( - session: APISession, request: BoltzGenRequest, **kwargs -) -> StructureGenerationJob: - """ - POST a request for BoltzGen design. - - Returns a Job object that can be used to retrieve results later. - """ - endpoint = "v1/design/models/boltzgen" - body = request.model_dump(exclude_none=True) - body.update(kwargs) - response = session.post(endpoint, json=body) - return StructureGenerationJob.model_validate(response.json()) - - -def _boltzgen_api_get_metadata(session: APISession) -> ModelMetadata: - """ - POST a request for BoltzGen design. - - Returns a Job object that can be used to retrieve results later. - """ - endpoint = "v1/design/models/boltzgen" - response = session.get(endpoint) - return ModelMetadata.model_validate(response.json()) - - -class BoltzGenModel(ProteinModel): - """ - BoltzGen model for generating de novo protein structures. - - This model supports functionalities like unconditional design, scaffolding, - and binder design. - """ - - model_id: str = "boltzgen" - - def __init__(self, session: APISession, model_id: str = "boltzgen"): - # The model_id from the API might be more specific, e.g., "boltzgen-v1.1" - super().__init__(session, model_id) - - def get_metadata(self) -> ModelMetadata: - return _boltzgen_api_get_metadata(session=self.session) - - def generate( - self, - query: str | bytes | Protein | Complex | Query | None = None, - design_spec: BoltzGenDesignSpec | dict[str, Any] | None = None, - structure_file: str | bytes | BinaryIO | None = None, - N: int = 1, - diffusion_batch_size: int | None = None, - step_scale: float | None = None, - noise_scale: float | None = None, - # scaffolds that can be provided for design - scaffolds: dict[str, str | bytes | BinaryIO] | None = None, - scaffold_set: Scaffolds | str | None = None, - # extra structures that can be bundled together as assets - extra_structure_files: dict[str, str | bytes | BinaryIO] | None = None, - **kwargs, - ) -> StructureGenerationFuture: - """ - Run a protein structure generate job using BoltzGen. - - Parameters - ---------- - query : str or bytes or Protein or Complex or Query, optional - A query representing the design specification. Either `query` or `design_spec` - must be provided. - `query` provides a unified way to represent design specifications on the - OpenProtein platform. In this case, the structure mask of the containing Complex - proteins are specified to be designed. Other parameters like binding, group, - secondary structures, etc. are also passed through to BoltzGen. - design_spec : BoltzGenDesignSpec | dict[str, Any] | None, optional - The BoltzGen design specification to run. Either `query` or `design_spec` - must be provided. - `design_spec` exposes a low-level interface to using BoltzGen by accepting the YAML - specification used by official BoltzGen examples. - Can be a typed BoltzGenDesignSpec object or a dict representing the - BoltzGen yaml request specification. - Note: If the design_spec includes file paths, provide - these extra files either using `scaffolds` or `extra_structure_files`. - structure_file : str | bytes | BinaryIO | None, optional - (Deprecated: use `extra_structure_files`) - An input PDB/CIF file used for inpainting or other guided design tasks - where parts of an existing structure are provided. This parameter provides - the actual structure content that corresponds to any FileEntity `path` - fields in the design_spec. Can be: - - A file path (str) to read from - - Raw file content (bytes) - - A file-like object (BinaryIO) - n : int, optional - The number of unique design trajectories to run (default is 1). - diffusion_batch_size : int, optional - The batch size for diffusion sampling. Controls how many samples are - processed in parallel during the diffusion process. - step_scale : float, optional - Scaling factor for the number of diffusion steps. Higher values may - improve quality at the cost of longer generation time. - noise_scale : float, optional - Scaling factor for the noise schedule during diffusion. Controls the - amount of noise added at each step of the reverse diffusion process. - scaffolds : dict[str, str | bytes | BinaryIO] | None, optional - Dictionary mapping scaffold filenames to their content. Each value can be: - - A file path (str) to read from - - Raw file content (bytes) - - A file-like object (BinaryIO) - These files will be packaged into a gzipped tar archive and made available - to the design process under the 'scaffolds/' directory. - scaffold_set : Scaffolds | str | None, optional - A pre-defined scaffold set object. Alternative to providing individual - scaffold files via the `scaffolds` parameter. - extra_structure_files : dict[str, str | bytes | BinaryIO] | None, optional - Dictionary mapping additional structure filenames to their content, with - the same format options as `scaffolds`. These files will be packaged into - the same archive under the 'extra/' directory and can be referenced in - the design specification. - - Other Parameters - ---------------- - **kwargs : dict - Additional keyword args that are passed directly to the boltzgen - inference script. Overwrites any preceding options. - - Returns - ------- - StructureGenerationFuture - A future object that can be used to retrieve the results of the design - job upon completion. - """ - # Ensure only query or design_spec is provided - if (query is None and design_spec is None) or ( - query is not None and design_spec is not None - ): - raise ValueError("Expected either `query` or `design_spec`") - - if query is not None: - prompt_api = getattr(self.session, "prompt", None) - assert isinstance(prompt_api, PromptAPI) - query_id = prompt_api._resolve_query( - query=query, force_structure=True - ) # ensure we have a structure query - else: - query_id = None - - # Validate design_spec if it's a dict - if isinstance(design_spec, dict): - design_spec = BoltzGenDesignSpec.model_validate(design_spec) - - # Extract the string - if isinstance(scaffold_set, Scaffolds): - scaffold_set = scaffold_set.value - - request = BoltzGenRequest( - N=N, - query_id=query_id, - design_spec=design_spec, - diffusion_batch_size=diffusion_batch_size, - step_scale=step_scale, - noise_scale=noise_scale, - scaffold_set=scaffold_set, - ) - - # Handle structure_file - if structure_file is not None: - raise ValueError( - "structure_file no longer accepted. use extra_structure_files instead to provide multiple structure files." - ) - - # Create assets archive from scaffolds and extra files - assets_bytes = _create_assets_archive( - scaffolds=scaffolds, extra_files=extra_structure_files - ) - if assets_bytes: - request.assets = base64.b64encode(assets_bytes).decode("utf-8") - - # Submit the job - job = _boltzgen_api_post( - session=self.session, - request=request, - **kwargs, - ) - - return StructureGenerationFuture( - session=self.session, - job=job, - N=request.N, - result_format="cif", - ) - - predict = generate diff --git a/openprotein/models/foundation/boltzgen_schema.py b/openprotein/models/foundation/boltzgen_schema.py deleted file mode 100644 index 7955970..0000000 --- a/openprotein/models/foundation/boltzgen_schema.py +++ /dev/null @@ -1,389 +0,0 @@ -"""Pydantic v2 schema for BoltzGen design specification.""" - -from typing import Literal - -from pydantic import BaseModel, Field, field_validator, model_validator - - -# ============================================================================ -# Entity Definitions -# ============================================================================ - - -class ProteinEntity(BaseModel): - """ - Protein entity specification. - - Attributes - ---------- - id : str or list[str] - Chain identifier(s) for the protein. - sequence : str - Protein sequence. Can include: - - Amino acid letters (A-Z) - - Design residues (numbers, e.g., "10" for 10 design residues) - - Ranges (e.g., "15..20" for random number between 15-20) - - Mixed patterns (e.g., "3..5C6C3" for variable design + fixed residues) - secondary_structure : str | None - Secondary structure specification. Defaults to None. - binding_types : str | dict | None - Binding type specification. Can be: - - String with characters: 'u' (unspecified), 'B' (binding), 'N' (not binding) - - Dict with 'binding' and/or 'not_binding' keys - cyclic : bool - Whether the protein is cyclic. Defaults to False. - """ - - id: str | list[str] - sequence: str - secondary_structure: str | None = None - binding_types: str | dict | None = None - cyclic: bool = False - - -class LigandEntity(BaseModel): - """ - Ligand entity specification. - - Attributes - ---------- - id : str or list[str] - Chain identifier(s) for the ligand. - ccd : str | None - Chemical Component Dictionary identifier. - smiles : str | None - SMILES string representation of the ligand. - binding_types : str | dict | None - Binding type specification. - """ - - id: str | list[str] - ccd: str | None = None - smiles: str | None = None - binding_types: str | dict | None = None - - @model_validator(mode="after") - def check_ccd_or_smiles(self): - """Ensure either ccd or smiles is provided.""" - if self.ccd is None and self.smiles is None: - raise ValueError("Either 'ccd' or 'smiles' must be provided for ligand") - return self - - -class ChainInclude(BaseModel): - """ - Chain inclusion specification. - - Attributes - ---------- - id : str - Chain identifier. - res_index : str | None - Residue index range (e.g., "10..16", "..5", "20.."). - """ - - id: str - res_index: str | None = None - - -class ChainIncludeProximity(BaseModel): - """ - Proximity-based chain inclusion. - - Attributes - ---------- - id : str - Chain identifier. - res_index : str - Residue index range. - radius : float - Radius in angstroms for proximity inclusion. - """ - - id: str - res_index: str - radius: float - - -class ChainBindingType(BaseModel): - """ - Binding type specification for a chain. - - Attributes - ---------- - id : str - Chain identifier. - binding : str | None - Residue indices that are binding (e.g., "5..7,13"). - not_binding : str | None - Residue indices that are not binding (e.g., "9..11" or "all"). - """ - - id: str - binding: str | None = None - not_binding: str | None = None - - -class StructureGroup(BaseModel): - """ - Structure group for visibility control. - - Attributes - ---------- - visibility : int - Visibility level (0, 1, 2, etc.). - id : str - Chain identifier or "all". - res_index : str | None - Residue index range. - """ - - visibility: int - id: str - res_index: str | None = None - - -class ChainDesign(BaseModel): - """ - Design specification for a chain. - - Attributes - ---------- - id : str - Chain identifier. - res_index : str - Residue indices to design (e.g., "..4,20..27"). - """ - - id: str - res_index: str - - -class ChainSecondaryStructure(BaseModel): - """ - Secondary structure specification for a chain. - - Attributes - ---------- - id : str - Chain identifier. - loop : str | None - Residue indices for loop regions. - helix : str | None - Residue indices for helix regions. - sheet : str | None - Residue indices for sheet regions. - """ - - id: str - loop: str | None = None - helix: str | None = None - sheet: str | None = None - - -class DesignInsertion(BaseModel): - """ - Design insertion specification. - - Attributes - ---------- - id : str - Chain identifier. - res_index : int - Residue index where insertion occurs (1-based). - num_residues : str | int - Number of residues to insert. Can be a range (e.g., "2..9") or fixed number. - secondary_structure : Literal["UNSPECIFIED", "LOOP", "HELIX", "SHEET"] - Secondary structure type for inserted residues. - """ - - id: str - res_index: int - num_residues: str | int - secondary_structure: Literal["UNSPECIFIED", "LOOP", "HELIX", "SHEET"] = ( - "UNSPECIFIED" - ) - - -class FileEntity(BaseModel): - """ - File-based entity specification (e.g., PDB/CIF files). - - Note - ---- - When using the `generate()` method, the `path` field is overwritten by the - `structure_file` argument. The OpenProtein platform backend currently only - accepts structure files via the `structure_file` parameter, not as paths - in the design spec. The `path` field is included here for compatibility with - the BoltzGen YAML format, but will be replaced when submitting to the API. - - Attributes - ---------- - path : str - Path to the structure file. This is a placeholder that will be overwritten - by the `structure_file` argument when calling `generate()`. The actual - structure content must be provided via the `structure_file` parameter. - fuse : str | None - Chain ID to fuse with. - include : str | list[dict] - Chains or regions to include. Can be "all" or list of chain specifications. - exclude : list[dict] | None - Chains or regions to exclude. - include_proximity : list[dict] | None - Proximity-based inclusion specifications. - binding_types : list[dict] | None - Binding type specifications for chains. - structure_groups : list[dict] | None - Structure group specifications. - design : list[dict] | None - Design specifications for chains. - secondary_structure : list[dict] | None - Secondary structure specifications for chains. - design_insertions : list[dict] | None - Design insertion specifications. - """ - - path: str - fuse: str | None = None - include: str | list[dict] | None = None - exclude: list[dict] | None = None - include_proximity: list[dict] | None = None - binding_types: list[dict] | None = None - structure_groups: list[dict] | None = None - design: list[dict] | None = None - secondary_structure: list[dict] | None = None - design_insertions: list[dict] | None = None - - -class Entity(BaseModel): - """ - Entity wrapper for different entity types. - - Attributes - ---------- - protein : ProteinEntity | None - Protein entity specification. - ligand : LigandEntity | None - Ligand entity specification. - file : FileEntity | None - File-based entity specification. - """ - - protein: ProteinEntity | None = None - ligand: LigandEntity | None = None - file: FileEntity | None = None - - @model_validator(mode="after") - def check_exactly_one_entity(self): - """Ensure exactly one entity type is specified.""" - entities = [self.protein, self.ligand, self.file] - if sum(x is not None for x in entities) != 1: - raise ValueError( - "Exactly one of 'protein', 'ligand', or 'file' must be specified" - ) - return self - - -# ============================================================================ -# Constraint Definitions -# ============================================================================ - - -class BondConstraint(BaseModel): - """ - Covalent bond constraint between two atoms. - - Attributes - ---------- - atom1 : list[str | int] - First atom specification: [CHAIN_ID, RES_IDX, ATOM_NAME]. - atom2 : list[str | int] - Second atom specification: [CHAIN_ID, RES_IDX, ATOM_NAME]. - """ - - atom1: list[str | int] = Field(..., min_length=3, max_length=3) - atom2: list[str | int] = Field(..., min_length=3, max_length=3) - - -class TotalLengthConstraint(BaseModel): - """ - Total length constraint for the design. - - Attributes - ---------- - min : int | None - Minimum total length. - max : int | None - Maximum total length. - """ - - min: int | None = None - max: int | None = None - - -class Constraint(BaseModel): - """ - Constraint wrapper for different constraint types. - - Attributes - ---------- - bond : BondConstraint | None - Bond constraint specification. - total_len : TotalLengthConstraint | None - Total length constraint specification. - """ - - bond: BondConstraint | None = None - total_len: TotalLengthConstraint | None = None - - @model_validator(mode="after") - def check_at_least_one_constraint(self): - """Ensure at least one constraint type is specified.""" - constraints = [self.bond, self.total_len] - if sum(x is not None for x in constraints) == 0: - raise ValueError("At least one constraint type must be specified") - return self - - -# ============================================================================ -# Top-Level Design Spec -# ============================================================================ - - -class BoltzGenDesignSpec(BaseModel): - """ - Complete BoltzGen design specification. - - This schema represents the full design specification for BoltzGen, - including entities (proteins, ligands, files) and constraints. - - Attributes - ---------- - entities : list[Entity] - List of entities in the design. - constraints : list[Constraint] | None - List of constraints for the design. - - Examples - -------- - >>> spec = BoltzGenDesignSpec( - ... entities=[ - ... Entity(protein=ProteinEntity(id="A", sequence="ACDEFGHIKLMNPQRSTVWY")), - ... Entity(ligand=LigandEntity(id="B", ccd="ATP")) - ... ], - ... constraints=[ - ... Constraint(bond=BondConstraint(atom1=["A", 10, "CA"], atom2=["B", 1, "O"])) - ... ] - ... ) - """ - - entities: list[Entity] - constraints: list[Constraint] | None = None - - @field_validator("entities") - @classmethod - def check_entities_not_empty(cls, v): - """Ensure at least one entity is provided.""" - if not v: - raise ValueError("At least one entity must be specified") - return v diff --git a/openprotein/models/foundation/esmif1.py b/openprotein/models/foundation/esmif1.py deleted file mode 100644 index 51fd29b..0000000 --- a/openprotein/models/foundation/esmif1.py +++ /dev/null @@ -1,213 +0,0 @@ -"""ESM-IF1 model providing inverse-folding, scoring, and generation capabilities.""" - -from typing import TYPE_CHECKING - -from openprotein.base import APISession -from openprotein.common import ModelMetadata -from openprotein.embeddings import api as embeddings_api -from openprotein.embeddings.future import ( - EmbeddingsGenerateFuture, - EmbeddingsScoreFuture, - EmbeddingsScoreSingleSiteFuture, -) -from openprotein.models.base import ProteinModel -from openprotein.molecules import Complex, Protein -from openprotein.prompt import PromptAPI, Query - -if TYPE_CHECKING: - from openprotein.models.structure_generation import StructureGenerationFuture - - -class ESMIF1Model(ProteinModel): - """ - Class for ESM Inverse Folding (ESM-IF1) model. - - Model inference requires an input structure which is provided by a `query`. - - Examples - -------- - View specific model details (including supported tokens) with the `?` operator. - - Examples - -------- - .. code-block:: ipython3 - - >>> import openprotein - >>> session = openprotein.connect() - >>> session.models.esmif1? - """ - - model_id = "esm-if1" - - def __init__(self, session: APISession): - super().__init__(session=session, model_id=self.model_id) - - def get_metadata(self) -> ModelMetadata: - return embeddings_api.get_model(session=self.session, model_id=self.model_id) - - def score( - self, - sequences: list[bytes] | list[str], - query: str | bytes | Protein | Complex | Query, - ) -> EmbeddingsScoreFuture: - """ - Score sequences based on the specified query. - - Parameters - ---------- - sequences : list of bytes or str - Sequences to score. - query : str or bytes or Protein or Complex or Query - Query to use with prompt. - - Returns - ------- - EmbeddingsScoreFuture - A future object that returns the scores of the submitted sequences. - """ - prompt_api = getattr(self.session, "prompt", None) - assert isinstance(prompt_api, PromptAPI) - query_id = prompt_api._resolve_query(query=query) - return EmbeddingsScoreFuture.create( - session=self.session, - job=embeddings_api.request_score_post( - session=self.session, - model_id=self.id, - sequences=sequences, - query_id=query_id, - ), - sequences=sequences, - ) - - def single_site( - self, - sequence: bytes | str, - query: str | bytes | Protein | Complex | Query, - ) -> EmbeddingsScoreSingleSiteFuture: - """ - Score all single substitutions of `sequence` using the specified `query`. - - Parameters - ---------- - sequence : bytes or str - Sequence to analyze. - query : str or bytes or Protein or Complex or Query - Query to use with prompt. - - Returns - ------- - EmbeddingsScoreSingleSiteFuture - A future object that returns the per-variant scores. - """ - prompt_api = getattr(self.session, "prompt", None) - assert isinstance(prompt_api, PromptAPI) - query_id = prompt_api._resolve_query(query=query) - return EmbeddingsScoreSingleSiteFuture.create( - session=self.session, - job=embeddings_api.request_score_single_site_post( - session=self.session, - model_id=self.id, - base_sequence=sequence, - query_id=query_id, - ), - ) - - def indel( - self, - sequence: bytes | str, - query: str | bytes | Protein | Complex | Query, - insert: str | None = None, - delete: list[int] | None = None, - ) -> EmbeddingsScoreFuture: - """ - Score all indels of `sequence` based on the specified `query`. - - Parameters - ---------- - sequence : bytes or str - Sequence to analyze. - query : str or bytes or Protein or Query or None, optional - Query to use with prompt. - insert : str or None, optional - Insertion fragment at each site. - delete : list of int or None, optional - Range of size of fragment to delete at each site. - **kwargs - Additional keyword arguments. - - Returns - ------- - EmbeddingsScoreFuture - A future object that returns the scores of the indel-ed sequence. - - Raises - ------ - ValueError - If neither insert nor delete is provided. - """ - raise NotImplementedError("Score indel not yet implemented") - - def generate( - self, - query: ( - str - | bytes - | Protein - | Complex - | Query - | list[str | bytes | Protein | Complex | Query] - | None - ) = None, - design: "str | StructureGenerationFuture | None" = None, - num_samples: int = 100, - temperature: float = 1.0, - seed: int | None = None, - ) -> EmbeddingsGenerateFuture: - """ - Generate protein sequences based on a masked input query. - - Parameters - ---------- - query : str or bytes or Protein or Complex or Query or list of these or None, optional - Query specifying the structure to generate sequences for. - design : str or StructureGenerationFuture or None, optional - Structure-generation design ID or future to condition generation from - design outputs. - num_samples : int, optional - Number of sequences to sample. Default 100. - temperature : float, optional - Sampling temperature. Lower = more conservative; near-zero - approximates greedy decoding. Default 1.0. - seed : int, optional - PRNG seed for reproducible sampling. - - Returns - ------- - EmbeddingsGenerateFuture - A future object representing the status and information about the generation job. - """ - if query is None and design is None: - raise ValueError("Expected either `query` or `design` to be provided") - - from openprotein.models.structure_generation import StructureGenerationFuture - - query_id = None - if query is not None: - prompt_api = getattr(self.session, "prompt", None) - assert isinstance(prompt_api, PromptAPI) - query_id = prompt_api._resolve_query(query=query) - design_id = ( - design.job_id if isinstance(design, StructureGenerationFuture) else design - ) - return EmbeddingsGenerateFuture.create( - session=self.session, - job=embeddings_api.request_generate_post( - session=self.session, - model_id=self.id, - query_id=query_id, - design_id=design_id, - num_samples=num_samples, - temperature=temperature, - random_seed=seed, - ), - ) diff --git a/openprotein/models/foundation/proteinmpnn.py b/openprotein/models/foundation/proteinmpnn.py deleted file mode 100644 index c2f4e1b..0000000 --- a/openprotein/models/foundation/proteinmpnn.py +++ /dev/null @@ -1,193 +0,0 @@ -"""ProteinMPNN model providing inverse-folding and scoring capabilities.""" - -from typing import TYPE_CHECKING - -from openprotein.base import APISession -from openprotein.common import ModelMetadata -from openprotein.embeddings import api as embeddings_api -from openprotein.embeddings.future import ( - EmbeddingsGenerateFuture, - EmbeddingsScoreFuture, - EmbeddingsScoreSingleSiteFuture, -) -from openprotein.models.base import ProteinModel -from openprotein.molecules import Complex, Protein -from openprotein.prompt import PromptAPI, Query - -if TYPE_CHECKING: - from openprotein.models.structure_generation import StructureGenerationFuture - - -class ProteinMPNNModel(ProteinModel): - """ - Class for ProteinMPNN model. - - Model inference requires an input structure which is provided by a `query`. - - Examples - -------- - View specific model details (including supported tokens) with the `?` operator. - - Examples - -------- - .. code-block:: ipython3 - - >>> import openprotein - >>> session = openprotein.connect(username="user", password="password") - >>> session.models.proteinmpnn? - """ - - model_id = "proteinmpnn" - - # TODO - Add model to explicitly require prompt_id - def __init__( - self, - session: APISession, - ): - super().__init__(session=session, model_id=self.model_id) - - def get_metadata(self) -> ModelMetadata: - return embeddings_api.get_model(session=self.session, model_id=self.model_id) - - def score( - self, - sequences: list[bytes], - query: str | bytes | Protein | Query, - ) -> EmbeddingsScoreFuture: - """ - Score query sequences based on the specified query. - - Parameters - ---------- - sequences : list of bytes - Sequences to score. - query : str or bytes or Protein or Query or None, optional - Query to use with prompt. - - Returns - ------- - EmbeddingsScoreFuture - A future object that returns the scores of the submitted sequences. - """ - raise NotImplementedError("Score not yet implemented") - - def indel( - self, - sequence: bytes, - query: str | bytes | Protein | Query, - insert: str | None = None, - delete: list[int] | None = None, - **kwargs, - ) -> EmbeddingsScoreFuture: - """ - Score all indels of the query sequence based on the specified query. - - Parameters - ---------- - sequence : bytes - Sequence to analyze. - query : str or bytes or Protein or Query or None, optional - Query to use with prompt. - insert : str or None, optional - Insertion fragment at each site. - delete : list of int or None, optional - Range of size of fragment to delete at each site. - **kwargs - Additional keyword arguments. - - Returns - ------- - EmbeddingsScoreFuture - A future object that returns the scores of the indel-ed sequence. - - Raises - ------ - ValueError - If neither insert nor delete is provided. - """ - raise NotImplementedError("Score indel not yet implemented") - - def single_site( - self, - sequence: bytes, - query: str | bytes | Protein | Query, - ) -> EmbeddingsScoreSingleSiteFuture: - """ - Score all single substitutions of the query sequence using the specified query. - - Parameters - ---------- - sequence : bytes - Sequence to analyze. - query : str or bytes or Protein or Query or None, optional - Query to use with prompt. - - Returns - ------- - EmbeddingsScoreSingleSiteFuture - A future object that returns the per-variant scores of the single substitutions. - """ - raise NotImplementedError("Score single site not yet implemented") - - def generate( - self, - query: ( - str - | bytes - | Protein - | Complex - | Query - | list[str | bytes | Protein | Complex | Query] - | None - ) = None, - design: "str | StructureGenerationFuture | None" = None, - num_samples: int = 100, - temperature: float = 0.1, - # topk: float | None = None, - # topp: float | None = None, - # max_length: int = 1000, - seed: int | None = None, - ) -> EmbeddingsGenerateFuture: - """ - Generate protein sequences based on a masked input query. - - Parameters - ---------- - query : str or bytes or Protein or Complex or Query or list of these or None, optional - Query specifying the structure to generate sequences for. - design : str or StructureGenerationFuture or None, optional - Structure-generation design ID or future to condition generation from - design outputs. - num_samples : int, optional - The number of samples to generate. Default is 100. - temperature : float, optional - The temperature for sampling. Higher values produce more random outputs. Default is 0.1. - - Returns - ------- - EmbeddingsGenerateFuture - A future object representing the status and information about the generation job. - """ - if query is None and design is None: - raise ValueError("Expected either `query` or `design` to be provided") - - from openprotein.models.structure_generation import StructureGenerationFuture - - 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 - design_id = ( - design.job_id if isinstance(design, StructureGenerationFuture) else design - ) - return EmbeddingsGenerateFuture.create( - session=self.session, - job=embeddings_api.request_generate_post( - session=self.session, - model_id=self.id, - query_id=query_id, - design_id=design_id, - num_samples=num_samples, - temperature=temperature, - random_seed=seed, - ), - ) diff --git a/openprotein/models/foundation/rfdiffusion.py b/openprotein/models/foundation/rfdiffusion.py deleted file mode 100644 index 5aa2d30..0000000 --- a/openprotein/models/foundation/rfdiffusion.py +++ /dev/null @@ -1,288 +0,0 @@ -"""RFdiffusion model for protein structure and sequence design.""" - -import warnings -from typing import BinaryIO, Literal - -from pydantic import BaseModel, Field - -from openprotein.base import APISession -from openprotein.common import ModelMetadata -from openprotein.common.model_metadata import ModelDescription -from openprotein.models.base import ProteinModel -from openprotein.models.structure_generation import ( - StructureGenerationFuture, - StructureGenerationJob, -) -from openprotein.molecules import Complex, Protein -from openprotein.prompt import PromptAPI, Query - - -class Contig(BaseModel): - """Defines a contig segment for protein design.""" - - length: str = Field(..., description="Length range, e.g., '10-20' or '100'") - chain: str | None = Field(None, description="Chain to sample from") - - -class Hotspot(BaseModel): - """Specifies a hotspot residue constraint.""" - - res_id: str = Field( - ..., description="Residue identifier, e.g., 'A100' for chain A, residue 100" - ) - - -class RFdiffusionRequest(BaseModel): - "Specification for an RFdiffusion request." - - N: int = 1 - query_id: str | None = None - structure_text: str | None = None - # contigs: list[Contig] - contigs: str | None = None - inpaint_seq: str | None = None - provide_seq: str | None = None - # hotspots: list[Hotspot] - hotspot: str | None = None - T: int | None = None - partial_T: int | None = None - use_active_site_model: bool | None = None - use_beta_model: bool | None = None - - # Simplified symmetry options - symmetry: Literal["cyclic", "dihedral", "tetrahedral"] | None = None - order: int | None = None - add_potential: bool | None = None - - # Fold conditioning - scaffold_target_structure_text: str | None = None - scaffold_target_use_struct: bool = False - - -class RFdiffusionFuture(StructureGenerationFuture): - """Deprecated alias for :class:`StructureGenerationFuture`.""" - - def __init__(self, *args, **kwargs): - warnings.warn( - "RFdiffusionFuture is deprecated; use StructureGenerationFuture instead.", - DeprecationWarning, - stacklevel=2, - ) - super().__init__(*args, **kwargs) - - -def _rfdiffusion_api_post( - session: APISession, request: RFdiffusionRequest, **kwargs -) -> StructureGenerationJob: - """ - POST a request for RFdiffusion design. - - Returns a Job object that can be used to retrieve results later. - """ - endpoint = "v1/design/models/rfdiffusion" - body = request.model_dump(exclude_none=True) - body.update(kwargs) - response = session.post(endpoint, json=body) - return StructureGenerationJob.model_validate(response.json()) - - -def _rfdiffusion_api_get_metadata(session: APISession) -> ModelMetadata: - """ - POST a request for RFdiffusion design. - - Returns a Job object that can be used to retrieve results later. - """ - endpoint = f"v1/design/models/rfdiffusion" - response = session.get(endpoint) - return ModelMetadata.model_validate(response.json()) - - -class RFdiffusionModel(ProteinModel): - """ - RFdiffusion model for generating de novo protein structures. - - This model supports functionalities like unconditional design, scaffolding, - and binder design. - """ - - model_id: str = "rfdiffusion" - - def __init__(self, session: APISession, model_id: str = "rfdiffusion"): - # The model_id from the API might be more specific, e.g., "rfdiffusion-v1.1" - super().__init__(session, model_id) - - def get_metadata(self) -> ModelMetadata: - return ModelMetadata( - model_id="rfdiffusion", - description=ModelDescription(summary="RFdiffusion"), - dimension=0, - output_types=["pdb"], - input_tokens=[], - token_descriptions=[[]], - ) - - def generate( - self, - query: str | bytes | Protein | Complex | Query | None = None, - contigs: int | str | None = None, - structure_file: str | bytes | BinaryIO | None = None, - N: int = 1, - inpaint_seq: str | None = None, - provide_seq: str | None = None, - # binding sites - hotspot: str | None = None, - # diffusion timesteps - T: int | None = None, - partial_T: int | None = None, - # model options - use_active_site_model: bool | None = None, - use_beta_model: bool | None = None, - # Symmetry options - symmetry: Literal["cyclic", "dihedral", "tetrahedral"] | None = None, - order: int | None = None, - add_potential: bool | None = None, - # Fold conditioning - # TODO: provide query as a way to do fold conditioning - scaffold_target_structure_file: str | bytes | BinaryIO | None = None, - scaffold_target_use_struct: bool = False, - **kwargs, - ) -> StructureGenerationFuture: - """ - Run a protein structure generate job using RFdiffusion. - - Parameters - ---------- - query : str or bytes or Protein or Complex or Query, optional - A query representing the design specification. Use either `query` or `contigs` - for default design. Or provide `scaffold_target_structure_file` - for scaffold guided design. - `query` provides a unified way to represent design specifications on the - OpenProtein platform. In this case, the structure mask of the containing Complex - proteins are specified to be designed. Other parameters like binding are passed - as hotspots to RFdiffusion. - contigs : int, str, optional - Defines the lengths and connectivity of chain segments for the desired - structure, specified in RFdiffusion's contig string format. - Required for most design tasks. Example: 150, '10-20/A100-110/10-20' for a - binder design. - structure_file : BinaryIO, optional - An input PDB file (as a file-like object) used for inpainting or other - guided design tasks where parts of an existing structure are provided. - n : int, optional - The number of unique design trajectories to run (default is 1). - inpaint_seq : str, optional - A string specifying the regions in the input structure to mask for - in-painting. Example: 'A1-A10/A30-40'. - provide_seq : str, optional - A string specifying which segments of the contig have a provided - sequence. Example: 'A1-A10/A30-40'. - hotspot : str, optional - A string specifying hotspot residues to constrain during design, - typically for functional sites. Example: 'A10,A12,A14'. - T : int, optional - The number of timesteps for the diffusion process. - partial_T : int, optional - The number of timesteps for partial diffusion. - use_active_site_model : bool, optional - If True, uses the active site model checkpoint, which has been finetuned to - better keep very small motifs in place in the output for motif scaffolding - (default is False). - use_beta_model : bool, optional - If True, uses the complex beta model checkpoint, which generates a - greater diversity of topologies but has not been extensively - experimentally validated (default is False). - symmetry : {"cyclic", "dihedral", "tetrahedral"}, optional - The type of symmetry to apply to the design. - order : int, optional - The order of the symmetry (e.g., 3 for C3 or D3 symmetry). - Must be provided if `symmetry` is set. - add_potential : bool, optional - A flag to toggle an additional potential to guide the design. - This defaults to true in the case of symmetric design. - scaffold_target_structure_file : str, bytes, BinaryIO, optional - A PDB file (which can be the text string or bytes or the file-like - object) containing a scaffold structure to be used as a structural - guide. It could also be used as a target when doing scaffold guided - binder design with `scaffold_target_use_struct`. - scaffold_target_use_struct : bool, optional - Whether or not to use the provided scaffold structure as a target. - Otherwise, it is used only as a topology guide. - - Other Parameters - ---------------- - **kwargs : dict - Additional keyword args that are passed directly to the rfdiffusion - inference script. Overwrites any preceding options. - - Returns - ------- - StructureGenerationFuture - A future object that can be used to retrieve the results of the design - job upon completion. - """ - if query is None and contigs is None and scaffold_target_structure_file is None: - raise ValueError( - "Expected either `query`, `contigs` or `scaffold_target_structure_file`" - ) - if query is not None: - prompt_api = getattr(self.session, "prompt", None) - assert isinstance(prompt_api, PromptAPI) - query_id = prompt_api._resolve_query( - query=query, force_structure=True - ) # ensure we have a structure query - else: - query_id = None - - if isinstance(contigs, int): - contigs = f"{contigs}-{contigs}" - request = RFdiffusionRequest( - N=N, - query_id=query_id, - contigs=contigs, - inpaint_seq=inpaint_seq, - provide_seq=provide_seq, - hotspot=hotspot, - T=T, - partial_T=partial_T, - use_active_site_model=use_active_site_model, - use_beta_model=use_beta_model, - symmetry=symmetry, - order=order, - add_potential=add_potential, - scaffold_target_use_struct=scaffold_target_use_struct, - ) - if structure_file is not None: - if isinstance(structure_file, bytes): - structure_text = structure_file.decode() - elif isinstance(structure_file, str): - structure_text = structure_file - else: - structure_text = structure_file.read().decode() - request.structure_text = structure_text - if scaffold_target_structure_file is not None: - if isinstance(scaffold_target_structure_file, bytes): - scaffold_target_structure_text = scaffold_target_structure_file.decode() - elif isinstance(scaffold_target_structure_file, str): - scaffold_target_structure_text = scaffold_target_structure_file - else: - scaffold_target_structure_text = ( - scaffold_target_structure_file.read().decode() - ) - request.scaffold_target_structure_text = scaffold_target_structure_text - - # Submit the job via the private API function - job = _rfdiffusion_api_post( - session=self.session, - request=request, - **kwargs, - ) - - # Return the future object - return StructureGenerationFuture( - session=self.session, - job=job, - N=request.N, - result_format="pdb", - ) - - predict = generate diff --git a/openprotein/models/foundation/solublempnn.py b/openprotein/models/foundation/solublempnn.py deleted file mode 100644 index dd6032f..0000000 --- a/openprotein/models/foundation/solublempnn.py +++ /dev/null @@ -1,25 +0,0 @@ -"""SolubleMPNN model: ProteinMPNN variant tuned for soluble protein targets.""" - -from .proteinmpnn import ProteinMPNNModel - - -class SolubleMPNNModel(ProteinMPNNModel): - """ - Class for SolubleMPNN model. - - Soluble-protein variant of ProteinMPNN. - - Examples - -------- - View specific model details (including supported tokens) with the `?` operator. - - Examples - -------- - .. code-block:: ipython3 - - >>> import openprotein - >>> session = openprotein.connect(username="user", password="password") - >>> session.models.solublempnn? - """ - - model_id = "solublempnn" diff --git a/openprotein/models/foundational/__init__.py b/openprotein/models/foundational/__init__.py new file mode 100644 index 0000000..1623a6b --- /dev/null +++ b/openprotein/models/foundational/__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/foundational/_inverse_folding.py b/openprotein/models/foundational/_inverse_folding.py new file mode 100644 index 0000000..0f008d7 --- /dev/null +++ b/openprotein/models/foundational/_inverse_folding.py @@ -0,0 +1,127 @@ +"""The verbs inverse-folding models share.""" + +from typing import Any, cast + +from openprotein import _deprecation +from openprotein.jobs import futures + +from .. import _inputs +from ..model import Model, _prepared, _text + + +def _renamed(params: dict[str, Any], method: str, old: str, new: str) -> None: + """Move a deprecated keyword in ``params`` to its current name.""" + if old not in params: + return + _deprecation.warn_deprecated( + f"{method}({old}=...)", + f"`{method}({new}=...)`", + since="0.18.0", + removed_in="0.19.0", + stacklevel=4, + ) + if params.get(new) is not None: + raise TypeError(f"pass {new}, not both {new} and {old}") + params[new] = params.pop(old) + + +class _InverseFoldingModel(Model): + """A model that scores and designs sequences on a structure. + + Every verb takes ``query``, the structure to condition on: a ``Protein``, + ``Complex``, ``Query`` or query id, sent as ``query_id``. + """ + + def _on_structure( + self, + params: dict[str, Any], + query: Any = None, + design: Any = None, + many: bool = False, + method: tuple[str, str] | None = None, + ) -> dict[str, Any]: + _inputs.check_inputs(params, query=query, design=design) + _inputs.check_one_structure_source(params, query, design) + if method is not None: + self._method(*method) + params = dict(params) + _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 params + + def score( + self, sequences: list[str] | list[bytes], query: Any = None, **params: Any + ) -> futures.LogLikelihoodFuture: + """Log-likelihoods of sequences on the query's backbone (``batch/loglikelihood``).""" + sequences = _prepared(sequences) + return super().score( + sequences, + **self._on_structure( + params, query, method=("score", "batch/loglikelihood") + ), + ) + + def single_site( + self, base_sequence: str | bytes | None = None, query: Any = None, **params: Any + ) -> futures.SingleSiteScoreFuture: + """Score every single-site mutant of ``base_sequence`` on the query's backbone. + + .. deprecated:: 0.18.0 + ``sequence=`` is removed in 0.19.0; pass ``base_sequence``. + """ + 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) + if base_sequence is None: + raise TypeError("single_site() missing argument: base_sequence") + base_sequence = _text(base_sequence, "base_sequence") + return cast( + futures.SingleSiteScoreFuture, + super().single_site( + base_sequence, + **self._on_structure( + params, query, method=("single_site", "single-site/*") + ), + ), + ) + + def generate( + self, + query: Any = None, + design: Any = None, + **params: Any, + ) -> futures.SequenceGenerationFuture: + """Design sequences for a backbone (``generate/sequences``). + + Pass ``query``, the backbone, or ``design``, an RFdiffusion or BoltzGen + job or its id, in any state. A design's job runs once the design has + finished, with ``num_samples`` per designed structure. + + .. deprecated:: 0.18.0 + ``seed=`` is removed in 0.19.0; pass ``random_seed``. + """ + _renamed(params, "generate", "seed", "random_seed") + _inputs.check_inputs(params, query=query, design=design) + _inputs.check_one_structure_source(params, query, design) + if all( + value is None + for value in ( + query, + design, + params.get("query_id"), + params.get("design_id"), + ) + ): + raise TypeError("generate() needs a query or a design") + self._method("generate", "generate/*") + many = _inputs.takes_list(self._params_schema("generate/sequences"), "query_id") + return cast( + futures.SequenceGenerationFuture, + super().generate(**self._on_structure(params, query, design, many=many)), + ) diff --git a/openprotein/models/foundational/ablang2.py b/openprotein/models/foundational/ablang2.py new file mode 100644 index 0000000..fa125ed --- /dev/null +++ b/openprotein/models/foundational/ablang2.py @@ -0,0 +1,14 @@ +"""AbLang2.""" + +from .base import ProteinLanguageModel + +__all__ = ["AbLang2"] + + +class AbLang2(ProteinLanguageModel): + """AbLang2, an antibody language model for paired heavy and light chains. + + Its checkpoint is ``ablang2``. + """ + + _default_id = "ablang2" diff --git a/openprotein/models/foundational/base.py b/openprotein/models/foundational/base.py new file mode 100644 index 0000000..50f8876 --- /dev/null +++ b/openprotein/models/foundational/base.py @@ -0,0 +1,122 @@ +"""The base handle of the foundational protein models.""" + +from typing import TYPE_CHECKING, Any, cast + +from openprotein.common import Reduction +from openprotein.data.assaydataset import AssayDataset +from openprotein.jobs import futures + +from .. import _inputs +from ..model import Model, _texts + +if TYPE_CHECKING: + from openprotein.jobs.futures import GPFitFuture, SVDFitFuture, UMAPFitFuture + +__all__ = ["ProteinLanguageModel"] + + +class ProteinLanguageModel(Model): + """A protein language model: embeddings pooled by default, 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``. + """ + + _embeds_assay_by_id = True + + def embed( + self, + sequences: list[str] | list[bytes] | AssayDataset, + reduction: Reduction | None = "MEAN", + **params: Any, + ) -> futures.EmbeddingFuture: + """Embed sequences or an assay's (``batch/embeddings``); + ``reduction=None`` is per residue. + """ + return super().embed(sequences, reduction=reduction, **params) + + def single_site( + self, base_sequence: str | bytes, **params: Any + ) -> futures.SingleSiteScoreFuture: + """Score the sequence's single-site substitutions.""" + return cast( + futures.SingleSiteScoreFuture, + super().single_site(base_sequence, **params), + ) + + def fit_svd( + self, + sequences: list[str] | list[bytes] | None = None, + assay: Any = None, + n_components: int | None = None, + reduction: Reduction | None = None, + **params: Any, + ) -> "SVDFitFuture": + """Fit an SVD on this model's embeddings of ``sequences`` or an assay's.""" + from ..svd import _fit + + _inputs.check_fit_source(sequences, assay) + return _fit( + self.session, + self, + sequences=None if sequences is None else _texts(sequences), + assay=assay, + n_components=n_components, + reduction=reduction, + **params, + ) + + 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, + **params: Any, + ) -> "UMAPFitFuture": + """Fit a UMAP on this model's embeddings of ``sequences`` or an assay's.""" + from ..umap import _fit + + _inputs.check_fit_source(sequences, assay) + return _fit( + self.session, + self, + sequences=None if sequences is None else _texts(sequences), + assay=assay, + reduction=reduction, + n_components=n_components, + n_neighbors=n_neighbors, + min_dist=min_dist, + **params, + ) + + 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, + **params: Any, + ) -> "GPFitFuture": + """Train a Gaussian process on an assay's properties, featurized by this model.""" + from ..gp import _fit + + return _fit( + self.session, + self, + assay=assay, + properties=properties, + reduction=reduction, + name=name, + description=description, + kernel=kernel, + period=period, + alpha=alpha, + **params, + ) diff --git a/openprotein/models/foundational/esm1.py b/openprotein/models/foundational/esm1.py new file mode 100644 index 0000000..8e78f55 --- /dev/null +++ b/openprotein/models/foundational/esm1.py @@ -0,0 +1,16 @@ +"""ESM-1.""" + +from .base import ProteinLanguageModel + +__all__ = ["ESM1"] + + +class ESM1(ProteinLanguageModel): + """ESM-1, a masked protein language model with 650M parameters. + + Its checkpoints are ``esm1b_t33_650M_UR50S``, ESM-1b trained on UniRef50 and the + default, and ``esm1v_t33_650M_UR90S_1`` to ``esm1v_t33_650M_UR90S_5``, the five + ESM-1v models trained on UniRef90 for variant effect prediction. + """ + + _default_id = "esm1b_t33_650M_UR50S" diff --git a/openprotein/models/foundational/esm2.py b/openprotein/models/foundational/esm2.py new file mode 100644 index 0000000..e9b3a2e --- /dev/null +++ b/openprotein/models/foundational/esm2.py @@ -0,0 +1,16 @@ +"""ESM2.""" + +from .base import ProteinLanguageModel + +__all__ = ["ESM2"] + + +class ESM2(ProteinLanguageModel): + """ESM2, a masked protein language model trained on UniRef50. + + Its checkpoints differ only in size: ``esm2_t6_8M_UR50D``, ``esm2_t12_35M_UR50D``, + ``esm2_t30_150M_UR50D``, ``esm2_t33_650M_UR50D``, the default, and + ``esm2_t36_3B_UR50D``. + """ + + _default_id = "esm2_t33_650M_UR50D" diff --git a/openprotein/models/foundational/esmc.py b/openprotein/models/foundational/esmc.py new file mode 100644 index 0000000..3d7b4f6 --- /dev/null +++ b/openprotein/models/foundational/esmc.py @@ -0,0 +1,15 @@ +"""ESM Cambrian.""" + +from .base import ProteinLanguageModel + +__all__ = ["ESMC"] + + +class ESMC(ProteinLanguageModel): + """ESM Cambrian, a protein language model. + + It was trained on sequences from UniRef, MGnify and JGI. Its checkpoints differ in + size: ``esmc-300m``, ``esmc-600m``, the default, and ``esmc-6b``. + """ + + _default_id = "esmc-600m" diff --git a/openprotein/models/foundational/esmif1.py b/openprotein/models/foundational/esmif1.py new file mode 100644 index 0000000..17ad19f --- /dev/null +++ b/openprotein/models/foundational/esmif1.py @@ -0,0 +1,15 @@ +"""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/poet.py b/openprotein/models/foundational/poet.py new file mode 100644 index 0000000..36987bf --- /dev/null +++ b/openprotein/models/foundational/poet.py @@ -0,0 +1,196 @@ +"""PoET.""" + +from typing import TYPE_CHECKING, Any, cast + +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 .base import ProteinLanguageModel + +if TYPE_CHECKING: + from openprotein.jobs.futures import GPFitFuture, SVDFitFuture, UMAPFitFuture + +__all__ = ["PoET"] + + +class PoET(ProteinLanguageModel): + """PoET, a protein language model conditioned on a protein family. + + It embeds, scores and generates sequences given a prompt sampled from the + family's MSA. Every verb takes ``prompt``, a prompt or its id, sent as + ``prompt_id``. Its checkpoint is ``poet``. + """ + + _default_id = "poet" + + def _conditioned( + self, + params: dict[str, Any], + prompt: Any = None, + query: Any = None, + assay: Any = None, + method: tuple[str, str] | None = None, + ) -> dict[str, Any]: + _inputs.check_inputs(params, prompt=prompt, query=query, assay=assay) + if method is not None: + self._method(*method) + 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), "query" + ) + return params + + def embed( + self, + sequences: list[str] | list[bytes] | AssayDataset, + reduction: Reduction | None = "MEAN", + prompt: 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, method=("embed", "batch/embeddings")), + ) + + def logits( + self, sequences: list[str] | list[bytes], prompt: Any = None, **params: Any + ) -> futures.LogitsFuture: + """Per-position logits for sequences (``batch/logits``).""" + sequences = _prepared(sequences) + return super().logits( + sequences, + **self._conditioned(params, prompt, method=("logits", "batch/logits")), + ) + + def score( + self, sequences: list[str] | list[bytes], prompt: Any = None, **params: Any + ) -> futures.LogLikelihoodFuture: + """Log-likelihoods of sequences (``batch/loglikelihood``).""" + sequences = _prepared(sequences) + return super().score( + sequences, + **self._conditioned( + params, prompt, method=("score", "batch/loglikelihood") + ), + ) + + def single_site( + self, base_sequence: str | bytes, prompt: 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, method=("single_site", "single-site/*") + ), + ) + + def indel( + self, + base_sequence: str | bytes, + insert: str | None = None, + delete: list[int] | None = None, + prompt: Any = None, + **params: Any, + ) -> futures.IndelScoreFuture: + """Score ``base_sequence`` with ``insert`` added, or ``delete`` sizes removed, at each site.""" + 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/*")), + ) + + def generate( + self, prompt: Any = None, **params: Any + ) -> futures.SequenceGenerationFuture: + """Sample sequences (``generate/sequences``).""" + return cast( + futures.SequenceGenerationFuture, + super().generate( + **self._conditioned(params, prompt, method=("generate", "generate/*")) + ), + ) + + 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, + **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, assay=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, + **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, assay=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, + **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, assay=assay), + ) diff --git a/openprotein/models/foundational/poet2.py b/openprotein/models/foundational/poet2.py new file mode 100644 index 0000000..b3bf2b1 --- /dev/null +++ b/openprotein/models/foundational/poet2.py @@ -0,0 +1,212 @@ +"""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 new file mode 100644 index 0000000..e959258 --- /dev/null +++ b/openprotein/models/foundational/proteinmpnn.py @@ -0,0 +1,44 @@ +"""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/foundational/protseq.py b/openprotein/models/foundational/protseq.py new file mode 100644 index 0000000..3190eca --- /dev/null +++ b/openprotein/models/foundational/protseq.py @@ -0,0 +1,15 @@ +"""ProtSeq.""" + +from .base import ProteinLanguageModel + +__all__ = ["ProtSeq"] + + +class ProtSeq(ProteinLanguageModel): + """ProtSeq, a masked protein language model trained on UniRef50. + + It has about 300M parameters and was trained with contact and secondary structure + prediction as secondary objectives. Its checkpoint is ``prot-seq``. + """ + + _default_id = "prot-seq" diff --git a/openprotein/models/foundational/prott5.py b/openprotein/models/foundational/prott5.py new file mode 100644 index 0000000..1b55c2a --- /dev/null +++ b/openprotein/models/foundational/prott5.py @@ -0,0 +1,14 @@ +"""ProtT5.""" + +from .base import ProteinLanguageModel + +__all__ = ["ProtT5"] + + +class ProtT5(ProteinLanguageModel): + """ProtT5-XL, an encoder that embeds protein sequences. + + Its checkpoint is ``prott5-xl``. + """ + + _default_id = "prott5-xl" diff --git a/openprotein/models/foundational/rotaprot.py b/openprotein/models/foundational/rotaprot.py new file mode 100644 index 0000000..f8f2d3a --- /dev/null +++ b/openprotein/models/foundational/rotaprot.py @@ -0,0 +1,15 @@ +"""RotaProt.""" + +from .base import ProteinLanguageModel + +__all__ = ["RotaProt"] + + +class RotaProt(ProteinLanguageModel): + """RotaProt, a masked protein language model. + + It has about 900M parameters and uses rotary position embeddings. Its checkpoints + are ``rotaprot-large-uniref50w``, the default, and ``rotaprot-large-uniref90-ft``. + """ + + _default_id = "rotaprot-large-uniref50w" diff --git a/openprotein/models/generative/__init__.py b/openprotein/models/generative/__init__.py new file mode 100644 index 0000000..bbfc8da --- /dev/null +++ b/openprotein/models/generative/__init__.py @@ -0,0 +1,7 @@ +"""Structure generative models.""" + +from .base import StructureGenerativeModel +from .boltzgen import BoltzGen +from .rfdiffusion import RFdiffusion + +__all__ = ["BoltzGen", "RFdiffusion", "StructureGenerativeModel"] diff --git a/openprotein/models/generative/base.py b/openprotein/models/generative/base.py new file mode 100644 index 0000000..51b0a39 --- /dev/null +++ b/openprotein/models/generative/base.py @@ -0,0 +1,48 @@ +"""Shared structure-generation query handling.""" + +from typing import Any, cast + +from openprotein.jobs import futures + +from .. import _inputs +from ..model import Model + +__all__ = ["StructureGenerativeModel"] + + +class StructureGenerativeModel(Model): + """A model that generates structures from design queries.""" + + def generate( + self, query: Any = None, **params: Any + ) -> futures.StructureDesignFuture: + """Generate structures from a query. + + Parameters + ---------- + query : Protein, Complex, Query, str, or list, optional + A design query or query id. Accepted contents depend on the model. + **params + Parameters declared by ``generate/structures``. + + Returns + ------- + StructureDesignFuture + The submitted structure-design job. + """ + _inputs.check_inputs(params, query=query) + self._method("generate", "generate/*") + params = dict(params) + many = _inputs.takes_list( + self._params_schema("generate/structures"), "query_id" + ) + _inputs.with_param( + params, + "query_id", + _inputs.query_ids(self.session, query, force_structure=True, many=many), + "query", + ) + return cast( + futures.StructureDesignFuture, + super().generate(**params), + ) diff --git a/openprotein/models/generative/boltzgen.py b/openprotein/models/generative/boltzgen.py new file mode 100644 index 0000000..8b3fbe1 --- /dev/null +++ b/openprotein/models/generative/boltzgen.py @@ -0,0 +1,15 @@ +"""BoltzGen.""" + +from .base import StructureGenerativeModel + +__all__ = ["BoltzGen"] + + +class BoltzGen(StructureGenerativeModel): + """BoltzGen, an all-atom model that designs binders. + + It designs protein binders against proteins, nucleic acids or small + molecules. The query has a fixed length. Its checkpoint is ``boltzgen``. + """ + + _default_id = "boltzgen" diff --git a/openprotein/models/generative/rfdiffusion.py b/openprotein/models/generative/rfdiffusion.py new file mode 100644 index 0000000..c8cff19 --- /dev/null +++ b/openprotein/models/generative/rfdiffusion.py @@ -0,0 +1,15 @@ +"""RFdiffusion.""" + +from .base import StructureGenerativeModel + +__all__ = ["RFdiffusion"] + + +class RFdiffusion(StructureGenerativeModel): + """RFdiffusion, for de novo backbones, scaffolding and binder design. + + ``Protein.from_expr(n)`` as the query designs ``n`` residues de novo. The + query has a fixed length. Its checkpoint is ``rfdiffusion``. + """ + + _default_id = "rfdiffusion" diff --git a/openprotein/models/gp.py b/openprotein/models/gp.py new file mode 100644 index 0000000..d84b8ca --- /dev/null +++ b/openprotein/models/gp.py @@ -0,0 +1,270 @@ +"""Trained Gaussian processes, served as ``gp/`` models.""" + +from __future__ import annotations + +from collections.abc import Sequence +from functools import cached_property +from typing import Any, Literal, cast +from uuid import uuid4 + +from pydantic import TypeAdapter + +from openprotein.base import _IDEMPOTENCY_KEY_HEADER, APISession +from openprotein.data import AssayDataset, AssayMetadata +from openprotein.jobs import Job, _submission, futures +from openprotein.jobs import _api as _jobs_api +from openprotein.models.kernels import ( + TrainedKernel, + _GPHyperparameters, + _sole_hyperparameters, + _trained_kernel, +) + +from . import _api, _folds, _inputs +from .model import Model +from .schemas import ModelMetadata + +__all__ = ["GPModel"] + + +_FAMILY = "gp" + + +class GPModel(Model): + """A Gaussian process predictor trained on an assay. + + ``predict`` and ``single_site`` submit predictions; the other methods read + or start its cross-validation and read its training record. + """ + + @property + def spec(self) -> dict[str, Any] | None: + """The training configuration: features, kernel and dataset.""" + return self.metadata.spec + + def _path(self, *parts: str) -> str: + return "/".join([_api.fitted_path(_FAMILY, self.id), *parts]) + + def crossvalidate( + self, n_splits: int | None = None, folds: Sequence[int] | None = None + ) -> futures.CrossvalidateFuture: + """Cross-validate on the training assay. + + Parameters + ---------- + n_splits : int, optional + Number of random folds, between 2 and 10 (default 5). Keeps rows sharing a + sequence in the same fold. Mutually exclusive with ``folds``. + folds : sequence of int, optional + Test fold of each row of the training assay, one entry per row in assay + order, labelled 0..K-1 with none empty and 2 <= K <= 10. Rows are assigned + independently of which sequence they hold, unlike ``n_splits``. Use -1 to + exclude a row, which then comes back with a fold of -1 and NaN predictions. + Splitting a repeated sequence across folds leaks, since embeddings come + from the sequence, so expect optimistic scores. + + Returns + ------- + CrossvalidateFuture + Future whose ``get`` and ``wait`` return the run's `CrossvalidateResults`. + + Raises + ------ + InvalidParameterError + If both ``n_splits`` and ``folds`` are given, or if ``folds`` does not + have one valid entry per row of the training assay. + """ + _folds.check_exclusive(n_splits, folds) + if folds is not None: + assert self.spec is not None + assay = AssayDataset._for(self.session)( + id=self.spec["training_dataset"]["assay_id"] + ) + folds = _folds.validate_folds(folds, num_assay_rows=len(assay)) + body = { + key: value + for key, value in {"n_splits": n_splits, "folds": folds}.items() + if value is not None + } + response = _submission.post_with_retry( + self.session, + self._path("crossvalidate"), + json=body, + headers={_IDEMPOTENCY_KEY_HEADER: str(uuid4())}, + ) + job = _jobs_api.operation_job(self.session, response.json(), "id") + return futures.CrossvalidateFuture(self.session, Job.create(job), self) + + def single_site( + self, base_sequence: str | bytes, **params: Any + ) -> futures.SingleSitePredictionFuture: + """Predict properties for the sequence's single-site substitutions.""" + return cast( + futures.SingleSitePredictionFuture, + super().single_site(base_sequence, **params), + ) + + def evaluations(self, evaluation_id: str | None = None) -> Any: + """Every cross-validation run, newest first, or one run with its rows.""" + parts = ( + ["evaluations"] if evaluation_id is None else ["evaluations", evaluation_id] + ) + return self.session.get(self._path(*parts)).json() + + def training(self) -> list[dict[str, Any]]: + """The loss curves recorded while training, one per property.""" + return self.session.get(self._path("training")).json() + + @cached_property + def _hyperparameters(self) -> _GPHyperparameters: + served = self.session.get( + self._path("hyperparameters"), timeout=self.session.timeout + ).json() + return _sole_hyperparameters( + TypeAdapter(dict[str, _GPHyperparameters]).validate_python(served) + ) + + # IPython can evaluate this descriptor to complete the concrete kernel's fields. + @cached_property + def kernel(self) -> TrainedKernel: + """ + The trained kernel, in data space. + + The first access, including runtime tab completion, may make a request. + Failed reads are retried on subsequent access. + + Its class follows the kernel type and carries only the hyperparameters that + apply to it: every kernel has an ``outputscale``, every kernel but linear a + ``lengthscale``, periodic a ``period`` and rational quadratic an ``alpha``. + + Raises + ------ + HTTPError + 404 for a GP trained before hyperparameters were recorded. + + Examples + -------- + >>> trained.kernel + PeriodicKernel(outputscale=1.92, lengthscale=0.83, period=2.31) + >>> trained.kernel.lengthscale + 0.83 + """ + hyperparameters = self._hyperparameters + assert self.spec is not None + try: + return _trained_kernel(self.spec["kernel"]["type"], hyperparameters) + except ValueError: + self.__dict__.pop("_hyperparameters", None) + raise + + @property + def mean(self) -> float | None: + """ + Constant mean of the GP prior, in the units of the trained property. + + Raises + ------ + HTTPError + 404 for a GP trained before hyperparameters were recorded. + """ + return self._hyperparameters.mean + + @property + def noise(self) -> float | None: + """ + Observation noise variance, in the units of the trained property squared. + + Raises + ------ + HTTPError + 404 for a GP trained before hyperparameters were recorded. + """ + return self._hyperparameters.noise + + def delete(self) -> None: + """Delete this trained Gaussian process from the caller's model listing.""" + _api.delete_fitted(self.session, _FAMILY, self.id) + + +def _submit(session: APISession, request: dict[str, Any]) -> futures.GPFitFuture: + """Submit a training request; returns its fit future.""" + body = _api.create_fit(session, _FAMILY, request) + return futures.GPFitFuture( + session, Job.create(_jobs_api.operation_job(session, body, "id")) + ) + + +def _load(session: APISession, gp_id: str) -> GPModel: + """A trained GP by its id, bare or ``gp/``.""" + card = ModelMetadata.model_validate(_api.get_fitted(session, _FAMILY, gp_id)) + return GPModel(session, card.model_id, card) + + +def _page( + session: APISession, limit: int | None = None, offset: int | None = None +) -> list[GPModel]: + """The caller's GPs from every page, newest first.""" + cards = [ + ModelMetadata.model_validate(card) + for card in _api.list_fitted(session, _FAMILY, limit, offset) + ] + return [GPModel(session, card.model_id, card) for card in cards] + + +def _fit( + session: APISession, + model: str | Model, + assay: AssayDataset | AssayMetadata | str, + properties: list[str], + reduction: Literal["MEAN", "SUM"] | None = None, + *, + kernel: str = "rbf", + period: float | None = None, + alpha: float | None = None, + name: str | None = None, + description: str | None = None, + prompt_id: str | None = None, + query_id: str | None = None, + use_query_structure_in_decoder: bool | None = None, + decoder_type: str | None = None, +) -> futures.GPFitFuture: + """Train a Gaussian process on an assay's properties. + + ``model`` featurizes the sequences: a model id, a handle from + ``get_model`` or a fitted SVD. An embedding model needs ``reduction``. + ``prompt_id``, ``query_id``, ``use_query_structure_in_decoder`` and + ``decoder_type`` are its embedding params. ``period`` is for the + periodic kernel, ``alpha`` for rational_quadratic. + """ + feature_model = _inputs.model_id(model) + features: dict[str, Any] = {"model_id": feature_model} + for key, value in { + "reduction": reduction, + "prompt_id": prompt_id, + "query_id": query_id, + "use_query_structure_in_decoder": use_query_structure_in_decoder, + "decoder_type": decoder_type, + }.items(): + if value is not None: + features[key] = value + kernel_spec: dict[str, Any] = {"type": kernel} + if period is not None: + kernel_spec["period"] = period + if alpha is not None: + kernel_spec["alpha"] = alpha + request: dict[str, Any] = { + "features": features, + "kernel": kernel_spec, + "training_dataset": { + "assay_id": _inputs.assay_id(assay), + "properties": properties, + }, + } + if name is not None: + request["name"] = name + if description is not None: + request["description"] = description + future = _submit(session, request) + if isinstance(assay, (AssayDataset, AssayMetadata)): + future.dataset = _inputs.as_dataset(session, assay) + return future diff --git a/openprotein/models/kernels.py b/openprotein/models/kernels.py new file mode 100644 index 0000000..315d65b --- /dev/null +++ b/openprotein/models/kernels.py @@ -0,0 +1,159 @@ +"""Trained Gaussian process kernels, as fitted GPs report them.""" + +from typing import ClassVar + +from pydantic import BaseModel, ConfigDict + +__all__ = [ + "LinearKernel", + "Matern12Kernel", + "Matern32Kernel", + "Matern52Kernel", + "PeriodicKernel", + "RBFKernel", + "RationalQuadraticKernel", + "TrainedKernel", +] + + +class _GPHyperparameters(BaseModel): + """Trained hyperparameters of one property's GP, in data space, as the API serves + them. Kernel values are listed per subkernel. + """ + + mean: float | None = None + noise: float | None = None + lengthscale: list[float | None] = [] + outputscale: list[float | None] = [] + period: list[float | None] = [] + alpha: list[float | None] = [] + + +class TrainedKernel(BaseModel): + """A trained GP kernel, in data space. + + Each kernel type carries only the hyperparameters that apply to it. + + Attributes + ---------- + outputscale : float + Signal variance of the kernel. + """ + + model_config = ConfigDict(frozen=True) + + type: ClassVar[str] + outputscale: float + + +class LinearKernel(TrainedKernel): + """A trained linear kernel.""" + + type: ClassVar[str] = "linear" + + +class _StationaryKernel(TrainedKernel): + """A trained kernel over distances between embeddings. + + Attributes + ---------- + lengthscale : float + Distance in embedding space over which the kernel decays. + """ + + lengthscale: float + + +class RBFKernel(_StationaryKernel): + """A trained RBF kernel.""" + + type: ClassVar[str] = "rbf" + + +class Matern12Kernel(_StationaryKernel): + """A trained Matern 1/2 kernel.""" + + type: ClassVar[str] = "matern12" + + +class Matern32Kernel(_StationaryKernel): + """A trained Matern 3/2 kernel.""" + + type: ClassVar[str] = "matern32" + + +class Matern52Kernel(_StationaryKernel): + """A trained Matern 5/2 kernel.""" + + type: ClassVar[str] = "matern52" + + +class PeriodicKernel(_StationaryKernel): + """A trained periodic kernel. + + Attributes + ---------- + period : float + Period length, in embedding space. + """ + + type: ClassVar[str] = "periodic" + period: float + + +class RationalQuadraticKernel(_StationaryKernel): + """A trained rational quadratic kernel. + + Attributes + ---------- + alpha : float + Scale-mixture parameter. + """ + + type: ClassVar[str] = "rational_quadratic" + alpha: float + + +_TRAINED_KERNELS: dict[str, type[TrainedKernel]] = { + kernel.type: kernel + for kernel in ( + LinearKernel, + RBFKernel, + Matern12Kernel, + Matern32Kernel, + Matern52Kernel, + PeriodicKernel, + RationalQuadraticKernel, + ) +} + + +def _sole_hyperparameters( + by_property: dict[str, _GPHyperparameters], +) -> _GPHyperparameters: + """The hyperparameters of a GP trained on one property.""" + if len(by_property) != 1: + raise ValueError( + f"expected hyperparameters for one property, got {len(by_property)}" + ) + return next(iter(by_property.values())) + + +def _trained_kernel( + kernel_type: str, hyperparameters: _GPHyperparameters +) -> TrainedKernel: + """Build the trained kernel of ``kernel_type`` from its served hyperparameters.""" + kernel = _TRAINED_KERNELS.get(kernel_type.lower()) + if kernel is None: + raise ValueError(f"unknown kernel type {kernel_type!r}") + values = {} + for name in ("outputscale", "lengthscale", "period", "alpha"): + per_subkernel = getattr(hyperparameters, name) + applies = name in kernel.model_fields + if len(per_subkernel) > 1 or (applies and not per_subkernel): + raise ValueError( + f"expected one {kernel.type} kernel, got {len(per_subkernel)} {name} values" + ) + if applies: + values[name] = per_subkernel[0] + return kernel(**values) diff --git a/openprotein/models/model.py b/openprotein/models/model.py new file mode 100644 index 0000000..cc7608b --- /dev/null +++ b/openprotein/models/model.py @@ -0,0 +1,261 @@ +"""Model handles for the models API.""" + +from fnmatch import fnmatchcase +from typing import TYPE_CHECKING, Any, ClassVar, cast + +from openprotein.base import APISession +from openprotein.data.assaydataset import AssayDataset +from openprotein.jobs import _dispatch, futures +from openprotein.jobs.futures import ( + FitFuture, + Future, + _Submission, +) + +from . import _api, _inputs +from .schemas import MethodDescriptor, ModelMetadata + +if TYPE_CHECKING: + pass + +__all__ = ["Model"] + + +def _text(sequence: str | bytes, name: str = "sequence") -> str: + if isinstance(sequence, bytes): + try: + return sequence.decode() + except UnicodeDecodeError as exc: + raise ValueError(f"{name} is not valid UTF-8 text") from exc + return sequence + + +def _check_batch(sequences: Any) -> None: + """Refuse a bare ``str`` or ``bytes`` where a list of sequences is expected.""" + if isinstance(sequences, (str, bytes)): + raise TypeError( + f"sequences must be a list of sequences, not a {type(sequences).__name__}; " + 'pass a list of sequences, e.g. ["ACD"]' + ) + + +def _texts(sequences: list[str] | list[bytes]) -> list[str]: + """The batch as text, refusing a bare string or an entry that is not text.""" + _check_batch(sequences) + texts: list[str] = [] + for index, sequence in enumerate(sequences): + if not isinstance(sequence, (str, bytes)): + raise TypeError( + f"sequences[{index}] must be a str or bytes, " + f"not {type(sequence).__name__}" + ) + texts.append(_text(sequence, f"sequences[{index}]")) + return texts + + +def _prepared(sequences: Any) -> Any: + """``sequences`` with a batch of sequences as text; an assay or ``None`` is kept.""" + if sequences is None or isinstance(sequences, AssayDataset): + return sequences + return _texts(sequences) + + +#: The method a fitted SVD or UMAP serves, known before its fit has a card. +_PROJECTION = MethodDescriptor(path="batch/embeddings", outputs=["embeddings"]) + + +def _project( + fit: FitFuture, data: list[str] | list[bytes] | AssayDataset +) -> futures.EmbeddingFuture: + """Submit a projection of sequences, or an assay's, through ``fit``'s model. + + The projection is submitted now and runs once the fit has finished. + """ + sequences = ( + _inputs.assay_sequences(fit.session, data) + if isinstance(data, AssayDataset) + else _texts(data) + ) + params: dict[str, Any] = {"sequences": sequences} + model = f"{fit._family}/{fit.id}" + future = _dispatch.create( + fit.session, + _api.run_method(fit.session, model, _PROJECTION.path, params), + descriptor=_PROJECTION, + submission=_Submission(model, _PROJECTION.path, params), + ) + future.dataset = data if isinstance(data, AssayDataset) else None + return cast(futures.EmbeddingFuture, future) + + +class Model: + """A handle for submitting the methods listed on a model's card. + + Attributes + ---------- + id : str + The model identifier used to submit its methods. + """ + + #: whether ``batch/embeddings`` names an assay by ``assay_id`` + _embeds_assay_by_id: ClassVar[bool] = False + #: the checkpoint a handle built without ``model_id`` uses + _default_id: ClassVar[str | None] = None + + def __init__( + self, + session: APISession, + model_id: str | None = None, + metadata: ModelMetadata | None = None, + ): + if model_id is None: + if self._default_id is None: + raise TypeError(f"{type(self).__name__} needs a model_id") + model_id = self._default_id + self.session = session + self.id = model_id + self._metadata = metadata + self._schemas: dict[str, dict[str, Any]] = {} + + @property + def metadata(self) -> ModelMetadata: + """The model card, loaded on first access.""" + if self._metadata is None: + self._metadata = _api.get_model(self.session, self.id) + return self._metadata + + @property + def methods(self) -> list[MethodDescriptor]: + """The method descriptors listed on the model card.""" + return self.metadata.methods + + def _params_schema(self, path: str) -> dict[str, Any]: + """The JSON Schema of a method's params, read once per handle.""" + schema = self._schemas.get(path) + if schema is None: + schema = self._schemas[path] = _api.get_method_params( + self.session, self.id, path + ) + return schema + + def _method(self, verb: str, path: str) -> MethodDescriptor: + """The card's first method matching ``path``, which may be a glob. + + Raises when the card lists none, so a verb can check before converting + its inputs. + """ + method = next((m for m in self.methods if fnmatchcase(m.path, path)), None) + if method is None: + paths = ", ".join(m.path for m in self.methods) or "none" + raise ValueError(f"model {self.id!r} has no {verb}; its methods: {paths}") + return method + + def _run(self, verb: str, path: str, **params: Any) -> Future: + """Submit the card's first method matching ``path`` for ``verb``.""" + method = self._method(verb, path) + job = _api.run_method(self.session, self.id, method.path, params) + return _dispatch.create( + self.session, + job, + descriptor=method, + submission=_Submission(self.id, method.path, params), + ) + + def embed( + self, sequences: list[str] | list[bytes] | AssayDataset, **params: Any + ) -> futures.EmbeddingFuture: + """Embed sequences, or an assay's, which stays on the future as ``dataset``. + + Submits ``batch/embeddings``. + """ + if isinstance(sequences, AssayDataset) and self._embeds_assay_by_id: + future = self._run( + "embed", "batch/embeddings", assay_id=sequences.id, **params + ) + elif isinstance(sequences, AssayDataset): + texts = _inputs.assay_sequences(self.session, sequences) + future = self._run("embed", "batch/embeddings", sequences=texts, **params) + else: + future = self._run( + "embed", "batch/embeddings", sequences=_texts(sequences), **params + ) + future.dataset = sequences if isinstance(sequences, AssayDataset) else None + return cast(futures.EmbeddingFuture, future) + + def logits( + self, sequences: list[str] | list[bytes], **params: Any + ) -> futures.LogitsFuture: + """Per-residue logits for sequences (``batch/logits``).""" + return cast( + futures.LogitsFuture, + self._run("logits", "batch/logits", sequences=_texts(sequences), **params), + ) + + def attn( + self, sequences: list[str] | list[bytes], **params: Any + ) -> futures.AttentionFuture: + """Attention maps for sequences (``batch/attn``).""" + return cast( + futures.AttentionFuture, + self._run("attn", "batch/attn", sequences=_texts(sequences), **params), + ) + + def score( + self, sequences: list[str] | list[bytes], **params: Any + ) -> futures.LogLikelihoodFuture: + """Log-likelihoods of sequences (``batch/loglikelihood``).""" + return cast( + futures.LogLikelihoodFuture, + self._run( + "score", "batch/loglikelihood", sequences=_texts(sequences), **params + ), + ) + + def single_site( + self, base_sequence: str | bytes, **params: Any + ) -> futures.SingleSiteScoreFuture | futures.SingleSitePredictionFuture | Future: + """Every single-site mutant of ``base_sequence`` (``single-site/*``).""" + return self._run( + "single_site", "single-site/*", base_sequence=_text(base_sequence), **params + ) + + def indel( + self, base_sequence: str | bytes, **params: Any + ) -> futures.IndelScoreFuture: + """Every insertion or deletion variant of ``base_sequence`` (``indel/*``).""" + return cast( + futures.IndelScoreFuture, + self._run("indel", "indel/*", base_sequence=_text(base_sequence), **params), + ) + + def generate( + self, **params: Any + ) -> futures.SequenceGenerationFuture | futures.StructureDesignFuture | Future: + """Generate sequences or structures (``generate/*``).""" + return self._run("generate", "generate/*", **params) + + def fold( + self, complexes: list[Any], **params: Any + ) -> futures.StructurePredictionFuture: + """Predict structures of complexes (``batch/structures``).""" + return cast( + futures.StructurePredictionFuture, + self._run("fold", "batch/structures", complexes=complexes, **params), + ) + + def predict( + self, sequences: list[str] | list[bytes], **params: Any + ) -> futures.PredictionFuture: + """Predict properties of sequences (``batch/predictions``).""" + return cast( + futures.PredictionFuture, + self._run( + "predict", "batch/predictions", sequences=_texts(sequences), **params + ), + ) + + def __str__(self) -> str: + return self.id + + def __repr__(self) -> str: + return f"Model({self.id!r})" diff --git a/openprotein/models/models.py b/openprotein/models/models.py index a9d04dc..6ab8e97 100644 --- a/openprotein/models/models.py +++ b/openprotein/models/models.py @@ -1,42 +1,460 @@ -"""The ModelsAPI class, providing access to all protein models.""" +"""Models served through the models API.""" +from functools import cached_property +from typing import Any, TypeVar + +from openprotein import _deprecation from openprotein.base import APISession +from openprotein.errors import HTTPError + +from . import _api, estimators, gp, svd, umap +from .ensemble import AlphaFlow, BioEmu, ESMFlow +from .folding import ( + AlphaFold2, + Boltz1, + Boltz2, + ESMFold, + ESMFold2, + MiniFold, + OpenDDE, + Protenix, + ProtenixV2, + RosettaFold3, +) +from .foundational import ( + ESM1, + ESM2, + ESMC, + ESMIF1, + AbLang2, + PoET, + PoET2, + ProteinMPNN, + ProtSeq, + ProtT5, + RotaProt, +) +from .foundational.proteinmpnn import _SolubleMPNN +from .generative import BoltzGen, RFdiffusion +from .gp import GPModel +from .model import Model +from .schemas import ModelMetadata +from .svd import SVDModel +from .umap import UMAPModel + +__all__ = ["ModelsAPI"] + + +_H = TypeVar("_H", bound=Model) -from .foundation.boltzgen import BoltzGenModel -from .foundation.esmif1 import ESMIF1Model -from .foundation.proteinmpnn import ProteinMPNNModel -from .foundation.rfdiffusion import RFdiffusionModel -from .foundation.solublempnn import SolubleMPNNModel +_RENAMED = { + "BoltzGenModel": BoltzGen, + "ESMIF1Model": ESMIF1, + "ProteinMPNNModel": ProteinMPNN, + "RFdiffusionModel": RFdiffusion, +} -# In the future, we would import other models here: -# from .foundation.esm import ESMModel -# from .foundation.alphafold import AlphaFoldModel -# from .custom.gp import GaussianProcessModel + +def __getattr__(name: str) -> Any: + if name == "SolubleMPNNModel": + _deprecation.warn_deprecated( + "openprotein.models.models.SolubleMPNNModel", + "`session.models.solublempnn`", + since="0.18.0", + removed_in="0.19.0", + ) + return _SolubleMPNN + if name not in _RENAMED: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + new = _RENAMED[name] + _deprecation.warn_deprecated( + f"openprotein.models.models.{name}", + f"`openprotein.models.{new.__name__}`", + since="0.18.0", + removed_in="0.19.0", + ) + return new class ModelsAPI: - """ - API-like accessor that groups all available protein models. + """Discover models and access their handles through ``session.models``. - This class is attached to the main APISession and provides a single, - consistent entry point for accessing various models. + ``list_models`` lists available cards, and ``get_model`` loads a handle by + model identifier. Named properties provide handles for common models and + estimators for fitting SVD, UMAP and Gaussian process models. """ def __init__(self, session: APISession): + self.session = session + self._handles: dict[str, Model] = {} + + def _handle(self, model_id: str, handle: type[_H]) -> _H: + cached = self._handles.get(model_id) + if not isinstance(cached, handle): + cached = self._handles[model_id] = handle(self.session, model_id) + return cached + + @cached_property + def SVD(self) -> type[estimators.SVD]: + """An SVD to fit, a fitted one by ``id``, or ``list`` the caller's.""" + return estimators.SVD._bind(self.session) + + @cached_property + def UMAP(self) -> type[estimators.UMAP]: + """A UMAP to fit, a fitted one by ``id``, or ``list`` the caller's.""" + return estimators.UMAP._bind(self.session) + + @cached_property + def GP(self) -> type[estimators.GP]: + """A GP to train, a trained one by ``id``, or ``list`` the caller's.""" + return estimators.GP._bind(self.session) + + @property + def rfdiffusion(self) -> RFdiffusion: + """``rfdiffusion``.""" + return self._handle("rfdiffusion", RFdiffusion) + + @property + def proteinmpnn(self) -> ProteinMPNN: + """``proteinmpnn``.""" + return self._handle("proteinmpnn", ProteinMPNN) + + @property + def solublempnn(self) -> ProteinMPNN: + """``solublempnn``.""" + return self._handle("solublempnn", ProteinMPNN) + + @property + def boltzgen(self) -> BoltzGen: + """``boltzgen``.""" + return self._handle("boltzgen", BoltzGen) + + @property + def esmif1(self) -> ESMIF1: + """``esm-if1``.""" + return self._handle("esm-if1", ESMIF1) + + @property + def esm_if1(self) -> ESMIF1: + """``esm-if1``.""" + return self.esmif1 + + @property + def poet2(self) -> PoET2: + """``poet-2``.""" + return self._handle("poet-2", PoET2) + + @property + def poet_2(self) -> PoET2: + """``poet-2``.""" + return self.poet2 + + @property + def poet(self) -> PoET: + """``poet``.""" + return self._handle("poet", PoET) + + @property + def prot_seq(self) -> ProtSeq: + """``prot-seq``.""" + return self._handle("prot-seq", ProtSeq) + + @property + def rotaprot_large_uniref50w(self) -> RotaProt: + """``rotaprot-large-uniref50w``.""" + return self._handle("rotaprot-large-uniref50w", RotaProt) + + @property + def rotaprot_large_uniref90_ft(self) -> RotaProt: + """``rotaprot-large-uniref90-ft``.""" + return self._handle("rotaprot-large-uniref90-ft", RotaProt) + + @property + def ablang2(self) -> AbLang2: + """``ablang2``.""" + return self._handle("ablang2", AbLang2) + + @property + def esm1b_t33_650M_UR50S(self) -> ESM1: + """``esm1b_t33_650M_UR50S``.""" + return self._handle("esm1b_t33_650M_UR50S", ESM1) + + @property + def esm1b(self) -> ESM1: + """``esm1b_t33_650M_UR50S``.""" + return self.esm1b_t33_650M_UR50S + + @property + def esm1v_t33_650M_UR90S_1(self) -> ESM1: + """``esm1v_t33_650M_UR90S_1``.""" + return self._handle("esm1v_t33_650M_UR90S_1", ESM1) + + @property + def esm1v(self) -> ESM1: + """``esm1v_t33_650M_UR90S_1``.""" + return self.esm1v_t33_650M_UR90S_1 + + @property + def esm1v_t33_650M_UR90S_2(self) -> ESM1: + """``esm1v_t33_650M_UR90S_2``.""" + return self._handle("esm1v_t33_650M_UR90S_2", ESM1) + + @property + def esm1v_t33_650M_UR90S_3(self) -> ESM1: + """``esm1v_t33_650M_UR90S_3``.""" + return self._handle("esm1v_t33_650M_UR90S_3", ESM1) + + @property + def esm1v_t33_650M_UR90S_4(self) -> ESM1: + """``esm1v_t33_650M_UR90S_4``.""" + return self._handle("esm1v_t33_650M_UR90S_4", ESM1) + + @property + def esm1v_t33_650M_UR90S_5(self) -> ESM1: + """``esm1v_t33_650M_UR90S_5``.""" + return self._handle("esm1v_t33_650M_UR90S_5", ESM1) + + @property + def esm2_t12_35M_UR50D(self) -> ESM2: + """``esm2_t12_35M_UR50D``.""" + return self._handle("esm2_t12_35M_UR50D", ESM2) + + @property + def esm2_t30_150M_UR50D(self) -> ESM2: + """``esm2_t30_150M_UR50D``.""" + return self._handle("esm2_t30_150M_UR50D", ESM2) + + @property + def esm2_t33_650M_UR50D(self) -> ESM2: + """``esm2_t33_650M_UR50D``.""" + return self._handle("esm2_t33_650M_UR50D", ESM2) + + @property + def esm2(self) -> ESM2: + """``esm2_t33_650M_UR50D``.""" + return self.esm2_t33_650M_UR50D + + @property + def esm2_t36_3B_UR50D(self) -> ESM2: + """``esm2_t36_3B_UR50D``.""" + return self._handle("esm2_t36_3B_UR50D", ESM2) + + @property + def esm2_t6_8M_UR50D(self) -> ESM2: + """``esm2_t6_8M_UR50D``.""" + return self._handle("esm2_t6_8M_UR50D", ESM2) + + @property + def esmc_300m(self) -> ESMC: + """``esmc-300m``.""" + return self._handle("esmc-300m", ESMC) + + @property + def esmc_600m(self) -> ESMC: + """``esmc-600m``.""" + return self._handle("esmc-600m", ESMC) + + @property + def esmc_6b(self) -> ESMC: + """``esmc-6b``.""" + return self._handle("esmc-6b", ESMC) + + @property + def prott5_xl(self) -> ProtT5: + """``prott5-xl``.""" + return self._handle("prott5-xl", ProtT5) + + @property + def alphafold2(self) -> AlphaFold2: + """``alphafold2``.""" + return self._handle("alphafold2", AlphaFold2) + + @property + def af2(self) -> AlphaFold2: + """``alphafold2``.""" + return self.alphafold2 + + @property + def boltz_1(self) -> Boltz1: + """``boltz-1``.""" + return self._handle("boltz-1", Boltz1) + + @property + def boltz1(self) -> Boltz1: + """``boltz-1``.""" + return self.boltz_1 + + @property + def boltz_1x(self) -> Boltz1: + """``boltz-1x``.""" + return self._handle("boltz-1x", Boltz1) + + @property + def boltz1x(self) -> Boltz1: + """``boltz-1x``.""" + return self.boltz_1x + + @property + def boltz_2(self) -> Boltz2: + """``boltz-2``.""" + return self._handle("boltz-2", Boltz2) + + @property + def boltz2(self) -> Boltz2: + """``boltz-2``.""" + return self.boltz_2 + + @property + def esmfold(self) -> ESMFold: + """``esmfold``.""" + return self._handle("esmfold", ESMFold) + + @property + def esmfold2(self) -> ESMFold2: + """``esmfold2``.""" + return self._handle("esmfold2", ESMFold2) + + @property + def esmfold2_fast(self) -> ESMFold2: + """``esmfold2-fast``.""" + return self._handle("esmfold2-fast", ESMFold2) + + @property + def minifold(self) -> MiniFold: + """``minifold``.""" + return self._handle("minifold", MiniFold) + + @property + def opendde(self) -> OpenDDE: + """``opendde``.""" + return self._handle("opendde", OpenDDE) + + @property + def opendde_abag(self) -> OpenDDE: + """``opendde-abag``.""" + return self._handle("opendde-abag", OpenDDE) + + @property + def protenix(self) -> Protenix: + """``protenix``.""" + return self._handle("protenix", Protenix) + + @property + def protenix_v2(self) -> ProtenixV2: + """``protenix-v2``.""" + return self._handle("protenix-v2", ProtenixV2) + + @property + def rosettafold_3(self) -> RosettaFold3: + """``rosettafold-3``.""" + return self._handle("rosettafold-3", RosettaFold3) + + @property + def rf3(self) -> RosettaFold3: + """``rosettafold-3``.""" + return self.rosettafold_3 + + @property + def bioemu_v1_1(self) -> BioEmu: + """``bioemu-v1-1``.""" + return self._handle("bioemu-v1-1", BioEmu) + + @property + def bioemu(self) -> BioEmu: + """``bioemu-v1-1``.""" + return self.bioemu_v1_1 + + @property + def alphaflow_md_base_v1(self) -> AlphaFlow: + """``alphaflow-md-base-v1``.""" + return self._handle("alphaflow-md-base-v1", AlphaFlow) + + @property + def alphaflow(self) -> AlphaFlow: + """``alphaflow-md-base-v1``.""" + return self.alphaflow_md_base_v1 + + @property + def alphaflow_md_distilled_v1(self) -> AlphaFlow: + """``alphaflow-md-distilled-v1``.""" + return self._handle("alphaflow-md-distilled-v1", AlphaFlow) + + @property + def esmflow_md_base_v1(self) -> ESMFlow: + """``esmflow-md-base-v1``.""" + return self._handle("esmflow-md-base-v1", ESMFlow) + + @property + def esmflow(self) -> ESMFlow: + """``esmflow-md-base-v1``.""" + return self.esmflow_md_base_v1 + + @property + def esmflow_md_distilled_v1(self) -> ESMFlow: + """``esmflow-md-distilled-v1``.""" + return self._handle("esmflow-md-distilled-v1", ESMFlow) + + def list_models( + self, + verbose: bool = False, + *, + path: list[str] | None = None, + ) -> list[str] | list[ModelMetadata]: + """List the system models served by the models API. + + Parameters + ---------- + verbose : bool, optional + Return each model's metadata rather than its id. + path : list of str, optional + Keep models with a method whose path contains one of these values, + ignoring case. Method paths are listed in each model's + ``metadata.methods``, e.g. ``batch/embeddings`` or + ``generate/sequences``, so ``["embeddings"]`` keeps embedding + models and ``["generate"]`` keeps models that generate sequences + or structures. + + Returns + ------- + list of str or list of ModelMetadata + Model ids, or their metadata with ``verbose``. """ - Initializes the ModelsAPI and attaches instances of all available models. + return _api.list_models(self.session, verbose=verbose, path=path) + + def get_model(self, model_id: str) -> Model: + """Get a handle on a model by id. - Args: - session: The active APISession to be used by the models for API calls. + A model with an accessor, named as its id with ``-`` as ``_``, gets the + accessor's handle. Other ids get their family's handle by prefix, or a + plain ``Model``. + + Raises + ------ + ValueError + If no system model has the id. A fitted model's id is checked when + the handle is first used, since its fit may still be running. """ - self.rfdiffusion = RFdiffusionModel(session) - self.proteinmpnn = ProteinMPNNModel(session) - self.solublempnn = SolubleMPNNModel(session) - self.boltzgen = BoltzGenModel(session) - self.esmif1 = ESMIF1Model(session) - self.esm_if1 = self.esmif1 # alias mirroring the `esm-if1` model_id - - # To add new models, you would simply instantiate them here: - # self.esm = ESMModel(session) - # self.alphafold = AlphaFoldModel(session) - # self.gp = GaussianProcessModel(session) + if model_id.startswith(f"{umap._FAMILY}/"): + return UMAPModel(self.session, model_id) + if model_id.startswith(f"{gp._FAMILY}/"): + return GPModel(self.session, model_id) + if model_id.startswith(f"{svd._FAMILY}/"): + return SVDModel(self.session, model_id) + handle = self._accessor(model_id) or Model(self.session, model_id) + try: + _ = handle.metadata + except HTTPError as error: + if error.status_code != 404: + raise + raise ValueError( + f"model {model_id!r} not found; list_models() lists the " + "available models" + ) from error + return handle + + def _accessor(self, model_id: str) -> Model | None: + name = model_id.replace("-", "_") + if not isinstance(getattr(type(self), name, None), property): + return None + handle = getattr(self, name) + return handle if isinstance(handle, Model) and handle.id == model_id else None diff --git a/openprotein/models/schemas.py b/openprotein/models/schemas.py new file mode 100644 index 0000000..329d343 --- /dev/null +++ b/openprotein/models/schemas.py @@ -0,0 +1,178 @@ +"""Schemas for the models API. + +A model exposes methods addressed by a ``path`` under +``/api/v1/models/{model_id}/{path}``. Metadata carries the method list; each +method's request params are fetched separately as a JSON Schema. +""" + +from datetime import datetime +from typing import Any + +from pydantic import BaseModel, ConfigDict, Field, model_validator + +__all__ = [ + "MethodDescriptor", + "ModelDescription", + "ModelMetadata", +] + + +class ModelDescription(BaseModel): + """Human-facing description of a model. + + Attributes + ---------- + summary : str + Description of the model's capabilities. + citation_title : str or None + Title of the model's reference publication. + doi : str or None + DOI of the model's reference publication. + """ + + summary: str + citation_title: str | None = None + doi: str | None = None + + +class MethodDescriptor(BaseModel): + """A method supported by a model. + + Attributes + ---------- + path : str + The method's address under its model, such as ``batch/embeddings``. + outputs : list of str + Output names, with the method's default output first. + description : str or None + Description of the method's capabilities. + name : str or None + Display name of the method. + """ + + path: str = Field( + description="The method's address under its model, e.g. ``batch/embeddings``." + ) + outputs: list[str] = Field( + min_length=1, + description="Named outputs this method produces; the first is the default.", + ) + description: str | None = None + name: str | None = Field( + default=None, description="Human-readable method name, when the model has one." + ) + + @model_validator(mode="before") + @classmethod + def _wire_shape(cls, data: Any) -> Any: + """Accept an ``input``/``output`` pair as the path, and outputs keyed by name. + + Named outputs are ordered default first. + """ + if not isinstance(data, dict): + return data + if "path" not in data and "input" in data and "output" in data: + data = data | {"path": f"{data['input']}/{data['output']}"} + if not isinstance(data.get("outputs"), dict): + return data + names = list(data["outputs"]) + default = data.get("default_output") + if default in names: + names.remove(default) + names.insert(0, default) + return data | {"outputs": names} + + @property + def default_output(self) -> str: + """The output to fetch when the caller doesn't choose one.""" + return self.outputs[0] + + +class ModelMetadata(BaseModel): + """A model card and the methods it exposes. + + Attributes + ---------- + model_id : str + Identifier of the system model or fitted model. + type : str or None + Kind of fitted model, such as ``gp``, ``svd`` or ``umap``. + family_id : str or None + Model family identifier, such as ``esm``. + model : str or None + Label shared by the model's checkpoints. + name : str or None + Full display name of this model card. + variant : str or None + Label distinguishing this card within its model. + is_system : bool + Whether this is a system model. + base : bool + Whether this card represents its model in the model listing. + tags : list of str or None + Capability tags used to describe the model. + input_types : list of str or None + Input-category hints for model discovery; method schemas define inputs. + description : ModelDescription + Model summary and reference publication. + dimension : int + Representation dimension reported by the model. + query : str or None + Conditioning input type: ``sequence``, ``structure``, ``both`` or None. + multichain : bool or None + Whether the model supports multichain inputs, when specified. + methods : list of MethodDescriptor + Methods and named outputs available on this card. + max_sequence_length : int + Maximum sequence length reported by the model. + owner : str or None + Username of the fitted model's owner. + created_at : datetime or None + Creation time of a fitted model. + spec : dict of str to Any or None + Training configuration of a fitted model. + """ + + model_config = ConfigDict(protected_namespaces=()) + + model_id: str = Field( + description="The model's path under ``/models``: a system model's id, or " + "``{type}/{id}`` for a fitted model." + ) + type: str | None = Field( + default=None, description="Fitted model kind, ``gp``, ``svd`` or ``umap``." + ) + family_id: str | None = Field( + default=None, description="Broad model family, e.g. ``esm``." + ) + model: str | None = Field( + default=None, + description="Label shared by one model's checkpoints, e.g. ``ESM2``.", + ) + name: str | None = Field( + default=None, description="The model's full display name, e.g. ``ESM2 (650M)``." + ) + variant: str | None = Field( + default=None, + description="What tells this card apart within its ``model``, e.g. ``650M``.", + ) + is_system: bool = False + base: bool = Field( + default=False, + description="The card that stands for its model; a model's only card is " + "its base.", + ) + tags: list[str] | None = None + input_types: list[str] | None = None + description: ModelDescription + dimension: int + query: str | None = None + multichain: bool | None = None + methods: list[MethodDescriptor] + max_sequence_length: int + owner: str | None = None + created_at: datetime | None = None + spec: dict[str, Any] | None = Field( + default=None, + description="Training-time configuration of a fitted model, by its ``kind``.", + ) diff --git a/openprotein/models/structure_generation.py b/openprotein/models/structure_generation.py index f7aef76..dc0c87c 100644 --- a/openprotein/models/structure_generation.py +++ b/openprotein/models/structure_generation.py @@ -2,19 +2,38 @@ from typing import Iterator, Literal +from openprotein import _deprecation from openprotein.base import APISession from openprotein.jobs import Job, JobsAPI, MappedFuture from openprotein.molecules import Complex +__all__ = [ + "BoltzGenFuture", + "RFdiffusionFuture", + "StructureGenerationFuture", + "StructureGenerationJob", +] + class StructureGenerationJob(Job): - """Job schema for an RFdiffusion request.""" + """A compatibility structure-generation job. + + Attributes + ---------- + job_type : str + The ``/models/design`` job type read by ``StructureGenerationFuture``. + """ job_type: Literal["/models/design"] class StructureGenerationFuture(MappedFuture[int, Complex]): - """Future for handling structure-generation model results.""" + """ + Reader for compatibility design jobs with job type ``/models/design``. + + Results are ``Complex`` objects indexed by replicate. Generation methods on + ``session.models`` return ``StructureDesignFuture``. + """ job: StructureGenerationJob @@ -50,3 +69,45 @@ def stream(self, **kwargs) -> Iterator[Complex]: def _get(self, verbose: bool = False, **kwargs) -> list[Complex]: return [v for v in self.stream(**kwargs)] + + +class RFdiffusionFuture(StructureGenerationFuture): + """ + Alias for :class:`StructureGenerationFuture`. + + .. deprecated:: 0.18.0 + Submit designs with ``session.models.rfdiffusion.generate(...)``, + which returns :class:`openprotein.jobs.StructureDesignFuture`. + This alias reads compatibility design jobs. + """ + + def __init__(self, *args, **kwargs): + _deprecation.warn_deprecated( + "openprotein.models.RFdiffusionFuture", + "`session.models.rfdiffusion.generate(...)` " + "(returns `openprotein.jobs.StructureDesignFuture`)", + since="0.18.0", + removed_in="0.19.0", + ) + super().__init__(*args, **kwargs) + + +class BoltzGenFuture(StructureGenerationFuture): + """ + Alias for :class:`StructureGenerationFuture`. + + .. deprecated:: 0.18.0 + Submit designs with ``session.models.boltzgen.generate(...)``, + which returns :class:`openprotein.jobs.StructureDesignFuture`. + This alias reads compatibility design jobs. + """ + + def __init__(self, *args, **kwargs): + _deprecation.warn_deprecated( + "openprotein.models.BoltzGenFuture", + "`session.models.boltzgen.generate(...)` " + "(returns `openprotein.jobs.StructureDesignFuture`)", + since="0.18.0", + removed_in="0.19.0", + ) + super().__init__(*args, **kwargs) diff --git a/openprotein/models/svd.py b/openprotein/models/svd.py new file mode 100644 index 0000000..aa2062a --- /dev/null +++ b/openprotein/models/svd.py @@ -0,0 +1,256 @@ +"""SVDs, each served as an ``svd/`` model.""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Literal + +from pydantic import BaseModel + +from openprotein.base import APISession +from openprotein.data import AssayDataset, AssayMetadata +from openprotein.jobs import Job, futures +from openprotein.jobs import _api as _jobs_api + +from . import _api, _inputs +from .model import Model, _texts +from .schemas import ModelMetadata + +__all__ = ["SVDEmbeddingSource", "SVDModel"] + + +_FAMILY = "svd" + + +class SVDEmbeddingSource(BaseModel): + """The embedding method reused for an SVD's projections. + + Attributes + ---------- + model_id : str or None + Model used to embed the fit's sequences. + version : str or None + Version of that embedding method. + reduction : str or None + Reduction applied to each sequence's embeddings. + prompt_id : str or None + Prompt used to condition the embedding method. + """ + + model_id: str | None = None + version: str | None = None + reduction: str | None = None + prompt_id: str | None = None + + +class _SVDRecord(BaseModel): + """The fitted SVD description on its model card. + + Attributes + ---------- + id : str + Identifier of the fitted SVD. + owner : str or None + Owner identifier of the fitted model. + requested_n_components : int or None + Component count requested for the fit. + n_components : int or None + Component count of the fitted projection. + embedding : SVDEmbeddingSource or None + Embedding method used for fitting and projection. + name : str or None + Display name of the fitted model. + description : str or None + Description of the fitted model. + created_at : datetime or None + Creation time of the fitted model. + """ + + id: str + owner: str | None = None + requested_n_components: int | None = None + n_components: int | None = None + embedding: SVDEmbeddingSource | None = None + name: str | None = None + description: str | None = None + created_at: datetime | None = None + + +def _record(card: dict[str, Any]) -> _SVDRecord: + return _SVDRecord.model_validate(card["svd"]) + + +def _get(session: APISession, svd_id: str) -> _SVDRecord: + """The live SVD's record; raises a 404 unless the SVD is live.""" + return _record(_api.get_fitted(session, _FAMILY, svd_id)) + + +class SVDModel(Model): + """A fitted SVD for projecting sequences through ``transform`` or ``embed``. + + Its fit configuration is read from the model card on first use. + """ + + def __init__( + self, + session: APISession, + model_id: str, + metadata: ModelMetadata | None = None, + ): + bare = _api.bare_id(_FAMILY, model_id) + super().__init__(session, f"{_FAMILY}/{bare}", metadata) + self._record: _SVDRecord | None = None + + @classmethod + def _from_record(cls, session: APISession, record: _SVDRecord | dict) -> SVDModel: + parsed = ( + _SVDRecord.model_validate(record) if isinstance(record, dict) else record + ) + model = cls(session, parsed.id) + model._record = parsed + return model + + @property + def _svd_record(self) -> _SVDRecord: + if self._record is None: + self._record = _get(self.session, self.id) + return self._record + + @property + def embedding(self) -> SVDEmbeddingSource | None: + """The embedding source reused when projecting new sequences.""" + return self._svd_record.embedding + + @property + def requested_n_components(self) -> int | None: + """The requested component count; ``n_components`` is the fitted count.""" + return self._svd_record.requested_n_components + + @property + def n_components(self) -> int | None: + """Rank of the fitted basis.""" + return self._svd_record.n_components + + def transform( + self, data: list[str] | list[bytes] | AssayDataset + ) -> futures.EmbeddingFuture: + """Project sequences, or an assay's, through this basis.""" + return self.embed(data) + + def fit_umap( + self, + sequences: list[str] | list[bytes] | None = None, + assay: AssayDataset | AssayMetadata | str | None = None, + n_components: int | None = None, + n_neighbors: int | None = None, + min_dist: float | None = None, + ) -> futures.UMAPFitFuture: + """Fit a UMAP on this SVD's projections of ``sequences`` or an assay's.""" + from .umap import _fit + + return _fit( + self.session, + self, + sequences=None if sequences is None else _texts(sequences), + assay=assay, + n_components=n_components, + n_neighbors=n_neighbors, + min_dist=min_dist, + ) + + def fit_gp( + self, + assay: AssayDataset | AssayMetadata | str, + properties: list[str], + name: str | None = None, + description: str | None = None, + kernel: str = "rbf", + period: float | None = None, + alpha: float | None = None, + ) -> futures.GPFitFuture: + """Train a Gaussian process on an assay's properties, featurized by this SVD.""" + from .gp import _fit + + return _fit( + self.session, + self, + assay=assay, + properties=properties, + name=name, + description=description, + kernel=kernel, + period=period, + alpha=alpha, + ) + + def delete(self) -> None: + """Delete this fitted SVD from the caller's model listing.""" + _api.delete_fitted(self.session, _FAMILY, self.id) + + +def _submit(session: APISession, request: dict[str, Any]) -> futures.SVDFitFuture: + """Submit a fit request; returns its fit future.""" + body = _api.create_fit(session, _FAMILY, request) + return futures.SVDFitFuture( + session, Job.create(_jobs_api.operation_job(session, body, "id")) + ) + + +def _load(session: APISession, svd_id: str) -> SVDModel: + """A fitted SVD by its id, bare or ``svd/``; raises a 404 unless it is live.""" + return SVDModel._from_record(session, _get(session, svd_id)) + + +def _page( + session: APISession, limit: int | None = None, offset: int | None = None +) -> list[SVDModel]: + """The caller's fitted SVDs from every page, newest first.""" + cards = _api.list_fitted(session, _FAMILY, limit, offset) + return [ + SVDModel._from_record(session, _record(card)) + for card in cards + if card.get("svd") is not None + ] + + +def _fit( + session: APISession, + model: str | Model, + sequences: list[str] | None = None, + assay: AssayDataset | AssayMetadata | str | None = None, + n_components: int | None = None, + reduction: Literal["MEAN", "SUM"] | None = None, + *, + prompt_id: str | None = None, + query_id: str | None = None, + use_query_structure_in_decoder: bool | None = None, + decoder_type: str | None = None, + seed: int | None = None, +) -> futures.SVDFitFuture: + """Fit an SVD on ``model``'s embeddings of ``sequences`` or an ``assay``'s. + + ``model`` is a model id or a handle from ``get_model``. ``prompt_id``, + ``query_id``, ``use_query_structure_in_decoder`` and ``decoder_type`` are + its embedding params. + """ + request: dict[str, Any] = { + "model_id": _inputs.model_id(model), + "output": "embeddings", + } + for key, value in { + "n_components": n_components, + "sequences": sequences, + "assay_id": None if assay is None else _inputs.assay_id(assay), + "prompt_id": prompt_id, + "reduction": reduction, + "query_id": query_id, + "use_query_structure_in_decoder": use_query_structure_in_decoder, + "decoder_type": decoder_type, + "seed": seed, + }.items(): + if value is not None: + request[key] = value + future = _submit(session, request) + if isinstance(assay, (AssayDataset, AssayMetadata)): + future.dataset = _inputs.as_dataset(session, assay) + return future diff --git a/openprotein/models/umap.py b/openprotein/models/umap.py new file mode 100644 index 0000000..f07e376 --- /dev/null +++ b/openprotein/models/umap.py @@ -0,0 +1,118 @@ +"""Fitted UMAPs, each served as a ``umap/`` model.""" + +from __future__ import annotations + +from typing import Any, Literal + +from openprotein.base import APISession +from openprotein.data import AssayDataset, AssayMetadata +from openprotein.jobs import Job, futures +from openprotein.jobs import _api as _jobs_api + +from . import _api, _inputs +from .model import Model +from .schemas import ModelMetadata + +__all__ = ["UMAPModel"] + + +_FAMILY = "umap" + + +class UMAPModel(Model): + """A fitted UMAP; ``embed`` projects new sequences. + + Its id is its fit job's, so ``session.jobs.get`` on the bare id reads the + fit set's ``sequences`` and ``embeddings``. + """ + + @property + def spec(self) -> dict[str, Any] | None: + """The fit's configuration: features, components, neighbors, distance.""" + return self.metadata.spec + + def delete(self) -> None: + """Delete this fitted UMAP from the caller's model listing.""" + _api.delete_fitted(self.session, _FAMILY, self.id) + + def transform( + self, data: list[str] | list[bytes] | AssayDataset + ) -> futures.EmbeddingFuture: + """Map sequences, or an assay's, through this UMAP.""" + return self.embed(data) + + +def _submit(session: APISession, request: dict[str, Any]) -> futures.UMAPFitFuture: + """Submit a fit request; returns its fit future.""" + body = _api.create_fit(session, _FAMILY, request) + return futures.UMAPFitFuture( + session, Job.create(_jobs_api.operation_job(session, body, "id")) + ) + + +def _load(session: APISession, umap_id: str) -> UMAPModel: + """A fitted UMAP by its id, bare or ``umap/``.""" + card = ModelMetadata.model_validate(_api.get_fitted(session, _FAMILY, umap_id)) + return UMAPModel(session, card.model_id, card) + + +def _page( + session: APISession, limit: int | None = None, offset: int | None = None +) -> list[UMAPModel]: + """The caller's fitted UMAPs from every page, newest first.""" + cards = [ + ModelMetadata.model_validate(card) + for card in _api.list_fitted(session, _FAMILY, limit, offset) + ] + return [UMAPModel(session, card.model_id, card) for card in cards] + + +def _fit( + session: APISession, + model: str | Model, + sequences: list[str] | None = None, + assay: AssayDataset | AssayMetadata | str | None = None, + n_components: int | None = None, + reduction: Literal["MEAN", "SUM"] | None = None, + n_neighbors: int | None = None, + min_dist: float | None = None, + *, + prompt_id: str | None = None, + query_id: str | None = None, + use_query_structure_in_decoder: bool | None = None, + decoder_type: str | None = None, +) -> futures.UMAPFitFuture: + """Fit a UMAP on ``model``'s features of ``sequences`` or an assay's. + + ``model`` is a model id, a handle from ``get_model`` or a fitted SVD. + An embedding model needs ``reduction``. ``prompt_id``, ``query_id``, + ``use_query_structure_in_decoder`` and ``decoder_type`` are its + embedding params. + """ + features = _inputs.model_id(model) + _inputs.check_fit_source(sequences, assay) + dataset = None + if assay is not None: + dataset = _inputs.as_dataset(session, assay) + sequences = _inputs.assay_sequences(session, dataset) + request: dict[str, Any] = { + "model_id": features, + "sequences": sequences, + } + for key, value in { + "n_components": n_components, + "n_neighbors": n_neighbors, + "min_dist": min_dist, + "prompt_id": prompt_id, + "reduction": reduction, + "query_id": query_id, + "use_query_structure_in_decoder": use_query_structure_in_decoder, + "decoder_type": decoder_type, + }.items(): + if value is not None: + request[key] = value + future = _submit(session, request) + # the request carries the assay's sequences, not its id, so the job can't name it + if dataset is not None: + future.dataset = dataset + return future diff --git a/openprotein/molecules/__init__.py b/openprotein/molecules/__init__.py index 0da5eb8..1e963cf 100644 --- a/openprotein/molecules/__init__.py +++ b/openprotein/molecules/__init__.py @@ -3,3 +3,14 @@ from .protein import Binding, Protein from .structure import Structure from .template import Template + +__all__ = [ + "DNA", + "RNA", + "Binding", + "Complex", + "Ligand", + "Protein", + "Structure", + "Template", +] diff --git a/openprotein/molecules/chains.py b/openprotein/molecules/chains.py index ae0364d..0c817ba 100644 --- a/openprotein/molecules/chains.py +++ b/openprotein/molecules/chains.py @@ -5,18 +5,20 @@ import gemmi -import openprotein.utils.cif as _cif_utils +import openprotein.utils.cif as cif_utils from .protein import ( _extract_full_sequence_from_residues, _extract_one_letter_from_full_sequence, ) +__all__ = ["DNA", "RNA", "Ligand"] + class _BasicSerde(Protocol): _GEMMI_ENTITY_TYPE: ClassVar[gemmi.EntityType] _GEMMI_POLYMER_TYPE: ClassVar[gemmi.PolymerType] - _structure_block: _cif_utils.StructureCIFBlock | None + _structure_block: cif_utils.StructureCIFBlock | None def _make_structure( self, @@ -25,24 +27,21 @@ def _make_structure( chain_id: str = "A", entity_name: str = "1", ) -> gemmi.Structure: - assert ( - self._structure_block is not None - ), "only chains constructed directly from a structure file can be serialized for now" - assert ( - self._structure_block.structure.input_format == gemmi.CoorFormat.Mmcif - ), "only chains that were deserialized from cif can be serialized for now" + assert self._structure_block is not None, ( + "only chains constructed directly from a structure file can be serialized for now" + ) + assert self._structure_block.structure.input_format == gemmi.CoorFormat.Mmcif, ( + "only chains that were deserialized from cif can be serialized for now" + ) # Create an empty structure and add a model with a default chain. if structure is None: structure = gemmi.Structure() - # Get existing model or create new one if len(structure) > 0: model = structure[model_idx] else: - model = structure.add_model(gemmi.Model(str(model_idx))) # type: ignore - gemmi 0.6 needs str - # Get existing chain + model = structure.add_model(gemmi.Model(str(model_idx + 1))) # type: ignore - gemmi 0.6 needs str subchain = self._structure_block.structure[model_idx].get_subchain(chain_id) assert len(subchain) > 0 - # Create entity if self._GEMMI_ENTITY_TYPE == gemmi.EntityType.Polymer: entity = gemmi.Entity(entity_name) entity.name = entity_name @@ -72,7 +71,6 @@ def _make_structure( pass else: raise ValueError("more matching entities found than expected") - # Create chain chain = model.add_chain(gemmi.Chain(chain_id)) chain.append_residues(list(subchain.first_conformer())) return structure @@ -97,7 +95,7 @@ class DNA(_BasicSerde): _GEMMI_ENTITY_TYPE: ClassVar[gemmi.EntityType] = gemmi.EntityType.Polymer _GEMMI_POLYMER_TYPE: ClassVar[gemmi.PolymerType] = gemmi.PolymerType.Dna - _structure_block: _cif_utils.StructureCIFBlock | None = None + _structure_block: cif_utils.StructureCIFBlock | None = None def __post_init__(self): if not all(nt in set("ACGT") for nt in self.sequence.upper()): @@ -113,17 +111,15 @@ def copy(self) -> "DNA": @staticmethod def _from_structure_block( - structure_block: _cif_utils.StructureCIFBlock, chain_id: str, model_idx: int + structure_block: cif_utils.StructureCIFBlock, chain_id: str, model_idx: int ) -> "DNA": assert structure_block.structure.input_format == gemmi.CoorFormat.Mmcif structure = structure_block.structure model = structure[model_idx] polymer = model.get_subchain(chain_id) assert len(polymer) > 0 - # extract sequence entity = structure.get_entity_of(polymer) residues = list(polymer.first_conformer()) - # TODO: consider utilizing polymer.make_one_letter_sequence() here or elsewhere del polymer if len(entity.full_sequence) > 0: chain_seq = entity.full_sequence @@ -149,7 +145,7 @@ class RNA(_BasicSerde): _GEMMI_ENTITY_TYPE: ClassVar[gemmi.EntityType] = gemmi.EntityType.Polymer _GEMMI_POLYMER_TYPE: ClassVar[gemmi.PolymerType] = gemmi.PolymerType.Rna - _structure_block: _cif_utils.StructureCIFBlock | None = None + _structure_block: cif_utils.StructureCIFBlock | None = None def __post_init__(self): if not all(nt in set("ACGU") for nt in self.sequence.upper()): @@ -165,17 +161,15 @@ def copy(self) -> "RNA": @staticmethod def _from_structure_block( - structure_block: _cif_utils.StructureCIFBlock, chain_id: str, model_idx: int + structure_block: cif_utils.StructureCIFBlock, chain_id: str, model_idx: int ) -> "RNA": assert structure_block.structure.input_format == gemmi.CoorFormat.Mmcif structure = structure_block.structure model = structure[model_idx] polymer = model.get_subchain(chain_id) assert len(polymer) > 0 - # extract sequence entity = structure.get_entity_of(polymer) residues = list(polymer.first_conformer()) - # TODO: consider utilizing polymer.make_one_letter_sequence() here or elsewhere del polymer if len(entity.full_sequence) > 0: chain_seq = entity.full_sequence @@ -204,7 +198,7 @@ class Ligand(_BasicSerde): _GEMMI_ENTITY_TYPE: ClassVar[gemmi.EntityType] = gemmi.EntityType.NonPolymer _GEMMI_POLYMER_TYPE: ClassVar[gemmi.PolymerType] = gemmi.PolymerType.Unknown - _structure_block: _cif_utils.StructureCIFBlock | None = None + _structure_block: cif_utils.StructureCIFBlock | None = None def __post_init__(self): if (self.ccd is None and self.smiles is None) or ( @@ -214,12 +208,12 @@ def __post_init__(self): def copy(self) -> "Ligand": return replace(self) - + # TODO - support (&) and (|) operators for combining into Complexes (like Protein) @staticmethod def _from_structure_block( - structure_block: _cif_utils.StructureCIFBlock, chain_id: str, model_idx: int + structure_block: cif_utils.StructureCIFBlock, chain_id: str, model_idx: int ) -> "Ligand": assert structure_block.structure.input_format == gemmi.CoorFormat.Mmcif subchain = structure_block.structure[model_idx].get_subchain(chain_id) diff --git a/openprotein/molecules/complex.py b/openprotein/molecules/complex.py index 8ebcd85..bbaca15 100644 --- a/openprotein/molecules/complex.py +++ b/openprotein/molecules/complex.py @@ -1,6 +1,6 @@ import gzip import operator -from collections.abc import Mapping, Sequence, MutableMapping +from collections.abc import Mapping, MutableMapping, Sequence from functools import reduce from pathlib import Path from types import MappingProxyType @@ -10,8 +10,8 @@ import numpy as np import numpy.typing as npt -import openprotein.utils.chain_id as _chain_id_utils -import openprotein.utils.cif as _cif_utils +import openprotein.utils.chain_id as chain_id_utils +import openprotein.utils.cif as cif_utils from .chains import DNA, RNA, Ligand from .protein import Protein @@ -19,14 +19,16 @@ if TYPE_CHECKING: from .template import Template +__all__ = ["Chain", "Complex"] + Chain = Protein | DNA | RNA | Ligand | str + def _is_chain_type(chain): return isinstance(chain, Chain) -# TODO: deserialization note about plddt parsed per residue class Complex(MutableMapping): def __init__( self, @@ -39,14 +41,11 @@ def __init__( if not isinstance(key, str): raise TypeError(f"chain id must be str; got {key!r}") collected[key] = value - # preserve insertion order of the chains by not sorting the dictionary - # Note that as of python 3.7 dicts preserve insertion order (OrderedDict not needed) + # preserve insertion order of the chains self._chains = collected self._templates: "Sequence[Protein | Complex | Template]" = () self.name = name - # --- NAME methods --- - @property def name(self) -> str | None: return self._name @@ -62,8 +61,6 @@ def set_name(self, x: bytes | str | None) -> "Complex": self.name = x return self - # --- TEMPLATE methods --- - @property def templates(self) -> "Sequence[Protein | Complex | Template]": """A list of templates for guiding the structure prediction of this molecular complex.""" @@ -82,8 +79,6 @@ def set_templates( self.templates = templates return self - # --- dict-like methods and other general ops --- - def get_chain_ids(self): """Returns the Chain IDs in this Complex""" return self._chains.keys() @@ -95,7 +90,7 @@ def get_chains(self) -> Mapping[str, Protein | DNA | RNA | Ligand]: def get_chain(self, chain_id: str): """Get the chain for this chain_id""" return self._chains[chain_id] - + def set_chain( self, chain_id: str, value: Protein | DNA | RNA | Ligand ) -> "Complex": @@ -110,7 +105,7 @@ def remove_chain(self, chain_id: str): def insert_chain(self, chain: Protein | DNA | RNA | Ligand | str): """Inserts a new chain into this Complex with an auto-generated chain_id. Casts strings into Proteins.""" assert _is_chain_type(chain) - id_gen = _chain_id_utils.id_generator(list(self._chains.keys())) + id_gen = chain_id_utils.id_generator(list(self._chains.keys())) if isinstance(chain, str): chain = Protein.from_expr(chain) @@ -166,7 +161,6 @@ def update(self, **kwargs): if not isinstance(key, str): raise TypeError(f"chain id must be str; got {key!r}") # TODO - assert that chain objects are the right types too - # assert _is_chain_type(value) # strictly do not allow replacing existing chain_ids if key in self._chains: @@ -175,8 +169,7 @@ def update(self, **kwargs): raise ValueError( f"Trying to combine two sets of chains with overlapping chain ids: {overlapping_chain_ids}" ) - - # update chains + self._chains.update(**kwargs) def clear(self): @@ -187,17 +180,14 @@ def clear(self): def copy(self) -> "Complex": """Copy this Complex. Returns a deep copy of the contained Chains""" - # TODO - should this deepcopy the chain objects themselves? chains_copy: dict[str, Protein | DNA | RNA | Ligand] = { chain_id: chain.copy() for chain_id, chain in self._chains.items() } return Complex(chains=chains_copy, name=self._name) - # --- other dictionary operators like set combine --- - # python actually uses the or operator for dict combine def __ior__(self, other) -> "Complex": - """In-place update to this Complex using |= """ + """In-place update to this Complex using |=""" # other is either a single Chain or a Complex # if single chain, we insert it with an autogenerated ID @@ -211,7 +201,7 @@ def __ior__(self, other) -> "Complex": def __or__(self, right) -> "Complex": """Create a combined copy: self | right""" a = self.copy() - a |= right # handles right being Complex or single Chain + a |= right return a def __ror__(self, left) -> "Complex": @@ -224,8 +214,6 @@ def __ror__(self, left) -> "Complex": __rand__ = __ror__ __and__ = __or__ - # -- Chain-type specific methods --- - def get_proteins(self) -> Mapping[str, Protein]: return MappingProxyType( {k: v for k, v in self._chains.items() if isinstance(v, Protein)} @@ -266,8 +254,6 @@ def get_ligand(self, chain_id: str) -> Ligand: assert isinstance(chain, Ligand) return chain - # --- structure comparison and geometry methods --- - @overload def rmsd( self, @@ -290,12 +276,12 @@ def rmsd( backbone_only: bool | str | Sequence[str] = False, return_transform: bool = False, ) -> float | tuple[float, npt.NDArray[np.floating], npt.NDArray[np.floating]]: - assert all( - isinstance(v, Protein) for v in self._chains.values() - ), "rmsd supported only for Protein chains, not supported for non-protein chains" - assert all( - isinstance(v, Protein) for v in tgt._chains.values() - ), "rmsd supported only for Protein chains, not supported for non-protein chains" + assert all(isinstance(v, Protein) for v in self._chains.values()), ( + "rmsd supported only for Protein chains, not supported for non-protein chains" + ) + assert all(isinstance(v, Protein) for v in tgt._chains.values()), ( + "rmsd supported only for Protein chains, not supported for non-protein chains" + ) src_proteins, tgt_proteins = self.get_proteins(), tgt.get_proteins() assert tgt_proteins.keys() == src_proteins.keys() assert [len(x) for x in src_proteins.values()] == [ @@ -314,9 +300,9 @@ def transform( R: npt.NDArray[np.floating] | None = None, t: npt.NDArray[np.floating] | None = None, ) -> "Complex": - assert all( - isinstance(v, Protein) for v in self._chains.values() - ), "transform supported only for Protein chains, not supported for non-protein chains" + assert all(isinstance(v, Protein) for v in self._chains.values()), ( + "transform supported only for Protein chains, not supported for non-protein chains" + ) for protein in self.get_proteins().values(): protein.transform(R=R, t=t) return self @@ -327,8 +313,6 @@ def superimpose_onto( _, R, t = tgt.rmsd(self, backbone_only=backbone_only, return_transform=True) return self.transform(R=R, t=t) - # --- read and write PDB and CIF files and strings --- - def to_string(self, format: Literal["cif", "pdb"] = "cif") -> str: """ Serialize this Complex to a string. Note that format="pdb" may not serialize all @@ -379,7 +363,7 @@ def from_string( model_idx: int = 0, verbose: bool = True, ) -> "Complex": - structure_block = _cif_utils.StructureCIFBlock( + structure_block = cif_utils.StructureCIFBlock( filestring=filestring, format=format ) return Complex._from_structure_block( @@ -406,7 +390,7 @@ def _assert_valid_templates(self): @staticmethod def _from_structure_block( - structure_block: _cif_utils.StructureCIFBlock, + structure_block: cif_utils.StructureCIFBlock, use_bfactor_as_plddt: bool | None = None, model_idx: int = 0, verbose: bool = True, @@ -418,7 +402,6 @@ def _from_structure_block( if len(subchain_ids) == 0 and model is not None: # Try to get actual chain IDs from the structure subchain_ids = [subchain.subchain_id() for subchain in model.subchains()] - # collect chains chains = {} for subchain_id in sorted(subchain_ids): subchain = model.get_subchain(subchain_id) if model is not None else None @@ -469,18 +452,14 @@ def _from_structure_block( model_idx=model_idx, ) else: - # if verbose: - # print( - # f"Warning: Skipping unsupported polymer type {polymer_type} for chain {subchain_id}" - # ) continue elif entity_type == gemmi.EntityType.NonPolymer: if structure.input_format == gemmi.CoorFormat.Pdb: raise ValueError("ligands from pdb files not supported yet") chain_id = subchain_id - assert ( - structure.input_format != gemmi.CoorFormat.Pdb - ), "ligands from pdb files not supported yet" + assert structure.input_format != gemmi.CoorFormat.Pdb, ( + "ligands from pdb files not supported yet" + ) chains[chain_id] = Ligand._from_structure_block( structure_block=structure_block, chain_id=subchain_id, @@ -489,10 +468,6 @@ def _from_structure_block( elif entity_type == gemmi.EntityType.Water: continue else: - # if verbose: - # print( - # f"Warning: Skipping unsupported entity type {entity_type} for chain {subchain_id}" - # ) continue return Complex(chains=chains, name=structure.name) @@ -501,7 +476,7 @@ def _make_cif_string(self) -> str: block = structure.make_mmcif_block( groups=gemmi.MmcifOutputGroups(True, chem_comp=False) ) - sequence_loop, atom_loop = _cif_utils.init_loops(block=block) + sequence_loop, atom_loop = cif_utils.init_loops(block=block) for chain_id, chain in self._chains.items(): chain._append_loop_data( chain_id=chain_id, sequence_loop=sequence_loop, atom_loop=atom_loop @@ -513,9 +488,9 @@ def _make_pdb_string(self) -> str: return structure.make_pdb_string(gemmi.PdbWriteOptions(minimal=True)) def _make_structure(self) -> gemmi.Structure: - assert ( - len(set(x._structure_block for x in self.get_ligands().values())) <= 1 - ), "can only serialize ligands if they all originate from the same structure file" + assert len(set(x._structure_block for x in self.get_ligands().values())) <= 1, ( + "can only serialize ligands if they all originate from the same structure file" + ) structure = gemmi.Structure() for chain_id, chain in self._chains.items(): structure = chain._make_structure( diff --git a/openprotein/molecules/protein.py b/openprotein/molecules/protein.py index 21e28d0..b47361a 100644 --- a/openprotein/molecules/protein.py +++ b/openprotein/molecules/protein.py @@ -10,18 +10,22 @@ import numpy as np import numpy.typing as npt -import openprotein.utils.chain_id as _chain_id_utils -import openprotein.utils.cif as _cif_utils -import openprotein.utils.numpy as _numpy_utils -import openprotein.utils.sequence as _sequence_utils +import openprotein.utils.chain_id as chain_id_utils +import openprotein.utils.cif as cif_utils +import openprotein.utils.numpy as numpy_utils +import openprotein.utils.sequence as sequence_utils from .. import fasta if TYPE_CHECKING: from ..align.msa import MSAFuture + from ..data.msa import MSA from .complex import Complex from .template import Template +__all__ = ["Binding", "Protein", "StrEnum", "T", "V", "parse_fasta_as_proteins"] + + V = TypeVar("V") @@ -30,13 +34,11 @@ class StrEnum(str, enum.Enum): ... @enum.unique class Binding(StrEnum): - # TODO: should we use any/X/?/* or something else instead of unknown? UNKNOWN = "U" BINDING = "B" NOT_BINDING = "N" -# TODO: deserialization note about plddt parsed per residue class Protein: """ Represents a protein with an optional name. @@ -63,14 +65,14 @@ class Protein: def __init__(self, sequence: bytes | str, name: bytes | str | None = None): assert set( sequence if isinstance(sequence, str) else sequence.decode() - ).issubset( - set(_sequence_utils.AMINO_ACIDS + _sequence_utils.EXTRA_TOKENS) - ), "Expected only amino acids or the mask token 'X' or the variable length token '?'\nHint: Use Protein.from_expr if using a sequence expression" + ).issubset(set(sequence_utils.AMINO_ACIDS + sequence_utils.EXTRA_TOKENS)), ( + "Expected only amino acids or the mask token 'X' or the variable length token '?'\nHint: Use Protein.from_expr if using a sequence expression" + ) self._sequence = sequence.encode() if isinstance(sequence, str) else sequence self.name = name # sequence-level properties self._cyclic: bool = False - self._msa: "str | MSAFuture | None | Type[Protein.NullMSA]" = None + self._msa: "str | MSAFuture | MSA | None | Type[Protein.NullMSA]" = None self._templates: "Sequence[Protein | Complex | Template]" = () # per-residue arrays self._data: dict[str, npt.NDArray] = {} @@ -94,8 +96,10 @@ def sequence(self) -> bytes: @sequence.setter def sequence(self, x: bytes | str) -> None: assert set(x if isinstance(x, str) else x.decode()).issubset( - set(_sequence_utils.AMINO_ACIDS + _sequence_utils.EXTRA_TOKENS) - ), "Expected only amino acids or the mask token 'X' or the variable length token '?'\nHint: Use Protein.from_expr if using a sequence expression" + set(sequence_utils.AMINO_ACIDS + sequence_utils.EXTRA_TOKENS) + ), ( + "Expected only amino acids or the mask token 'X' or the variable length token '?'\nHint: Use Protein.from_expr if using a sequence expression" + ) assert len(x) == len(self) self._sequence = x.encode() if isinstance(x, str) else x @@ -105,11 +109,11 @@ def set_sequence(self, x: bytes | str) -> "Protein": @property def coordinates(self) -> npt.NDArray[np.float32]: - return _numpy_utils.readonly_view(self._coordinates) + return numpy_utils.readonly_view(self._coordinates) @property def plddt(self) -> npt.NDArray[np.float32]: - return _numpy_utils.readonly_view(self._plddt) + return numpy_utils.readonly_view(self._plddt) @property def cyclic(self) -> bool: @@ -131,20 +135,20 @@ class NullMSA: ... single_sequence_mode = NullMSA @property - def msa(self) -> "str | MSAFuture | None | Type[NullMSA]": + def msa(self) -> "str | MSAFuture | MSA | None | Type[NullMSA]": """A reference identifier to the MSA associated to this protein.""" return self._msa @msa.setter - def msa(self, msa: "str | MSAFuture | None | Type[NullMSA]") -> None: + def msa(self, msa: "str | MSAFuture | MSA | None | Type[NullMSA]") -> None: # NB: no defensive copy of msa b/c we don't want to copy things like session # objects, but msa should really be immutable anyways... self._msa = msa - def get_msa(self) -> "str | MSAFuture | None | Type[NullMSA]": + def get_msa(self) -> "str | MSAFuture | MSA | None | Type[NullMSA]": return self._msa - def set_msa(self, x: "str | MSAFuture | None | Type[NullMSA]") -> "Protein": + def set_msa(self, x: "str | MSAFuture | MSA | None | Type[NullMSA]") -> "Protein": self._msa = x return self @@ -170,7 +174,12 @@ def __len__(self): return len(self.sequence) def __getitem__( - self, idx: int | slice | Sequence[int] | npt.NDArray[np.integer] + self, + idx: int + | slice + | Sequence[int] + | npt.NDArray[np.integer] + | npt.NDArray[np.bool_], ) -> "Protein": """Return a new Protein object indexing into residues by `idx`.""" if isinstance(idx, int): @@ -183,7 +192,6 @@ def __getitem__( sequence=np.frombuffer(self.sequence, dtype=np.uint8)[idx].tobytes(), name=self.name, ) - # TODO: check msa compatible? new = new.set_msa(self._msa).set_cyclic(self._cyclic) new._data = {k: v[idx].copy() for k, v in self._data.items()} return new @@ -199,14 +207,15 @@ def __add__(self, right: "Protein | str") -> "Protein": assert isinstance(right, Protein) or isinstance(right, str) if isinstance(right, str): right = self.from_expr(right) - # TODO: if either cyclic, should we actually disable adding? assert right._msa == self._msa and right._cyclic == self._cyclic new = Protein( sequence=self.sequence + right.sequence, name=( # set name if equal, or if only one of the two have a name self.name if self.name == right.name or right.name is None - else right.name if self.name is None else None + else right.name + if self.name is None + else None ), ) new = new.set_msa(self._msa).set_cyclic(self._cyclic) @@ -216,7 +225,6 @@ def __add__(self, right: "Protein | str") -> "Protein": } return new - # --- complex set operations to support & and | operators between proteins and Complexes --- # NOTE - in python, the or operator (|) is used to combine sets and dicts, but we also support # the and operator (&) to do the same thing @@ -237,18 +245,16 @@ def __and__(self, right: "Complex | Protein | str") -> "Complex": if isinstance(right, str): right = self.from_expr(right) if isinstance(right, Protein): - id_gen = _chain_id_utils.id_generator() + id_gen = chain_id_utils.id_generator() return Complex({next(id_gen): self, next(id_gen): right}) # NOTE - this inserts this protein at the _end_ of the Complex even though the operation # was Protein & Complex - return right & self + return right & self # map the (|) or operator to the and operators __ror__ = __rand__ __or__ = __and__ - # --- end set operator definitions --- - def at(self, positions: Sequence[int] | npt.NDArray[np.integer]) -> "Protein": """ Return a new Protein object containing residues at given 1-indexed positions. @@ -340,7 +346,7 @@ def get_group_at( ) -> npt.NDArray[np.int_]: if not isinstance(positions, np.ndarray): positions = np.fromiter(positions, dtype=int) - return _numpy_utils.readonly_view(self._group[positions - 1]) + return numpy_utils.readonly_view(self._group[positions - 1]) def set_group_at( self, @@ -354,10 +360,10 @@ def set_group_at( @property def group(self) -> npt.NDArray[np.integer]: - return _numpy_utils.readonly_view(self._group) + return numpy_utils.readonly_view(self._group) def get_group(self) -> npt.NDArray[np.integer]: - return _numpy_utils.readonly_view(self._group) + return numpy_utils.readonly_view(self._group) def set_group(self, value: int) -> "Protein": self._group[:] = value @@ -368,7 +374,7 @@ def get_binding_at( ) -> npt.NDArray[np.str_]: if not isinstance(positions, np.ndarray): positions = np.fromiter(positions, dtype=int) - return _numpy_utils.readonly_view(self._binding[positions - 1]) + return numpy_utils.readonly_view(self._binding[positions - 1]) def set_binding_at( self, @@ -382,10 +388,10 @@ def set_binding_at( @property def binding(self) -> npt.NDArray[np.str_]: - return _numpy_utils.readonly_view(self._binding) + return numpy_utils.readonly_view(self._binding) def get_binding(self) -> npt.NDArray[np.str_]: - return _numpy_utils.readonly_view(self._binding) + return numpy_utils.readonly_view(self._binding) @overload def rmsd( @@ -493,24 +499,6 @@ def to_string(self, format: Literal["cif", "pdb"] = "cif") -> str: else: raise ValueError(format) - def make_cif_string(self) -> str: - warnings.warn( - "`make_cif_string()` is deprecated and will be removed in v0.11. " - "Use `to_string()` instead.", - FutureWarning, - stacklevel=2, - ) - return self._make_cif_string() - - def make_pdb_string(self) -> str: - warnings.warn( - "`make_pdb_string()` is deprecated and will be removed in v0.11. " - 'Use `to_string(format="pdb")` instead.', - FutureWarning, - stacklevel=2, - ) - return self._make_pdb_string() - def make_fasta_bytes(self) -> bytes: assert self.name is not None data = io.BytesIO() @@ -557,7 +545,7 @@ def from_expr(expr: str | int, name: str | None = None) -> "Protein": """ if isinstance(expr, int): expr = str(expr) - sequence = _sequence_utils.SequenceExpr.parse(expr).to_protein_sequence() + sequence = sequence_utils.SequenceExpr.parse(expr).to_protein_sequence() return Protein(sequence=sequence, name=name) @staticmethod @@ -617,7 +605,7 @@ def from_string( model_idx: int = 0, verbose: bool = True, ) -> "Protein": - structure_block = _cif_utils.StructureCIFBlock( + structure_block = cif_utils.StructureCIFBlock( filestring=filestring, format=format ) return Protein._from_structure_block( @@ -684,7 +672,7 @@ def _assert_valid_templates(self): @staticmethod def _from_structure_block( - structure_block: _cif_utils.StructureCIFBlock, + structure_block: cif_utils.StructureCIFBlock, chain_id: str, use_bfactor_as_plddt: bool | None = None, model_idx: int = 0, @@ -711,12 +699,12 @@ def _from_structure_block( f"{len(matching_entities)}: {matching_entities}" ) entity = matching_entities[0] - assert ( - entity.entity_type == gemmi.EntityType.Polymer - ), f"expected entity type polymer, got {entity.entity_type}" - assert ( - entity.polymer_type == gemmi.PolymerType.PeptideL - ), f"expected polymer type PeptideL, got {entity.polymer_type}" + assert entity.entity_type == gemmi.EntityType.Polymer, ( + f"expected entity type polymer, got {entity.entity_type}" + ) + assert entity.polymer_type == gemmi.PolymerType.PeptideL, ( + f"expected polymer type PeptideL, got {entity.polymer_type}" + ) if len(entity.full_sequence) > 0: chain_seq = entity.full_sequence else: @@ -736,7 +724,6 @@ def _from_structure_block( # extract sequence entity = structure.get_entity_of(polymer) residues = list(polymer.first_conformer()) - # TODO: consider utilizing polymer.make_one_letter_sequence() here or elsewhere del polymer if len(entity.full_sequence) > 0: chain_seq, label_seq_offset = entity.full_sequence, 1 @@ -750,7 +737,7 @@ def _from_structure_block( # extract coordinates and plddt coordinates = np.full((len(chain_seq), _N_ATOM, 3), np.nan, dtype=np.float32) plddt = np.full(len(chain_seq), np.nan, dtype=np.float32) - max_atom_b_iso = -np.inf # max B-factor over all atoms (for pLDDT check below) + max_atom_b_iso = -np.inf for residue_idx, residue in enumerate(residues): i = ( residue.label_seq - label_seq_offset @@ -761,8 +748,6 @@ def _from_structure_block( code = code.upper() if code != " " else "X" if code != chain_seq[i]: if verbose: - # TODO: can this ever happen...? probably want to have this regardless i guess - # TODO: improve this message? print( f"Amino acid mismatch at position {i + 1}: SEQRES {chain_seq[i]} Structure {code}" ) @@ -781,14 +766,13 @@ def _from_structure_block( max_atom_b_iso = max(max_atom_b_iso, atom.b_iso) if residue.name == "MSE" and atom_name == "SE": atom_name = "SD" - if (j := _ATOM_TYPE_TO_IDX.get(atom.name)) is None: + if (j := _ATOM_TYPE_TO_IDX.get(atom_name)) is None: continue coordinates[i, j] = atom.pos.tolist() if use_bfactor_as_plddt and atom_name == "CA": plddt[i] = ( atom.b_iso if atom.b_iso != _NAN_BFACTOR_VALUE else np.nan ) - # TODO: we should experiment and see if this is the behavior we want if ( not use_bfactor_as_plddt and np.isfinite(coordinates[i, _ATOM_TYPE_TO_IDX["CA"]]).all() @@ -812,7 +796,7 @@ def _from_structure_block( return protein def _set_loop_data( - self, structure_block: _cif_utils.StructureCIFBlock, chain_id: str + self, structure_block: cif_utils.StructureCIFBlock, chain_id: str ): # TODO: chain id overload, extract this into its own method # TODO: for all tables, support optional columns being missing @@ -899,11 +883,15 @@ def _binding(self, x: npt.NDArray[np.str_]) -> None: def _make_structure( self, structure: gemmi.Structure | None = None, - model_idx: int = 1, + model_idx: int = 0, chain_id: str = "A", entity_name: str = "1", ) -> gemmi.Structure: - # TODO: add note about _NAN_BFACTOR_VALUE + if b"?" in self.sequence: + raise ValueError( + "this protein has a length range (`?` positions); a structure takes " + "a fixed length, such as Protein.from_expr(15)" + ) # Create an empty structure and add a model with a default chain. if structure is None: structure = gemmi.Structure() @@ -913,9 +901,8 @@ def _make_structure( if len(structure) > 0: model = structure[model_idx] else: - model = structure.add_model(gemmi.Model(str(model_idx))) # type: ignore - gemmi 0.6 needs str + model = structure.add_model(gemmi.Model(str(model_idx + 1))) # type: ignore - gemmi 0.6 needs str # Process the sequence. - # TODO: handle optional token...? resnames = gemmi.expand_one_letter_sequence( self.sequence.decode(), gemmi.ResidueKind.AA ) @@ -927,9 +914,9 @@ def _make_structure( structure.entities.append(entity) # Process the coordinates. n_nan_coords = np.isnan(self._coordinates).sum(axis=2) - assert ( - (n_nan_coords == 0) | (n_nan_coords == 3) - ).all(), "either all coords of an atom must be nan, or none are" + assert ((n_nan_coords == 0) | (n_nan_coords == 3)).all(), ( + "either all coords of an atom must be nan, or none are" + ) # Process the plddt. assert ( np.isnan(self._plddt) | (~np.isnan(self._plddt) & (n_nan_coords[:, 1] == 0)) @@ -991,7 +978,7 @@ def _make_cif_string(self) -> str: block = structure.make_mmcif_block( groups=gemmi.MmcifOutputGroups(True, chem_comp=False) ) - sequence_loop, atom_loop = _cif_utils.init_loops(block=block) + sequence_loop, atom_loop = cif_utils.init_loops(block=block) self._append_loop_data( chain_id="A", sequence_loop=sequence_loop, atom_loop=atom_loop ) @@ -1084,7 +1071,7 @@ def _enum_to_str( def _calc_rmsd_and_transform( - xyz1: npt.NDArray[np.floating], xyz2: npt.NDArray[np.floating], eps: float = 1e-6 + xyz1: npt.NDArray[np.floating], xyz2: npt.NDArray[np.floating] ) -> tuple[float, npt.NDArray[np.floating], npt.NDArray[np.floating]]: """ Calculates RMSD and the rigid transformation (R, t) to superimpose xyz2 onto xyz1. @@ -1107,7 +1094,6 @@ def _calc_rmsd_and_transform( # 3. Compute optimal rotation matrix using SVD # Note: numpy.linalg.svd returns U, S, Vh (where Vh is V.T) - # The variable names V, W below follow the original code's notation logic V, S, W = np.linalg.svd(C) # 4. Get sign to ensure right-handedness (correct for reflections) @@ -1121,7 +1107,7 @@ def _calc_rmsd_and_transform( # 6. Rotate xyz2 (centered) to calculate RMSD xyz2_aligned_c = xyz2_c @ U L = xyz2_aligned_c.shape[0] - rmsd = np.sqrt(np.sum((xyz2_aligned_c - xyz1_c) ** 2, axis=(0, 1)) / L + eps) + rmsd = np.sqrt(np.sum((xyz2_aligned_c - xyz1_c) ** 2, axis=(0, 1)) / L) # 7. Compute R and t # We want: xyz2 @ R.T + t diff --git a/openprotein/molecules/structure.py b/openprotein/molecules/structure.py index edf5cdb..ee2d5e6 100644 --- a/openprotein/molecules/structure.py +++ b/openprotein/molecules/structure.py @@ -1,15 +1,17 @@ import gzip -import requests from collections.abc import Sequence from pathlib import Path from typing import Literal import gemmi +import requests -import openprotein.utils.cif as _cif_utils +import openprotein.utils.cif as cif_utils from .complex import Complex +__all__ = ["Structure"] + class Structure: """Represents a collection of :class:`Complex` instances.""" @@ -93,7 +95,7 @@ def from_string( use_bfactor_as_plddt: bool | None = None, verbose: bool = True, ) -> "Structure": - structure_block = _cif_utils.StructureCIFBlock( + structure_block = cif_utils.StructureCIFBlock( filestring=filestring, format=format ) return Structure( @@ -154,7 +156,7 @@ def _make_cif_string(self) -> str: if len(self._complexes) == 0: return block.as_string() # add additional loops for first complex - sequence_loop, atom_loop = _cif_utils.init_loops(block=block) + sequence_loop, atom_loop = cif_utils.init_loops(block=block) for chain_id, chain in self._complexes[0].get_chains().items(): chain._append_loop_data( chain_id=chain_id, sequence_loop=sequence_loop, atom_loop=atom_loop @@ -199,9 +201,9 @@ def _make_structure(self) -> gemmi.Structure: assert this_entity.sifts_unp_acc == first_entity.sifts_unp_acc assert this_entity.full_sequence == first_entity.full_sequence if sum(_structure_has_no_atoms(structure) for structure in structures) > 0: - assert ( - len(structures) == 1 - ), "can only serialize Structures containing Complexes with no structure data if there is only one complex in the structure" + assert len(structures) == 1, ( + "can only serialize Structures containing Complexes with no structure data if there is only one complex in the structure" + ) structure = structures[0] for this_structure in structures[1:]: structure.add_model(this_structure[0]) diff --git a/openprotein/molecules/template.py b/openprotein/molecules/template.py index 588f2f0..754c50f 100644 --- a/openprotein/molecules/template.py +++ b/openprotein/molecules/template.py @@ -5,6 +5,9 @@ from .complex import Complex from .protein import Protein +__all__ = ["ChainMapping", "TargetMolecule", "Template", "TemplateSource"] + + TemplateSource = Protein | Complex TargetMolecule = Protein | Complex ChainMapping = Mapping[str, str] | str | None @@ -31,16 +34,15 @@ class Template: chain(s) this template applies to. index (Sequence[int] | None): Restrict this template to specific sequence positions in the batched fold job. The default (``None``) applies the - template to every sequence — matching the passthrough behavior callers - see today. Populate to scope a template to a subset, e.g. in a - binder-design refold where structure ``M[k]`` templates only sequences - ``[k*N, k*N+N)``. + template to every sequence. Populate to scope a template to a subset, + e.g. in a binder-design refold where structure ``M[k]`` templates only + sequences ``[k*N, k*N+N)``. index_intervals (Sequence[tuple[int, int]] | None): Range-form alternative to ``index`` for scoping the template to contiguous spans of sequence positions. Each tuple is a half-open ``[start, end)`` range. Useful when the subset is large and contiguous (e.g. ``[(0, 1000)]`` instead - of ``list(range(1000))``). May be combined with ``index``; the server - unions the two. + of ``list(range(1000))``). May be combined with ``index``; the two are + unioned. """ template: TemplateSource diff --git a/openprotein/predictor/__init__.py b/openprotein/predictor/__init__.py index a35c1bc..8f5aa47 100644 --- a/openprotein/predictor/__init__.py +++ b/openprotein/predictor/__init__.py @@ -4,23 +4,77 @@ isort:skip_file """ +from openprotein.models.kernels import ( + LinearKernel as LinearKernel, +) +from openprotein.models.kernels import ( + Matern12Kernel as Matern12Kernel, +) +from openprotein.models.kernels import ( + Matern32Kernel as Matern32Kernel, +) +from openprotein.models.kernels import ( + Matern52Kernel as Matern52Kernel, +) +from openprotein.models.kernels import ( + PeriodicKernel as PeriodicKernel, +) +from openprotein.models.kernels import ( + RationalQuadraticKernel as RationalQuadraticKernel, +) +from openprotein.models.kernels import ( + RBFKernel as RBFKernel, +) +from openprotein.models.kernels import ( + TrainedKernel as TrainedKernel, +) + +from .models import PredictorModel +from .prediction import PredictionResultFuture +from .predictor import PredictorAPI from .schemas import ( - Kernel, - KernelType, Constraints, - Features, Dataset, - PredictorMetadata, - PredictorType, - PredictorArgs, + Features, + Kernel, + KernelType, PredictJob, PredictMultiJob, PredictMultiSingleSiteJob, - PredictSingleSiteJob, - PredictorTrainJob, - PredictorEnsembleJob, + PredictorArgs, PredictorCVJob, + PredictorEnsembleJob, + PredictorMetadata, + PredictorTrainJob, + PredictorType, + PredictSingleSiteJob, ) -from .models import PredictorModel -from .prediction import PredictionResultFuture -from .predictor import PredictorAPI + +__all__ = [ + "Constraints", + "Dataset", + "Features", + "Kernel", + "KernelType", + "LinearKernel", + "Matern12Kernel", + "Matern32Kernel", + "Matern52Kernel", + "PeriodicKernel", + "PredictJob", + "PredictMultiJob", + "PredictMultiSingleSiteJob", + "PredictSingleSiteJob", + "PredictionResultFuture", + "PredictorAPI", + "PredictorArgs", + "PredictorCVJob", + "PredictorEnsembleJob", + "PredictorMetadata", + "PredictorModel", + "PredictorTrainJob", + "PredictorType", + "RBFKernel", + "RationalQuadraticKernel", + "TrainedKernel", +] diff --git a/openprotein/predictor/api.py b/openprotein/predictor/api.py index 91399db..45c5cf1 100644 --- a/openprotein/predictor/api.py +++ b/openprotein/predictor/api.py @@ -8,10 +8,9 @@ from openprotein.base import APISession from openprotein.errors import APIError -from openprotein.jobs import Job +from openprotein.models.kernels import _GPHyperparameters from .schemas import ( - Job, PredictJob, PredictMultiJob, PredictMultiSingleSiteJob, @@ -21,7 +20,27 @@ PredictSingleSiteJob, ) -PATH_PREFIX = "v1/predictor" +__all__ = [ + "decode_crossvalidate", + "decode_predict", + "predictor_crossvalidate_get", + "predictor_crossvalidate_post", + "predictor_delete", + "predictor_ensemble", + "predictor_fit_gp_post", + "predictor_get", + "predictor_list", + "predictor_predict_get_batched_result", + "predictor_predict_get_sequence_result", + "predictor_predict_get_sequences", + "predictor_predict_multi_post", + "predictor_predict_multi_single_site_post", + "predictor_predict_post", + "predictor_predict_single_site_post", +] + + +_PATH_PREFIX = "v1/predictor" def predictor_list( @@ -52,7 +71,7 @@ def predictor_list( list[PredictorMetadata] List of predictors """ - endpoint = PATH_PREFIX + endpoint = _PATH_PREFIX response = session.get( endpoint, params={ @@ -89,7 +108,7 @@ def predictor_get( PredictorMetadata Metadata of the requested predictor. """ - endpoint = PATH_PREFIX + f"/{predictor_id}" + endpoint = _PATH_PREFIX + f"/{predictor_id}" response = session.get( endpoint, params={ @@ -100,6 +119,29 @@ def predictor_get( return TypeAdapter(PredictorMetadata).validate_python(response.json()) +def _predictor_get_hyperparameters( + session: APISession, predictor_id: str +) -> dict[str, _GPHyperparameters]: + """ + Get the trained hyperparameters of a GP predictor. + + Parameters + ---------- + session : APISession + Session object for API communication. + predictor_id : str + Unique identifier of the predictor. + + Returns + ------- + dict of str to _GPHyperparameters + Trained hyperparameters, keyed by trained property. + """ + endpoint = _PATH_PREFIX + f"/{predictor_id}/hyperparameters" + response = session.get(endpoint, timeout=session.timeout) + return TypeAdapter(dict[str, _GPHyperparameters]).validate_python(response.json()) + + def predictor_fit_gp_post( session: APISession, assay_id: str, @@ -150,7 +192,7 @@ def predictor_fit_gp_post( PredictorTrainJob Train job that can be tracked for progress. """ - endpoint = PATH_PREFIX + "/gp" + endpoint = _PATH_PREFIX + "/gp" kernel_spec: dict = {"type": kernel} if period is not None: @@ -175,7 +217,6 @@ def predictor_fit_gp_post( body["name"] = name if description is not None: body["description"] = description - # add kwargs for embeddings kwargs to features body["features"].update(kwargs) response = session.post(endpoint, json=body) @@ -185,7 +226,7 @@ def predictor_fit_gp_post( def predictor_ensemble( session: APISession, predictor_ids: list[str] ) -> PredictorMetadata: - endpoint = PATH_PREFIX + f"/ensemble" + endpoint = _PATH_PREFIX + f"/ensemble" body = { "model_ids": predictor_ids, @@ -196,7 +237,7 @@ def predictor_ensemble( def predictor_delete(session: APISession, predictor_id: str): - endpoint = PATH_PREFIX + f"/{predictor_id}" + endpoint = _PATH_PREFIX + f"/{predictor_id}" response = session.delete(endpoint) if 200 <= response.status_code < 300: return True @@ -207,7 +248,7 @@ def predictor_delete(session: APISession, predictor_id: str): def predictor_crossvalidate_post( session: APISession, predictor_id: str, n_splits: int | None = None ): - endpoint = PATH_PREFIX + f"/{predictor_id}/crossvalidate" + endpoint = _PATH_PREFIX + f"/{predictor_id}/crossvalidate" params = {} if n_splits is not None: @@ -218,7 +259,7 @@ def predictor_crossvalidate_post( def predictor_crossvalidate_get(session: APISession, crossvalidate_job_id: str): - endpoint = PATH_PREFIX + f"/crossvalidate/{crossvalidate_job_id}" + endpoint = _PATH_PREFIX + f"/crossvalidate/{crossvalidate_job_id}" response = session.get(endpoint) return response.content @@ -227,7 +268,7 @@ def predictor_crossvalidate_get(session: APISession, crossvalidate_job_id: str): def predictor_predict_post( session: APISession, predictor_id: str, sequences: list[bytes] | list[str] ): - endpoint = PATH_PREFIX + f"/{predictor_id}/predict" + endpoint = _PATH_PREFIX + f"/{predictor_id}/predict" sequences_unicode = [(s if isinstance(s, str) else s.decode()) for s in sequences] body = { @@ -241,7 +282,7 @@ def predictor_predict_post( def predictor_predict_multi_post( session: APISession, predictor_ids: list[str], sequences: list[bytes] | list[str] ): - endpoint = PATH_PREFIX + f"/predict" + endpoint = _PATH_PREFIX + f"/predict" sequences_unicode = [(s if isinstance(s, str) else s.decode()) for s in sequences] body = { @@ -258,7 +299,7 @@ def predictor_predict_single_site_post( predictor_id: str, base_sequence: bytes | str, ): - endpoint = PATH_PREFIX + f"/{predictor_id}/predict_single_site" + endpoint = _PATH_PREFIX + f"/{predictor_id}/predict_single_site" base_sequence = ( base_sequence.decode() if isinstance(base_sequence, bytes) else base_sequence @@ -276,7 +317,7 @@ def predictor_predict_multi_single_site_post( predictor_ids: list[str], base_sequence: bytes | str, ): - endpoint = PATH_PREFIX + f"/predict_single_site" + endpoint = _PATH_PREFIX + f"/predict_single_site" base_sequence = ( base_sequence.decode() if isinstance(base_sequence, bytes) else base_sequence @@ -293,7 +334,7 @@ def predictor_predict_multi_single_site_post( def predictor_predict_get_sequences( session: APISession, prediction_job_id: str ) -> list[bytes]: - endpoint = PATH_PREFIX + f"/predict/{prediction_job_id}/sequences" + endpoint = _PATH_PREFIX + f"/predict/{prediction_job_id}/sequences" response = session.get(endpoint) return TypeAdapter(list[bytes]).validate_python(response.json()) @@ -320,7 +361,7 @@ def predictor_predict_get_sequence_result( """ if isinstance(sequence, bytes): sequence = sequence.decode() - endpoint = PATH_PREFIX + f"/predict/{prediction_job_id}/{sequence}" + endpoint = _PATH_PREFIX + f"/predict/{prediction_job_id}/{sequence}" response = session.get(endpoint) return response.content @@ -344,7 +385,7 @@ def predictor_predict_get_batched_result( ------- result : bytes """ - endpoint = PATH_PREFIX + f"/predict/{prediction_job_id}" + endpoint = _PATH_PREFIX + f"/predict/{prediction_job_id}" response = session.get(endpoint) return response.content @@ -379,19 +420,18 @@ def decode_crossvalidate(data: bytes) -> tuple[np.ndarray, np.ndarray, np.ndarra """ Decode crossvalidate scores. - Args: - data (bytes): raw bytes encoding the array received over the API + Parameters + ---------- + data : bytes + Raw bytes of the crossvalidation csv received over the API. - Returns: - mus (np.ndarray): decoded array of means - vars (np.ndarray): decoded array of variances + Returns + ------- + tuple of np.ndarray + The observed ``y`` and the cross-validated ``y_mu`` and ``y_var`` of each + evaluated row. """ - s = io.BytesIO(data) - # should contain header and sequence column - df = pd.read_csv(s) + df = pd.read_csv(io.BytesIO(data)) scores = df.values # row_num, seq, measurement_name, y, y_mu, y_var - y = scores[:, 3] - mus = scores[:, 4] - vars = scores[:, 5] - return y, mus, vars + return scores[:, 3], scores[:, 4], scores[:, 5] diff --git a/openprotein/predictor/models.py b/openprotein/predictor/models.py index 0d43dd4..5804733 100644 --- a/openprotein/predictor/models.py +++ b/openprotein/predictor/models.py @@ -1,12 +1,19 @@ """Predictor models for making predictions on new sequences.""" +from functools import cached_property from typing import TYPE_CHECKING from openprotein.base import APISession from openprotein.data import AssayDataset, DataAPI -from openprotein.embeddings import EmbeddingModel, EmbeddingsAPI +from openprotein.embeddings import EmbeddingModel from openprotein.errors import InvalidParameterError from openprotein.jobs import Future, JobsAPI, JobType +from openprotein.models.kernels import ( + TrainedKernel, + _GPHyperparameters, + _sole_hyperparameters, + _trained_kernel, +) from openprotein.svd import SVDAPI, SVDModel from . import api @@ -22,6 +29,8 @@ if TYPE_CHECKING: from openprotein.design import ModelCriterion +__all__ = ["PredictorModel", "PredictorModelGroup"] + class PredictorModel(Future): """ @@ -46,8 +55,8 @@ def __init__( :meta private: """ self._training_assay = None + self._hyperparameters: _GPHyperparameters | None = None - # initialize the predictor metadata if metadata is None: if job is None or job.job_id is None: raise ValueError("Expected predictor metadata or job") @@ -136,9 +145,23 @@ def id(self): """ID of predictor.""" return self._metadata.id + @property + def name(self): + """The name of the predictor.""" + return self._metadata.name + + @property + def description(self): + """The description of the predictor.""" + return self._metadata.description + + def rename(self, name: str | None = None, description: str | None = None): + """Not supported: a predictor's name is set when it is trained.""" + raise NotImplementedError("a predictor's name is set when it is trained") + @property def reduction(self): - """The reduction of th embeddings used to train the predictor, if any.""" + """The reduction of the embeddings used to train the predictor, if any.""" return ( self._metadata.model_spec.features.reduction if self._metadata.model_spec.features is not None @@ -219,11 +242,21 @@ def get_assay(self) -> AssayDataset: """ data_api = getattr(self.session, "data", None) assert isinstance(data_api, DataAPI) - return data_api.get(assay_id=self._metadata.training_dataset.assay_id) + return data_api.Assay(id=self._metadata.training_dataset.assay_id) def crossvalidate(self, n_splits: int | None = None) -> CVResultFuture: """ Run a crossvalidation on the trained predictor. + + Parameters + ---------- + n_splits : int, optional + Number of folds. + + Returns + ------- + CVResultFuture + Future for the crossvalidation job. """ return CVResultFuture.create( session=self.session, @@ -253,6 +286,73 @@ def predict(self, sequences: list[bytes] | list[str]) -> PredictionResultFuture: ), ) + def _get_hyperparameters(self) -> _GPHyperparameters: + if self._hyperparameters is None: + self._hyperparameters = _sole_hyperparameters( + api._predictor_get_hyperparameters( + session=self.session, predictor_id=self.id + ) + ) + return self._hyperparameters + + # IPython can evaluate this descriptor to complete the concrete kernel's fields. + @cached_property + def kernel(self) -> TrainedKernel: + """ + The trained kernel of this GP predictor, in data space. + + The first access, including runtime tab completion, may make a request. + Failed reads are retried on subsequent access. + + Its class follows the kernel type and carries only the hyperparameters that + apply to it: every kernel has an ``outputscale``, every kernel but linear a + ``lengthscale``, periodic a ``period`` and rational quadratic an ``alpha``. + + Raises + ------ + HTTPError + 404 for an ensemble, or a GP trained before hyperparameters were recorded. + + Examples + -------- + >>> predictor.kernel + PeriodicKernel(outputscale=1.92, lengthscale=0.83, period=2.31) + >>> predictor.kernel.lengthscale + 0.83 + """ + hyperparameters = self._get_hyperparameters() + kernel_spec = self._metadata.model_spec.kernel + assert kernel_spec is not None + try: + return _trained_kernel(kernel_spec.type, hyperparameters) + except ValueError: + self._hyperparameters = None + raise + + @property + def mean(self) -> float | None: + """ + Constant mean of the GP prior, in the units of the trained property. + + Raises + ------ + HTTPError + 404 for an ensemble, or a GP trained before hyperparameters were recorded. + """ + return self._get_hyperparameters().mean + + @property + def noise(self) -> float | None: + """ + Observation noise variance, in the units of the trained property squared. + + Raises + ------ + HTTPError + 404 for an ensemble, or a GP trained before hyperparameters were recorded. + """ + return self._get_hyperparameters().noise + def single_site(self, sequence: bytes | str) -> PredictionResultFuture: """ Compute the single-site mutated predictions of a base sequence. diff --git a/openprotein/predictor/prediction.py b/openprotein/predictor/prediction.py index 2fd0cbf..2870b09 100644 --- a/openprotein/predictor/prediction.py +++ b/openprotein/predictor/prediction.py @@ -13,6 +13,8 @@ PredictSingleSiteJob, ) +__all__ = ["PredictionResultFuture"] + class PredictionResultFuture(Future): """Prediction results represented as a future.""" @@ -48,9 +50,11 @@ def id(self): def __keys__(self): return self.sequences - def get_item(self, sequence: bytes) -> tuple[np.ndarray, np.ndarray]: + def get_item( # ty: ignore[invalid-method-override] + self, sequence: bytes + ) -> tuple[np.ndarray, np.ndarray]: """ - Get embedding results for specified sequence. + Get prediction results for specified sequence. Args: sequence (bytes): sequence to fetch results for @@ -66,14 +70,14 @@ def get_item(self, sequence: bytes) -> tuple[np.ndarray, np.ndarray]: def _get(self, verbose: bool = False) -> tuple[np.ndarray, np.ndarray]: """ - Get embedding results for specified sequence. + Get prediction results for all sequences. Args: - sequence (bytes): sequence to fetch results for + verbose: Unused; present to match the `Future._get` signature. Returns: - mu (np.ndarray): means of predictions - var (np.ndarray): variances of predictions + mu (np.ndarray): means of predictions, one per sequence + var (np.ndarray): variances of predictions, one per sequence """ data = api.predictor_predict_get_batched_result(self.session, self.job.job_id) return api.decode_predict(data, batched=True) diff --git a/openprotein/predictor/predictor.py b/openprotein/predictor/predictor.py index 0fd6b94..ca57f67 100644 --- a/openprotein/predictor/predictor.py +++ b/openprotein/predictor/predictor.py @@ -15,6 +15,8 @@ from .models import PredictorModel from .schemas import KernelType +__all__ = ["PredictorAPI"] + class PredictorAPI: """Predictor API providing the interface to train and predict predictors.""" @@ -170,13 +172,13 @@ def fit_gp( data_api = getattr(self.session, "data", None) assert isinstance(data_api, DataAPI) # 1. Check assay data input - # get assay if str - assay = data_api.get(assay_id=assay) if isinstance(assay, str) else assay - # extract assay_id + assay = data_api.Assay(id=assay) if isinstance(assay, str) else assay assay_id = ( assay.assay_id if isinstance(assay, AssayMetadata) - else assay.id if isinstance(assay, AssayDataset) else assay + else assay.id + if isinstance(assay, AssayDataset) + else assay ) if len(properties) == 0: raise InvalidParameterError("Expected (at-least) 1 property to train") @@ -199,26 +201,30 @@ def fit_gp( ) from e if period is not None: if kernel != KernelType.PERIODIC: - raise InvalidParameterError("`period` is only valid for the 'periodic' kernel") + raise InvalidParameterError( + "`period` is only valid for the 'periodic' kernel" + ) if period <= 0: raise InvalidParameterError("`period` must be > 0") if alpha is not None: if kernel != KernelType.RATIONAL_QUADRATIC: - raise InvalidParameterError("`alpha` is only valid for the 'rational_quadratic' kernel") + raise InvalidParameterError( + "`alpha` is only valid for the 'rational_quadratic' kernel" + ) if alpha <= 0: raise InvalidParameterError("`alpha` must be > 0") # 2. Check features input - # extract feature type feature_type = ( FeatureType.PLM if isinstance(model, EmbeddingModel) - else FeatureType.SVD if isinstance(model, SVDModel) else feature_type + else FeatureType.SVD + if isinstance(model, SVDModel) + else feature_type ) if feature_type is None: raise InvalidParameterError( "Expected feature_type to be provided if passing str model_id as model" ) - # runtime check on value if isinstance(feature_type, str): feature_type = FeatureType(feature_type) @@ -227,7 +233,6 @@ def fit_gp( reduction = ReductionType(reduction) reduction = reduction.value - # get model if model_id if feature_type == FeatureType.PLM: if reduction is None: raise InvalidParameterError( diff --git a/openprotein/predictor/schemas.py b/openprotein/predictor/schemas.py index 174ee58..949a661 100644 --- a/openprotein/predictor/schemas.py +++ b/openprotein/predictor/schemas.py @@ -9,6 +9,25 @@ from openprotein.common import FeatureType from openprotein.jobs import Job, JobStatus, JobType +__all__ = [ + "Constraints", + "Dataset", + "Features", + "Kernel", + "KernelType", + "ModelSpec", + "PredictJob", + "PredictMultiJob", + "PredictMultiSingleSiteJob", + "PredictSingleSiteJob", + "PredictorArgs", + "PredictorCVJob", + "PredictorEnsembleJob", + "PredictorMetadata", + "PredictorTrainJob", + "PredictorType", +] + class KernelType(str, Enum): """Kernel options for a GP predictor.""" @@ -44,8 +63,6 @@ class Features(BaseModel): model_id: str | None = None reduction: str | None = None - # TODO: model extra kwargs - model_config = ConfigDict(protected_namespaces=()) diff --git a/openprotein/predictor/validate.py b/openprotein/predictor/validate.py index 4bb2e4b..32b2bab 100644 --- a/openprotein/predictor/validate.py +++ b/openprotein/predictor/validate.py @@ -2,39 +2,37 @@ import numpy as np -from openprotein.base import APISession from openprotein.jobs import Future from . import api from .schemas import PredictorCVJob +__all__ = ["CVResultFuture"] + class CVResultFuture(Future): """Future Job for manipulating results""" job: PredictorCVJob - def __init__( - self, - session: APISession, - job: PredictorCVJob, - ): - super().__init__(session, job) - @property def id(self): return self.job.job_id def _get(self, verbose: bool = False) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """ - Get embedding results for specified sequence. - - Args: - sequence (bytes): sequence to fetch results for - - Returns: - mu (np.ndarray): means of predictions - var (np.ndarray): variances of predictions + Get the cross-validation results for this job. + + Parameters + ---------- + verbose : bool, optional + Flag to enable verbose output, by default False. + + Returns + ------- + tuple of np.ndarray + The observed ``y`` and the cross-validated ``y_mu`` and ``y_var`` of + each evaluated row. """ data = api.predictor_crossvalidate_get(self.session, self.job.job_id) return api.decode_crossvalidate(data) diff --git a/openprotein/prompt/__init__.py b/openprotein/prompt/__init__.py index bbee046..8d5a0a2 100644 --- a/openprotein/prompt/__init__.py +++ b/openprotein/prompt/__init__.py @@ -7,3 +7,13 @@ from .schemas import Context, PromptMetadata, QueryMetadata, PromptJob from .models import Prompt, Query from .prompt import PromptAPI + +__all__ = [ + "Context", + "Prompt", + "PromptAPI", + "PromptJob", + "PromptMetadata", + "Query", + "QueryMetadata", +] diff --git a/openprotein/prompt/api.py b/openprotein/prompt/api.py index ba1a404..dbe1a02 100644 --- a/openprotein/prompt/api.py +++ b/openprotein/prompt/api.py @@ -1,6 +1,7 @@ """Prompt REST API interface for making HTTP calls to the prompt backend.""" import io +import re import zipfile from typing import BinaryIO, Sequence, cast @@ -10,6 +11,18 @@ from .schemas import Context, PromptMetadata, QueryMetadata +__all__ = [ + "create_prompt", + "create_query", + "get_prompt", + "get_prompt_metadata", + "get_query", + "get_query_metadata", + "list_prompts", + "unzip_prompt", + "zip_prompt", +] + def _coerce_sequence( name: str, sequence: bytes | str, allow_empty_chains: bool = False @@ -308,6 +321,12 @@ def zip_prompt( return context_zip_files +def _context_position(file_name: str) -> tuple[int, int]: + """Sort key for archive members: ``context-.zip`` by ``n``, then the rest.""" + match = re.fullmatch(r"context-(\d+)\.zip", file_name) + return (0, int(match.group(1))) if match else (1, 0) + + def unzip_prompt(prompt_zip: BinaryIO) -> list[list[Protein | Complex]]: """ Unzip a prompt zip file retrieved from the prompt API. @@ -324,16 +343,19 @@ def unzip_prompt(prompt_zip: BinaryIO) -> list[list[Protein | Complex]]: Returns ------- list of list of Protein or Complex - List of context entry lists, where each inner list represents a context group. + List of context entry lists, where each inner list represents a context + group, in the order of the number in ``context-.zip``. """ context_zip_files = [] with zipfile.ZipFile(prompt_zip, "r") as zip_file: - file_names = zip_file.namelist() + file_names = sorted( + (name for name in zip_file.namelist() if name.startswith("context-")), + key=_context_position, + ) for file_name in file_names: - if file_name.startswith("context-"): - context_zip_file = io.BytesIO(zip_file.read(file_name)) - context_zip_files.append(context_zip_file) + context_zip_file = io.BytesIO(zip_file.read(file_name)) + context_zip_files.append(context_zip_file) context = __parse_prompt(context_files=context_zip_files) return context @@ -477,9 +499,7 @@ def create_query( "text/x-fasta", ) else: - raise InvalidParameterError( - f"unexpected query type: {type(query).__name__}" - ) + raise InvalidParameterError(f"unexpected query type: {type(query).__name__}") response = session.post(endpoint, files={"query": (filename, io.BytesIO(qf), typ)}) @@ -531,27 +551,13 @@ def get_query_metadata(session: APISession, query_id: str) -> QueryMetadata: raise APIError(f"Unexpected response status code: {response.status_code}") -def get_query(session: APISession, query_id: str) -> Protein | Complex: - """ - Get the query content for a given query ID. - - Parameters - ---------- - session : APISession - The API session. - query_id : str - The query ID. - - Returns - ------- - Protein or Complex - The query content. Single-chain entries collapse to :py:class:`Protein`; - multichain entries are returned as :py:class:`Complex`. +def _fetch_query(session: APISession, query_id: str) -> Protein | Complex: + """Fetch and parse the query content for a given query ID. - Raises - ------ - APIError - If the API returns an error or the file format is unexpected. + An mmCIF or PDB query always parses as a :py:class:`Complex`, with chain ids + taken from the file; a FASTA query has no chain id and parses as a + :py:class:`Protein` (or a :py:class:`Complex` with auto-assigned chain ids + if it has ``:`` chain breaks). """ endpoint = f"v1/prompt/query/{query_id}/content" response = session.get(endpoint, stream=True) @@ -568,18 +574,19 @@ def get_query(session: APISession, query_id: str) -> Protein | Complex: filename = response.headers.get("Content-Disposition", "query") media_type = response.headers.get("Content-Type", "text/plain") is_mmcif = filename.endswith(".cif") or media_type == "chemical/x-mmcif" + is_pdb = filename.endswith(".pdb") or media_type == "chemical/x-pdb" is_fasta = filename.endswith(".fasta") or media_type == "text/x-fasta" query = None if is_mmcif: - complex_ = Complex.from_string( + query = Complex.from_string( filestring=response.content, format="cif", verbose=False ) - proteins = complex_.get_proteins() - if len(proteins) == 1 and len(complex_.get_chains()) == 1: - query = next(iter(proteins.values())) - else: - query = complex_ + + elif is_pdb: + query = Complex.from_string( + filestring=response.content, format="pdb", verbose=False + ) elif is_fasta: # Process FASTA file - take only the first sequence @@ -601,3 +608,64 @@ def get_query(session: APISession, query_id: str) -> Protein | Complex: raise APIError(f"Invalid query file returned from API {response.content[:10]}") return query + + +def get_query(session: APISession, query_id: str) -> Protein | Complex: + """ + Get the query content for a given query ID. + + Parameters + ---------- + session : APISession + The API session. + query_id : str + The query ID. + + Returns + ------- + Protein or Complex + The query content. Single-chain entries collapse to :py:class:`Protein`; + multichain entries are returned as :py:class:`Complex`. + + Raises + ------ + APIError + If the API returns an error or the file format is unexpected. + """ + query = _fetch_query(session=session, query_id=query_id) + if isinstance(query, Complex): + proteins = query.get_proteins() + if len(proteins) == 1 and len(query.get_chains()) == 1: + return next(iter(proteins.values())) + return query + + +def _get_query_as_complex(session: APISession, query_id: str) -> Complex: + """ + Get the query content for a given query ID as a :py:class:`Complex`. + + An mmCIF or PDB query returns the parsed Complex with chain ids taken from the + file. A FASTA query has no chain id, so a single-chain result is wrapped + as ``Complex({"A": protein})``. + + Parameters + ---------- + session : APISession + The API session. + query_id : str + The query ID. + + Returns + ------- + Complex + The query content as a Complex. + + Raises + ------ + APIError + If the API returns an error or the file format is unexpected. + """ + query = _fetch_query(session=session, query_id=query_id) + if isinstance(query, Protein): + return Complex({"A": query}, name=query.name) + return query diff --git a/openprotein/prompt/models.py b/openprotein/prompt/models.py index cd73013..cb1896f 100644 --- a/openprotein/prompt/models.py +++ b/openprotein/prompt/models.py @@ -1,15 +1,23 @@ from openprotein import config from openprotein.base import APISession from openprotein.errors import InvalidParameterError -from openprotein.jobs import Future, JobsAPI +from openprotein.jobs import Future, Job, JobsAPI from openprotein.molecules import Complex, Protein from . import api from .schemas import PromptJob, PromptMetadata, QueryMetadata +__all__ = ["Prompt", "Query"] + class Prompt(Future): - """Prompt which contains a set of sequences and/or structures used to condition the PoET models.""" + """Prompt which contains a set of sequences and/or structures used to condition the PoET models. + + See Also + -------- + openprotein.data.Prompt : A stored prompt. ``session.data.Prompt`` uploads, + lists and loads prompts. + """ metadata: PromptMetadata session: APISession @@ -71,7 +79,14 @@ def __str__(self) -> str: return str(self.metadata) def __repr__(self) -> str: - return repr(self.metadata) + fields = ", ".join(f"{name}={value!r}" for name, value in self.metadata) + return f"Prompt({fields})" + + def _refresh_job(self, timeout: float | None = None) -> Job: + """Refresh the job, and the status the metadata reports with it.""" + job = super()._refresh_job(timeout=timeout) + self.metadata = self.metadata.model_copy(update={"status": job.status}) + return job def _get(self, verbose: bool = False, **kwargs) -> list[list[Protein | Complex]]: """ @@ -159,6 +174,10 @@ def created_date(self): """The timestamp when the prompt was created.""" return self.metadata.created_date + def rename(self, name: str | None = None, description: str | None = None): + """Not supported: a prompt's name is set when it is created.""" + raise NotImplementedError("a prompt's name is set when it is created") + @property def num_replicates(self): """The number of replicates in the prompt for an ensemble prompt.""" @@ -178,7 +197,7 @@ class Query: Create a query with a masked sequence using :py:meth:`~openprotein.molecules.Protein.mask_sequence_at` for :py:class:`~openprotein.embeddings.PoET2Model` to run inverse folding. - Create a query with a masked structure using :py:meth:`~openprotein.molecules.Protein.mask_structure_at` for :py:class:`~openprotein.models.RFdiffusionModel` to run inverse folding. + Create a query with a masked structure using :py:meth:`~openprotein.molecules.Protein.mask_structure_at` for :py:class:`~openprotein.models.RFdiffusion` to run inverse folding. """ metadata: QueryMetadata @@ -222,13 +241,11 @@ def get_as_complex(self) -> Complex: """ Retrieve the query as a :py:class:`Complex`. - A single-chain :py:class:`Protein` result is wrapped as - ``Complex({"A": protein})`` so the return type is uniform. + An mmCIF or PDB query returns the parsed Complex with chain ids taken from the + file. A FASTA query has no chain id, so a single-chain result is + wrapped as ``Complex({"A": protein})``. """ - query = api.get_query(session=self.session, query_id=str(self.id)) - if isinstance(query, Protein): - return Complex({"A": query}, name=query.name) - return query + return api._get_query_as_complex(session=self.session, query_id=str(self.id)) def get_as_protein(self) -> Protein: """ diff --git a/openprotein/prompt/prompt.py b/openprotein/prompt/prompt.py index f07c5f9..86ac644 100644 --- a/openprotein/prompt/prompt.py +++ b/openprotein/prompt/prompt.py @@ -10,6 +10,15 @@ from .models import Prompt, Query from .schemas import Context +__all__ = [ + "HUMAN_ANTIBODY_VH_V1", + "HUMAN_ANTIBODY_VH_VL_V1", + "HUMAN_ANTIBODY_VL_V1", + "HUMAN_ANTIBODY_VL_VH_V1", + "PromptAPI", +] + + HUMAN_ANTIBODY_VH_V1 = "c044b1b9-9842-536a-83e0-e81400199f67" HUMAN_ANTIBODY_VH_VL_V1 = "0ddde5dc-d140-5d53-bebf-e69fff5a05c5" HUMAN_ANTIBODY_VL_V1 = "3da24801-7032-5b79-a0b9-6e687581de60" @@ -37,10 +46,9 @@ def create_prompt( Context or list of contexts. Each context is a sequence of entries where each entry is a raw sequence (``bytes``/``str``, optionally with ``:`` chain breaks for multichain), :py:class:`Protein`, or - :py:class:`Complex`. Currently only protein chains are accepted; - passing a Complex with DNA, RNA, or Ligand chains raises - :py:class:`InvalidParameterError`. This restriction may be relaxed - in the future. + :py:class:`Complex`. Only protein chains are accepted; passing a + Complex with DNA, RNA, or Ligand chains raises + :py:class:`InvalidParameterError`. name : str Name of the prompt. description : Optional[str] @@ -106,10 +114,9 @@ def create_query( ---------- query : bytes or str or Protein or Complex A query protein or complex. Raw ``bytes``/``str`` inputs may include - ``:`` chain breaks to denote a multichain protein. Currently only - protein chains are accepted; passing a Complex with DNA, RNA, or - Ligand chains raises :py:class:`InvalidParameterError`. This - restriction may be relaxed in the future. + ``:`` chain breaks to denote a multichain protein. Only protein + chains are accepted; passing a Complex with DNA, RNA, or Ligand + chains raises :py:class:`InvalidParameterError`. force_structure : bool, optional Optionally force a query to be interpreted with a structure. Useful for creating structure prediction queries which can have @@ -258,14 +265,11 @@ def _resolve_query( self._resolve_query(query=q, force_structure=force_structure) for q in query ] - elif ( - isinstance(query, Protein) - or isinstance(query, Complex) - or isinstance(query, bytes) - or (isinstance(query, str) and not uuid.is_valid_uuid(query)) - ): + elif (known_id := uuid._as_id(query)) is not None: + query_id = known_id + elif isinstance(query, (Protein, Complex, bytes, str)): query_ = self.create_query(query=query, force_structure=force_structure) query_id = query_.id else: - query_id = query if isinstance(query, str) else query.id + query_id = query.id return query_id diff --git a/openprotein/prompt/schemas.py b/openprotein/prompt/schemas.py index 3063d9c..39ad105 100644 --- a/openprotein/prompt/schemas.py +++ b/openprotein/prompt/schemas.py @@ -1,23 +1,27 @@ +from collections.abc import Sequence from datetime import datetime -from typing import Literal, Sequence +from typing import Literal from pydantic import BaseModel, Field from openprotein.jobs import Job, JobStatus, JobType from openprotein.molecules import Complex, Protein +__all__ = ["Context", "PromptJob", "PromptMetadata", "QueryMetadata"] + + Context = Sequence[bytes | str | Protein | Complex] class PromptJob(Job): - """A representation of a prompt job.""" + """A prompt sampling job.""" - job_type: Literal[JobType.align_prompt] + job_type: Literal[JobType.align_prompt, "/prompt/sample_msa"] @property - def msa_id(self): - """ID of the underlying MSA.""" - return self.msa_id + def msa_id(self) -> str | None: + """ID of the underlying MSA, or None if the job doesn't carry it.""" + return (self.model_extra or {}).get("msa_id") @property def prompt_id(self): diff --git a/openprotein/protein.py b/openprotein/protein.py deleted file mode 100644 index 9a974ff..0000000 --- a/openprotein/protein.py +++ /dev/null @@ -1,12 +0,0 @@ -import warnings - -warnings.warn( - "openprotein.protein is deprecated and will be removed in v0.11. " - "Use `from openprotein.molecules import Protein` instead.", - FutureWarning, - stacklevel=2, -) - -from openprotein.molecules import Protein - -__all__ = ["Protein"] diff --git a/openprotein/scaffolds.py b/openprotein/scaffolds.py deleted file mode 100644 index a0942ec..0000000 --- a/openprotein/scaffolds.py +++ /dev/null @@ -1,8 +0,0 @@ -"""Scaffolds that are available for protein design on OpenProtein AI platform.""" - -from enum import Enum - - -class Scaffolds(str, Enum): - - VHH = "default_vhh" diff --git a/openprotein/svd/__init__.py b/openprotein/svd/__init__.py index 71f0e57..5b1a890 100644 --- a/openprotein/svd/__init__.py +++ b/openprotein/svd/__init__.py @@ -7,3 +7,12 @@ from .schemas import SVDMetadata, SVDFitJob, SVDEmbeddingsJob from .models import SVDModel, SVDEmbeddingsResultFuture from .svd import SVDAPI + +__all__ = [ + "SVDAPI", + "SVDEmbeddingsJob", + "SVDEmbeddingsResultFuture", + "SVDFitJob", + "SVDMetadata", + "SVDModel", +] diff --git a/openprotein/svd/api.py b/openprotein/svd/api.py index d4133b9..3bcbcdd 100644 --- a/openprotein/svd/api.py +++ b/openprotein/svd/api.py @@ -10,7 +10,19 @@ from .schemas import SVDEmbeddingsJob, SVDFitJob, SVDMetadata -PATH_PREFIX = "v1/embeddings/svd" +__all__ = [ + "embed_decode", + "embed_get_sequence_result", + "svd_delete", + "svd_embed_post", + "svd_fit_post", + "svd_get", + "svd_get_sequences", + "svd_list_get", +] + + +_PATH_PREFIX = "v1/embeddings/svd" def svd_list_get( @@ -19,7 +31,7 @@ def svd_list_get( offset: int | None = None, ) -> list[SVDMetadata]: """Get SVD job metadata for all SVDs. Including SVD dimension and sequence lengths.""" - endpoint = PATH_PREFIX + endpoint = _PATH_PREFIX params = {} if limit is not None: params["limit"] = limit @@ -31,7 +43,7 @@ def svd_list_get( def svd_get(session: APISession, svd_id: str) -> SVDMetadata: """Get SVD job metadata. Including SVD dimension and sequence lengths.""" - endpoint = PATH_PREFIX + f"/{svd_id}" + endpoint = _PATH_PREFIX + f"/{svd_id}" response = session.get(endpoint) return SVDMetadata.model_validate(response.json()) @@ -51,7 +63,7 @@ def svd_get_sequences(session: APISession, svd_id: str) -> list[bytes]: ------- sequences : List[bytes] """ - endpoint = PATH_PREFIX + f"/{svd_id}/sequences" + endpoint = _PATH_PREFIX + f"/{svd_id}/sequences" response = session.get(endpoint) return TypeAdapter(list[bytes]).validate_python(response.json()) @@ -77,7 +89,7 @@ def embed_get_sequence_result( """ if isinstance(sequence, bytes): sequence = sequence.decode() - endpoint = PATH_PREFIX + f"/embed/{job_id}/{sequence}" + endpoint = _PATH_PREFIX + f"/embed/{job_id}/{sequence}" response = session.get(endpoint) return response.content @@ -98,7 +110,7 @@ def embed_decode(data: bytes) -> np.ndarray: def svd_delete(session: APISession, svd_id: str): """ - Delete and SVD model. + Delete an SVD model. Parameters ---------- @@ -112,7 +124,7 @@ def svd_delete(session: APISession, svd_id: str): bool """ - endpoint = PATH_PREFIX + f"/{svd_id}" + endpoint = _PATH_PREFIX + f"/{svd_id}" response = session.delete(endpoint) if 200 <= response.status_code < 300: return True @@ -158,7 +170,7 @@ def svd_fit_post( Job """ - endpoint = PATH_PREFIX + endpoint = _PATH_PREFIX body: dict = { "model_id": model_id, @@ -177,11 +189,9 @@ def svd_fit_post( if assay_id is None: raise InvalidParameterError("Expected either sequences or assay_id") body["assay_id"] = assay_id - # add kwargs for embeddings kwargs body.update(**kwargs) response = session.post(endpoint, json=body) - # return job for metadata return SVDFitJob.model_validate(response.json()) @@ -207,7 +217,7 @@ def svd_embed_post( ------- Job """ - endpoint = PATH_PREFIX + f"/{svd_id}/embed" + endpoint = _PATH_PREFIX + f"/{svd_id}/embed" sequences_unicode = [(s if isinstance(s, str) else s.decode()) for s in sequences] body = { diff --git a/openprotein/svd/models.py b/openprotein/svd/models.py index a4bf438..2f96288 100644 --- a/openprotein/svd/models.py +++ b/openprotein/svd/models.py @@ -19,6 +19,8 @@ from openprotein.predictor import PredictorModel from openprotein.umap import UMAPModel +__all__ = ["SVDEmbeddingsResultFuture", "SVDModel"] + class SVDModel(Future): """ @@ -36,7 +38,6 @@ def __init__( metadata: SVDMetadata | None = None, ): """Construct the SVD model using either job get or svd metadata get.""" - # initialize the metadata if metadata is None: # use job to fetch metadata if job is None: @@ -155,24 +156,25 @@ def fit_umap( **kwargs, ) -> "UMAPModel": """ - Fit an UMAP on the embedding results of this model. - - This function will create an UMAPModel based on the embeddings from this model \ - as well as the hyperparameters specified in the args. + Fit an UMAP on the embedding results of this model. Parameters ---------- - sequences : List[bytes] - sequences to UMAP - n_components: int - number of components in UMAP. Will determine output shapes - reduction: ReductionType | None - embeddings reduction to use (e.g. mean) + sequences : list[bytes] | list[str] | None, optional + Sequences to fit the UMAP on. Provide either this or ``assay``. + assay : AssayDataset | None, optional + Assay whose sequences to fit the UMAP on. Provide either this or + ``sequences``. + n_components : int, optional + Number of components in the UMAP, which determines the output shape. + Defaults to 2. + **kwargs + Additional keyword arguments passed to the UMAP fit. Returns ------- UMAPModel - UMAP model fitted on the reduced embeddings from provided sequences or assay. + UMAP model fitted on the reduced embeddings from provided sequences or assay. """ # local import for cyclic dep from openprotein.umap import UMAPAPI @@ -180,7 +182,6 @@ def fit_umap( umap_api = getattr(self.session, "umap", None) assert isinstance(umap_api, UMAPAPI) - # Ensure either or if (assay is None and sequences is None) or ( assay is not None and sequences is not None ): @@ -238,8 +239,7 @@ def fit_gp( predictor_api = getattr(self.session, "predictor", None) assert isinstance(predictor_api, PredictorAPI) - # get assay if str - assay = data_api.get(assay_id=assay) if isinstance(assay, str) else assay + assay = data_api.Assay(id=assay) if isinstance(assay, str) else assay if ( self.sequence_length is not None and assay.sequence_length != self.sequence_length diff --git a/openprotein/svd/schemas.py b/openprotein/svd/schemas.py index 6261ffb..5e828e1 100644 --- a/openprotein/svd/schemas.py +++ b/openprotein/svd/schemas.py @@ -7,6 +7,8 @@ from openprotein.jobs import BatchJob, Job, JobStatus, JobType +__all__ = ["SVDEmbeddingsJob", "SVDFitJob", "SVDMetadata"] + class SVDMetadata(BaseModel): id: str diff --git a/openprotein/svd/svd.py b/openprotein/svd/svd.py index 896d2aa..0033b5d 100644 --- a/openprotein/svd/svd.py +++ b/openprotein/svd/svd.py @@ -3,13 +3,14 @@ from typing import Literal from openprotein.base import APISession -from openprotein.common import ReductionType from openprotein.data import AssayDataset, AssayMetadata from openprotein.embeddings import EmbeddingModel, EmbeddingsAPI from . import api from .models import SVDModel +__all__ = ["SVDAPI"] + class SVDAPI: """SVD API providing the interface for creating and using SVD models.""" @@ -61,11 +62,12 @@ def fit_svd( assert isinstance(embeddings_api, EmbeddingsAPI) model = embeddings_api.get_model(model) if isinstance(model, str) else model assert isinstance(model, EmbeddingModel), "Expected EmbeddingModel" - # get assay_id assay_id = ( assay.assay_id if isinstance(assay, AssayMetadata) - else assay.id if isinstance(assay, AssayDataset) else assay + else assay.id + if isinstance(assay, AssayDataset) + else assay ) return SVDModel( session=self.session, diff --git a/openprotein/umap/__init__.py b/openprotein/umap/__init__.py index 1fddaac..158fb53 100644 --- a/openprotein/umap/__init__.py +++ b/openprotein/umap/__init__.py @@ -7,3 +7,12 @@ from .schemas import UMAPMetadata, UMAPEmbeddingsJob, UMAPFitJob from .models import UMAPModel, UMAPEmbeddingsResultFuture from .umap import UMAPAPI + +__all__ = [ + "UMAPAPI", + "UMAPEmbeddingsJob", + "UMAPEmbeddingsResultFuture", + "UMAPFitJob", + "UMAPMetadata", + "UMAPModel", +] diff --git a/openprotein/umap/api.py b/openprotein/umap/api.py index 82a032e..7df214c 100644 --- a/openprotein/umap/api.py +++ b/openprotein/umap/api.py @@ -9,9 +9,23 @@ from openprotein.base import APISession from openprotein.errors import APIError, InvalidParameterError -from .schemas import FeatureType, UMAPEmbeddingsJob, UMAPFitJob, UMAPMetadata +from .schemas import UMAPEmbeddingsJob, UMAPFitJob, UMAPMetadata -PATH_PREFIX = "v1/umap" +__all__ = [ + "embed_batch_decode", + "embed_decode", + "embed_get_batch_result", + "embed_get_sequence_result", + "umap_delete", + "umap_embed_post", + "umap_fit_post", + "umap_get", + "umap_get_sequences", + "umap_list_get", +] + + +_PATH_PREFIX = "v1/umap" def umap_list_get( @@ -20,7 +34,7 @@ def umap_list_get( offset: int | None = None, ) -> list[UMAPMetadata]: """Get UMAP job metadata for all UMAPs. Including UMAP dimension and sequence lengths.""" - endpoint = PATH_PREFIX + endpoint = _PATH_PREFIX params = {} if limit is not None: params["limit"] = limit @@ -32,7 +46,7 @@ def umap_list_get( def umap_get(session: APISession, umap_id: str) -> UMAPMetadata: """Get UMAP job metadata. Including UMAP dimension and sequence lengths.""" - endpoint = PATH_PREFIX + f"/{umap_id}" + endpoint = _PATH_PREFIX + f"/{umap_id}" response = session.get(endpoint) return UMAPMetadata.model_validate(response.json()) @@ -52,7 +66,7 @@ def umap_get_sequences(session: APISession, umap_id: str) -> list[bytes]: ------- sequences : List[bytes] """ - endpoint = PATH_PREFIX + f"/{umap_id}/sequences" + endpoint = _PATH_PREFIX + f"/{umap_id}/sequences" response = session.get(endpoint) return TypeAdapter(list[bytes]).validate_python(response.json()) @@ -78,7 +92,7 @@ def embed_get_sequence_result( """ if isinstance(sequence, bytes): sequence = sequence.decode() - endpoint = PATH_PREFIX + f"/embed/{job_id}/{sequence}" + endpoint = _PATH_PREFIX + f"/embed/{job_id}/{sequence}" response = session.get(endpoint) return response.content @@ -98,7 +112,7 @@ def embed_get_batch_result(session: APISession, job_id: str) -> bytes: ------- result : bytes """ - endpoint = PATH_PREFIX + f"/embed/{job_id}/csv" + endpoint = _PATH_PREFIX + f"/embed/{job_id}/csv" response = session.get(endpoint) return response.content @@ -121,15 +135,13 @@ def embed_decode(data: bytes) -> np.ndarray: def embed_batch_decode(data: bytes) -> np.ndarray: """ - Decode prediction scores. + Decode batched UMAP embeddings. Args: data (bytes): raw bytes encoding the array received over the API - batched (bool): whether or not the result was batched. affects the retrieved csv format whether they contain additional columns and header rows. Returns: - mus (np.ndarray): decoded array of means - vars (np.ndarray): decoded array of variances + np.ndarray: decoded array of projected embeddings """ s = io.BytesIO(data) # should contain header and sequence column @@ -140,7 +152,7 @@ def embed_batch_decode(data: bytes) -> np.ndarray: def umap_delete(session: APISession, umap_id: str) -> bool: """ - Delete and UMAP model. + Delete a UMAP model. Parameters ---------- @@ -154,7 +166,7 @@ def umap_delete(session: APISession, umap_id: str) -> bool: bool """ - endpoint = PATH_PREFIX + f"/{umap_id}" + endpoint = _PATH_PREFIX + f"/{umap_id}" response = session.delete(endpoint) if 200 <= response.status_code < 300: return True @@ -208,7 +220,7 @@ def umap_fit_post( UMAPFitJob """ - endpoint = PATH_PREFIX + endpoint = _PATH_PREFIX body = { "model_id": model_id, @@ -230,11 +242,9 @@ def umap_fit_post( if assay_id is None: raise InvalidParameterError("Expected either sequences or assay_id") body["assay_id"] = assay_id - # add kwargs for embeddings kwargs body.update(**kwargs) response = session.post(endpoint, json=body) - # return job for metadata return UMAPFitJob.model_validate(response.json()) @@ -260,7 +270,7 @@ def umap_embed_post( ------- UMAPEmbeddingsJob """ - endpoint = PATH_PREFIX + f"/{umap_id}/embed" + endpoint = _PATH_PREFIX + f"/{umap_id}/embed" sequences_unicode = [(s if isinstance(s, str) else s.decode()) for s in sequences] body = { diff --git a/openprotein/umap/models.py b/openprotein/umap/models.py index 5935901..529d7c3 100644 --- a/openprotein/umap/models.py +++ b/openprotein/umap/models.py @@ -10,6 +10,8 @@ from . import api from .schemas import UMAPEmbeddingsJob, UMAPFitJob, UMAPMetadata +__all__ = ["UMAPEmbeddingsResultFuture", "UMAPModel"] + class UMAPModel(Future["UMAPModel"]): """ diff --git a/openprotein/umap/schemas.py b/openprotein/umap/schemas.py index 1c8a76c..764ef62 100644 --- a/openprotein/umap/schemas.py +++ b/openprotein/umap/schemas.py @@ -8,6 +8,8 @@ from openprotein.common import FeatureType from openprotein.jobs import BatchJob, Job, JobStatus, JobType +__all__ = ["UMAPEmbeddingsJob", "UMAPFitJob", "UMAPMetadata"] + class UMAPMetadata(BaseModel): id: str diff --git a/openprotein/umap/umap.py b/openprotein/umap/umap.py index 73d4a64..47d9ca5 100644 --- a/openprotein/umap/umap.py +++ b/openprotein/umap/umap.py @@ -1,7 +1,6 @@ """UMAP API providing the interface to fit and run UMAP visualizations.""" import typing -from typing import Literal from openprotein.base import APISession from openprotein.common import Feature, FeatureType, Reduction, ReductionType @@ -14,6 +13,8 @@ from . import api from .models import UMAPModel +__all__ = ["UMAPAPI"] + class UMAPAPI: """UMAP API providing the interface to fit and run UMAP visualizations.""" @@ -102,17 +103,19 @@ def fit_umap( The UMAP model being fit. """ # 1. Check assay data input - just need the id - # get assay_id assay_id = ( assay.assay_id if isinstance(assay, AssayMetadata) - else assay.id if isinstance(assay, AssayDataset) else assay + else assay.id + if isinstance(assay, AssayDataset) + else assay ) - # extract feature type feature_type = ( FeatureType.PLM if isinstance(model, EmbeddingModel) - else FeatureType.SVD if isinstance(model, SVDModel) else feature_type + else FeatureType.SVD + if isinstance(model, SVDModel) + else feature_type ) if feature_type is None: raise InvalidParameterError( @@ -122,7 +125,6 @@ def fit_umap( feature_type = FeatureType(feature_type) if isinstance(reduction, str): reduction = ReductionType(reduction) - # get model if model_id if feature_type == FeatureType.PLM: if reduction is None: raise InvalidParameterError( diff --git a/openprotein/utils/__init__.py b/openprotein/utils/__init__.py index e69de29..a9a2c5b 100644 --- a/openprotein/utils/__init__.py +++ b/openprotein/utils/__init__.py @@ -0,0 +1 @@ +__all__ = [] diff --git a/openprotein/utils/chain_id.py b/openprotein/utils/chain_id.py index 82202eb..dc80a13 100644 --- a/openprotein/utils/chain_id.py +++ b/openprotein/utils/chain_id.py @@ -1,6 +1,9 @@ import re import string +__all__ = ["id_generator", "is_valid_id", "valid_id_pattern"] + + valid_id_pattern = re.compile(r"^[A-Za-z0-9]{1,5}$") @@ -24,7 +27,6 @@ def id_generator( used = set(used_list) letters = list(string.ascii_uppercase) - # --- Alphabetic IDs --- curr_len = 1 curr_indices = [0] * curr_len # start at 'A' @@ -50,7 +52,6 @@ def bump_indices(): break curr_indices = [0] * curr_len - # --- Numeric IDs --- num = 1 while num <= max_numeric: candidate = str(num) diff --git a/openprotein/utils/cif.py b/openprotein/utils/cif.py index ca68c95..424230c 100644 --- a/openprotein/utils/cif.py +++ b/openprotein/utils/cif.py @@ -6,6 +6,12 @@ import gemmi import numpy as np +__all__ = [ + "StructureCIFBlock", + "init_loops", + "parse_full_sequences_from_entity_poly_seq", +] + class StructureCIFBlock: """ @@ -33,7 +39,7 @@ def full_sequences(self) -> Mapping[str, tuple[Sequence[str], int]]: where full_sequence is a list of residue names and start_residue_number is the 1-indexed residue number corresponding to full_sequence[0]. - Only polymer entities are considered for now. Entities for which a full sequence + Only polymer entities are considered. Entities for which a full sequence cannot be determined are omitted. Sequence determination follows this fallback order: @@ -45,7 +51,7 @@ def full_sequences(self) -> Mapping[str, tuple[Sequence[str], int]]: and the start_residue_number is set to the minimum residue number observed. When reconstructing from `_entity_poly_seq`, no validation is performed to - ensure consistency with the entity's subchains (at least for now). + ensure consistency with the entity's subchains. """ full_sequences: dict[str, tuple[Sequence[str], int]] = {} entities_to_impute: list[gemmi.Entity] = [] diff --git a/openprotein/utils/numpy.py b/openprotein/utils/numpy.py index 107ade5..0b59be1 100644 --- a/openprotein/utils/numpy.py +++ b/openprotein/utils/numpy.py @@ -3,6 +3,9 @@ import numpy as np import numpy.typing as npt +__all__ = ["DType", "readonly_view"] + + DType = TypeVar("DType", bound=np.generic) diff --git a/openprotein/utils/sequence.py b/openprotein/utils/sequence.py index 2be43f5..c4de398 100644 --- a/openprotein/utils/sequence.py +++ b/openprotein/utils/sequence.py @@ -4,8 +4,18 @@ from dataclasses import dataclass from typing import Literal +__all__ = [ + "AMINO_ACIDS", + "CHAIN_BREAK", + "EXTRA_TOKENS", + "SequenceExpr", + "SequenceSegment", +] + + AMINO_ACIDS = "ARNDCQEGHILKMFPSTWYV" EXTRA_TOKENS = "XOUBZ-?" +CHAIN_BREAK = ":" @dataclass @@ -175,10 +185,12 @@ def parse(cls, expr: str) -> "SequenceExpr": Parse a sequence expression. Args: - expr: Sequence expression string + expr: Expression built from fixed residues (uppercase letters), + design counts (digits) and ranges (`start..end`), e.g. "3..5C6C3". Returns: - Parsed SequenceExpression object + The parsed expression, with `segments` holding one entry per + fixed, design or range term. Examples: >>> SequenceExpr.parse("15..20") diff --git a/openprotein/utils/uuid.py b/openprotein/utils/uuid.py index a97a9a3..aa4f5f3 100644 --- a/openprotein/utils/uuid.py +++ b/openprotein/utils/uuid.py @@ -1,14 +1,19 @@ +import re from uuid import UUID +__all__ = ["is_valid_uuid"] -def is_valid_uuid(uuid_to_test: str, version=4): + +def is_valid_uuid(uuid_to_test: str, version: int | None = None): """ Check if uuid_to_test is a valid UUID. Parameters ---------- uuid_to_test : str - version : {1, 2, 3, 4} + version : int, optional + Require this UUID version. Any version is accepted when unset, since + platform job ids are not all version 4. Returns ------- @@ -18,12 +23,36 @@ def is_valid_uuid(uuid_to_test: str, version=4): -------- >>> is_valid_uuid('c9bf9e57-1685-4c89-bafb-ff5af830be8a') True + >>> is_valid_uuid('9af6889e-504d-8bdd-bd6c-1e58a6925708') + True >>> is_valid_uuid('c9bf9e58') False """ try: - uuid_obj = UUID(uuid_to_test, version=version) + uuid_obj = UUID(uuid_to_test) except ValueError: return False + if version is not None and uuid_obj.version != version: + return False return str(uuid_obj) == uuid_to_test + + +_HYPHENATED_ID = re.compile( + r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", re.IGNORECASE +) + + +def _as_id(value: object) -> str | None: + """The lower-cased id when ``value`` is text in the hyphenated 8-4-4-4-12 form. + + Bare hex is not an id: it can be an amino-acid sequence. + """ + if isinstance(value, bytes): + try: + value = value.decode("ascii") + except UnicodeDecodeError: + return None + if isinstance(value, str) and _HYPHENATED_ID.fullmatch(value): + return value.lower() + return None diff --git a/pyproject.toml b/pyproject.toml index 9578146..cfdddf4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -28,6 +28,9 @@ dependencies = [ ] requires-python = ">=3.10,<3.15" +[project.optional-dependencies] +msa = ["pyarrow>=14"] + [dependency-groups] dev = [ "pip>=24.2", @@ -43,6 +46,7 @@ dev = [ "seaborn>=0.13.2", "jupyterlab>=4.4.1", "torch>=2.2.0,<3", + "jsonschema>=4.26", ] [tool.uv.sources] @@ -97,8 +101,8 @@ markers = [ "e2e: End-to-end tests that require API credentials", "slow: Slow-running tests", "integration: Integration tests", - "correctness: Correctness tests (invariants, ground-truth, prod-baseline)", - "differential: Correctness tests that compare against a captured prod baseline", + "correctness: Correctness tests (invariants, ground-truth, baseline)", + "differential: Correctness tests that compare against a committed baseline", ] addopts = "-v --strict-markers --tb=short --disable-warnings -m 'not e2e'" timeout = 1200 diff --git a/scripts/probe_dtypes.py b/scripts/probe_dtypes.py index 2217e51..1cceb42 100644 --- a/scripts/probe_dtypes.py +++ b/scripts/probe_dtypes.py @@ -1,6 +1,7 @@ -"""One-off probe: capture the wire dtype of model outputs from the live backend, -for the models the differential tests cover. Not a committed test — used to record -the ground-truth dtype matrix. Run: `uv run python scripts/probe_dtypes.py`. +"""Print the wire dtype of model outputs returned by the API, for the models +the differential tests cover. + +Run: `uv run python scripts/probe_dtypes.py`. """ from __future__ import annotations diff --git a/tests/align/test_align.py b/tests/align/test_align.py index 18d4b69..719b2ed 100644 --- a/tests/align/test_align.py +++ b/tests/align/test_align.py @@ -1,23 +1,32 @@ """L2 integration tests for the align domain.""" + import io -from datetime import datetime -from unittest.mock import MagicMock +from unittest.mock import MagicMock, patch import pytest from openprotein.align.align import AlignAPI from openprotein.align.msa import MSAFuture -from openprotein.jobs import JobStatus, JobType +from openprotein.align.schemas import AbNumberScheme, UnnumberedPolicy +from openprotein.errors import InvalidParameterError +from openprotein.jobs import JobType @pytest.fixture def align_api(mock_session: MagicMock) -> AlignAPI: - """Fixture for an AlignAPI instance.""" return AlignAPI(mock_session) +@pytest.mark.parametrize("method", ["mafft", "clustalo", "abnumber"]) +def test_names_of_another_length_than_sequences_are_refused_before_any_request( + align_api: AlignAPI, mock_session: MagicMock, method +): + with pytest.raises(InvalidParameterError, match="same length, not 1 and 2"): + getattr(align_api, method)(["ACD", "AAA"], names=["a"]) + mock_session.post.assert_not_called() + + def test_align_api_mafft(align_api: AlignAPI, mock_session: MagicMock): - """Test the mafft method.""" mock_session.post.return_value.status_code = 200 mock_session.post.return_value.json.return_value = { "job_id": "job123", @@ -32,8 +41,33 @@ def test_align_api_mafft(align_api: AlignAPI, mock_session: MagicMock): assert isinstance(future, MSAFuture) +def test_upload_msa_posts_the_file_as_a_ready_made_msa( + align_api: AlignAPI, mock_session: MagicMock +): + mock_session.post.return_value.json.return_value = { + "job_id": "msa-1", + "status": "PENDING", + "job_type": JobType.align_align.value, + "created_date": "2023-01-01T00:00:00", + } + msa_file = io.BytesIO(b">query\nACGT\n>homolog\nACGA\n") + + with pytest.warns(FutureWarning) as record: + future = align_api.upload_msa(msa_file) + + expected = ( + "`AlignAPI.upload_msa` is deprecated since 0.18.0 and will be removed in " + "0.19.0. Use `session.data.MSA.create` and `MSA.sample_prompt`." + ) + assert [str(w.message) for w in record] == [expected] + mock_session.post.assert_called_once_with( + "v1/align/msa", files={"msa_file": msa_file}, params={"is_seed": False} + ) + assert isinstance(future, MSAFuture) + assert future.id == "msa-1" + + def test_align_api_clustalo(align_api: AlignAPI, mock_session: MagicMock): - """Test the clustalo method.""" mock_session.post.return_value.status_code = 200 mock_session.post.return_value.json.return_value = { "job_id": "job123", @@ -49,7 +83,6 @@ def test_align_api_clustalo(align_api: AlignAPI, mock_session: MagicMock): def test_align_api_abnumber(align_api: AlignAPI, mock_session: MagicMock): - """Test the abnumber method.""" mock_session.post.return_value.status_code = 200 mock_session.post.return_value.json.return_value = { "job_id": "job123", @@ -62,3 +95,128 @@ def test_align_api_abnumber(align_api: AlignAPI, mock_session: MagicMock): future = align_api.abnumber(sequences, names) mock_session.post.assert_called_once() assert isinstance(future, MSAFuture) + + +@pytest.mark.parametrize( + ("content", "sequences", "names"), + [ + (b">a\nAC\nGT\n>b\nMKV\n", ["ACGT", "MKV"], ["a", "b"]), + (b"ACGT\nMKV\n\n", ["ACGT", "MKV"], None), + (b"a,ACGT\nb,MKV,\n,\n", ["ACGT", "MKV"], ["a", "b"]), + ( + b"ok,ACGT\nmissing,\nspaces, , ,\nextra,MKV,,\nsolo\n", + ["ACGT", "MKV", "solo"], + ["ok", "extra", ""], + ), + ( + b'"first\nsecond",ACGT\n"comma,label",MKV\n', + ["ACGT", "MKV"], + ["first\nsecond", "comma,label"], + ), + (b"ACGT,\nMKV,,\n", ["ACGT", "MKV"], None), + ], + ids=[ + "fasta", + "csv-one-column", + "csv-two-columns", + "csv-blank-sequences", + "csv-quoted-labels", + "csv-one-column-trailing-fields", + ], +) +@pytest.mark.parametrize( + ("method", "options"), + [ + ("mafft", {"auto": False, "ep": 0.1, "op": 1.5}), + ("clustalo", {"clustersize": 10, "iterations": 3}), + ( + "abnumber", + { + "scheme": AbNumberScheme.KABAT, + "drop_minority_chains": True, + "unnumbered_policy": UnnumberedPolicy.DROP, + }, + ), + ], +) +def test_align_api_file_methods_read_sequences_and_pass_options( + align_api: AlignAPI, + method: str, + options: dict, + content: bytes, + sequences: list[str], + names: list[str] | None, +): + with patch.object(AlignAPI, method) as target, pytest.warns(FutureWarning): + result = getattr(align_api, f"{method}_file")(io.BytesIO(content), **options) + target.assert_called_once_with(sequences, names, **options) + assert result is target.return_value + + +def test_align_api_file_methods_read_text_files(align_api: AlignAPI): + with patch.object(AlignAPI, "mafft") as target, pytest.warns(FutureWarning): + align_api.mafft_file(io.StringIO(">a\nACGT\n")) + target.assert_called_once_with(["ACGT"], ["a"], auto=True, ep=None, op=None) + + +@pytest.mark.parametrize("method", ["mafft_file", "clustalo_file", "abnumber_file"]) +@pytest.mark.parametrize("content", [b"a,b,ACGT\n", b"", b"\n\n", b">a\n\n"]) +def test_align_api_file_methods_reject_unusable_files( + align_api: AlignAPI, method: str, content: bytes +): + with pytest.warns(FutureWarning), pytest.raises(InvalidParameterError): + getattr(align_api, method)(io.BytesIO(content)) + + +@pytest.mark.parametrize("method", ["mafft", "clustalo", "abnumber"]) +def test_align_api_file_methods_warn_with_the_sequence_based_replacement( + align_api: AlignAPI, method: str +): + with patch.object(AlignAPI, method), pytest.warns(FutureWarning) as record: + getattr(align_api, f"{method}_file")(io.BytesIO(b">a\nACGT\n")) + expected = ( + f"`AlignAPI.{method}_file` is deprecated since 0.18.0 and will be removed " + f"in 0.19.0. Use `AlignAPI.{method}` with sequences and names." + ) + assert [str(w.message) for w in record] == [expected] + assert record[0].filename == __file__ + + +@pytest.mark.parametrize( + "make_file", + [ + lambda: b">a\nACGT\n", + lambda: ">a\nACGT\n", + lambda: io.BytesIO(b">a\nACGT\n"), + lambda: ("seqs.fasta", io.BytesIO(b">a\nACGT\n")), + lambda: ("seqs.fasta", io.StringIO(">a\nACGT\n"), "text/plain"), + lambda: ["seqs.fasta", io.BytesIO(b">a\nACGT\n")], + lambda: ["seqs.fasta", io.StringIO(">a\nACGT\n"), "text/plain"], + lambda: bytearray(b">a\nACGT\n"), + ], +) +@pytest.mark.parametrize("method", ["mafft", "clustalo", "abnumber"]) +def test_align_api_file_methods_accept_bytes_bytearray_str_file_objects_tuples_and_lists( + align_api: AlignAPI, method: str, make_file +): + with patch.object(AlignAPI, method) as target, pytest.warns(FutureWarning): + getattr(align_api, f"{method}_file")(make_file()) + assert target.call_args.args == (["ACGT"], ["a"]) + + +def test_align_api_file_methods_keep_every_record_after_a_utf8_bom( + align_api: AlignAPI, +): + content = b"\xef\xbb\xbf>a\nACGT\n>b\nACGA\n" + with patch.object(AlignAPI, "mafft") as target, pytest.warns(FutureWarning): + align_api.mafft_file(io.BytesIO(content)) + assert target.call_args.args == (["ACGT", "ACGA"], ["a", "b"]) + + +def test_align_api_file_methods_keep_every_record_after_a_bom_in_text( + align_api: AlignAPI, +): + content = "\ufeff>a\nACGT\n>b\nACGA\n" + with patch.object(AlignAPI, "mafft") as target, pytest.warns(FutureWarning): + align_api.mafft_file(content) + assert target.call_args.args == (["ACGT", "ACGA"], ["a", "b"]) diff --git a/tests/align/test_align_api.py b/tests/align/test_align_api.py index 87d3ccc..5fd0fdd 100644 --- a/tests/align/test_align_api.py +++ b/tests/align/test_align_api.py @@ -1,9 +1,13 @@ -import io +import warnings +from datetime import datetime +from io import BytesIO from unittest.mock import MagicMock, patch import pytest from openprotein.align.api import ( + _msa_mmseqs_search_post, + _sample_prompt, abnumber_post, antibody_schema_get, clustalo_post, @@ -15,10 +19,14 @@ msa_post, prompt_post, ) -from openprotein.align.schemas import AlignType, MSASamplingMethod, UnnumberedPolicy -from openprotein.base import APISession +from openprotein.align.schemas import ( + AlignType, + Pairing, + UnnumberedPolicy, +) from openprotein.errors import HTTPError, InvalidParameterError, MissingParameterError from openprotein.jobs import Job, JobStatus, JobType +from openprotein.prompt.schemas import PromptMetadata @pytest.fixture @@ -37,14 +45,16 @@ def test_get_align_job_inputs(mock_session: MagicMock): """Test get_align_job_inputs calls the correct endpoint and params.""" mock_session.get.return_value = MagicMock() - get_align_job_inputs(mock_session, "job1", AlignType.MSA) + with pytest.warns(FutureWarning): + get_align_job_inputs(mock_session, "job1", AlignType.MSA) mock_session.get.assert_called_with( "v1/align/inputs", params={"job_id": "job1", "msa_type": "GENERATED"}, stream=True, ) - get_align_job_inputs(mock_session, "job1", AlignType.PROMPT, prompt_index=1) + with pytest.warns(FutureWarning): + get_align_job_inputs(mock_session, "job1", AlignType.PROMPT, prompt_index=1) mock_session.get.assert_called_with( "v1/align/inputs", params={"job_id": "job1", "msa_type": "PROMPT", "replicate": 1}, @@ -52,11 +62,12 @@ def test_get_align_job_inputs(mock_session: MagicMock): ) -@patch("openprotein.align.api.get_align_job_inputs") +@patch("openprotein.align.api._get_align_job_inputs") @patch("openprotein.csv.parse_stream") def test_get_input(mock_csv_stream, mock_get_align_job_inputs, mock_session: MagicMock): """Test get_input correctly calls dependencies.""" - get_input(mock_session, "job1", AlignType.MSA) + with pytest.warns(FutureWarning): + get_input(mock_session, "job1", AlignType.MSA) mock_get_align_job_inputs.assert_called_once_with( session=mock_session, job_id="job1", input_type=AlignType.MSA, prompt_index=None ) @@ -64,81 +75,178 @@ def test_get_input(mock_csv_stream, mock_get_align_job_inputs, mock_session: Mag def test_get_msa_surfaces_incomplete_job_error(mock_session: MagicMock): - """Backend returns 409 when results are requested before the align job completes. + """Reading a stored MSA whose job has not finished raises an HTTPError. - The client should propagate the HTTPError carrying both the status code and - the backend's clarifying detail, so the user can tell the job is still - pending rather than missing. + The error carries the 409 status code and text naming the MSA id, so the + user can tell the job is still pending. """ response = MagicMock() response.status_code = 409 - response.url = "https://api.openprotein.ai/api/v1/align/inputs" - response.text = ( - '{"detail":"Job abc has not produced results yet (status: PENDING). ' - 'Results are only available once the job completes successfully."}' - ) - mock_session.get.side_effect = HTTPError(response) + response.url = "https://api.openprotein.ai/api/v1/data/msa/abc" + response.text = '{"detail":"msa abc is PENDING"}' + job = MagicMock(status_code=200) + job.json.return_value = { + "job_id": "abc", + "job_type": "/align/align", + "status": "SUCCESS", + "created_date": datetime(2023, 1, 1).isoformat(), + } + + def get(endpoint, **kwargs): + if endpoint.startswith("v1/data/msa/"): + raise HTTPError(response) + return job + + mock_session.get.side_effect = get with pytest.raises(HTTPError) as excinfo: - # get_msa -> get_input -> get_align_job_inputs -> session.get list(get_msa(mock_session, "abc")) assert excinfo.value.status_code == 409 - assert "has not produced results yet" in excinfo.value.text - assert "PENDING" in excinfo.value.text + assert "abc" in excinfo.value.text + + +def test_get_seed(mock_session: MagicMock): + """get_seed calls GET v1/align/seed?msa_id=... and returns the sequence.""" + mock_session.get.return_value.json.return_value = { + "sequence": "ACDEFGHIK", + "length": 9, + } + assert get_seed(mock_session, "job123") == "ACDEFGHIK" -def test_msa_post_with_seed(mock_session: MagicMock, sample_job_dict: dict): - """Test msa_post with a seed sequence.""" + args, kwargs = mock_session.get.call_args + assert args[0] == "v1/align/seed" + assert kwargs["params"] == {"msa_id": "job123"} + + +def test_msa_mmseqs_search_post(mock_session: MagicMock, sample_job_dict: dict): + """create_msa's homology search posts the seed to the mmseqs2 search endpoint.""" mock_session.post.return_value.json.return_value = sample_job_dict - job = msa_post(mock_session, seed="ACGT") + job = _msa_mmseqs_search_post(mock_session, seed="ACGT") args, kwargs = mock_session.post.call_args - assert args[0] == "v1/align/msa" - assert kwargs["params"] == {"is_seed": True} - assert "msa_file" in kwargs["files"] + assert args[0] == "v1/align/search/mmseqs2/msa" + assert kwargs["data"] == {"query": "ACGT", "pairing": "both"} + assert "files" not in kwargs assert isinstance(job, Job) -def test_msa_post_with_file(mock_session: MagicMock, sample_job_dict: dict): - """Test msa_post with a file.""" +def test_msa_mmseqs_search_post_pairing(mock_session: MagicMock, sample_job_dict: dict): + """A non-default pairing mode is sent as the pairing form field.""" mock_session.post.return_value.json.return_value = sample_job_dict - msa_file = io.BytesIO(b"test") + _msa_mmseqs_search_post(mock_session, seed="ACGT", pairing=Pairing.PAIRED) - job = msa_post(mock_session, msa_file=msa_file) - mock_session.post.assert_called_once_with( - "v1/align/msa", files={"msa_file": msa_file}, params={"is_seed": False} - ) - assert isinstance(job, Job) + _, kwargs = mock_session.post.call_args + assert kwargs["data"] == {"query": "ACGT", "pairing": "paired"} -def test_msa_post_missing_params(mock_session: MagicMock): - """Test msa_post raises error if both or neither param is given.""" - with pytest.raises(MissingParameterError): - msa_post(mock_session) - - with pytest.raises(MissingParameterError): - msa_post(mock_session, seed="ACGT", msa_file=io.BytesIO()) +@pytest.mark.parametrize( + ("post", "option", "value"), + [ + (mafft_post, "auto", False), + (clustalo_post, "clustersize", 50), + (abnumber_post, "scheme", "kabat"), + ], +) +@pytest.mark.parametrize("positional", [False, True]) +def test_align_post_accepts_sequence_files( + mock_session, sample_job_dict, post, option, value, positional +): + mock_session.post.return_value.json.return_value = sample_job_dict + file = BytesIO(b">first\nACDE\n>second\nACDF\n") + + with pytest.warns(FutureWarning, match=r"0\.18\.0.*0\.19\.0"): + job = ( + post(mock_session, file, value) + if positional + else post(mock_session, sequence_file=file, **{option: value}) + ) + + assert job.job_id == "job123" + assert mock_session.post.call_args.kwargs["json"] == { + "sequences": ["ACDE", "ACDF"], + "names": ["first", "second"], + } + assert mock_session.post.call_args.kwargs["params"][option] == value def test_mafft_post(mock_session: MagicMock, sample_job_dict: dict): """Test mafft_post.""" mock_session.post.return_value.json.return_value = sample_job_dict - sequence_file = io.BytesIO(b"test") - mafft_post(mock_session, sequence_file, auto=False, ep=0.1, op=1.5) + sequences = ["ACGT", "ACGA"] + mafft_post(mock_session, sequences, auto=False, ep=0.1, op=1.5) mock_session.post.assert_called_once_with( "v1/align/mafft", - files={"file": sequence_file}, + json={"sequences": sequences}, params={"auto": False, "ep": 0.1, "op": 1.5}, ) +def test_mafft_post_carries_names(mock_session: MagicMock, sample_job_dict: dict): + """Row labels ride alongside the sequences when the caller supplies them.""" + mock_session.post.return_value.json.return_value = sample_job_dict + sequences = ["ACGT", "ACGA"] + names = ["a", "b"] + mafft_post(mock_session, sequences, names=names) + + _args, kwargs = mock_session.post.call_args + assert kwargs["json"] == {"sequences": sequences, "names": names} + + +def test_mafft_post_omits_names_when_absent( + mock_session: MagicMock, sample_job_dict: dict +): + """No names means no key, so the server applies its own labelling.""" + mock_session.post.return_value.json.return_value = sample_job_dict + mafft_post(mock_session, ["ACGT", "ACGA"]) + + _args, kwargs = mock_session.post.call_args + assert "names" not in kwargs["json"] + + +def test_clustalo_post(mock_session: MagicMock, sample_job_dict: dict): + """Test clustalo_post.""" + mock_session.post.return_value.json.return_value = sample_job_dict + sequences = ["ACGT", "ACGA"] + clustalo_post(mock_session, sequences, clustersize=50, iterations=2) + mock_session.post.assert_called_once_with( + "v1/align/clustalo", + json={"sequences": sequences}, + params={"clustersize": 50, "iterations": 2}, + ) + + +def test_clustalo_post_carries_names(mock_session: MagicMock, sample_job_dict: dict): + """Row labels ride alongside the sequences when the caller supplies them.""" + mock_session.post.return_value.json.return_value = sample_job_dict + sequences = ["ACGT", "ACGA"] + clustalo_post(mock_session, sequences, names=["a", "b"]) + + _args, kwargs = mock_session.post.call_args + assert kwargs["json"] == {"sequences": sequences, "names": ["a", "b"]} + + +SEQUENCES = ["QVQLQESGPG", "DIVMTQSPAS"] + + def test_abnumber_post_invalid_scheme(mock_session: MagicMock): """Test abnumber_post raises error for invalid scheme.""" with pytest.raises( Exception, match="Antibody numbering invalid_scheme not recognized" ): - abnumber_post(mock_session, io.BytesIO(), scheme="invalid_scheme") # type: ignore - testing runtime error + abnumber_post(mock_session, SEQUENCES, scheme="invalid_scheme") + + +def test_abnumber_post_sends_sequences_as_the_body( + mock_session: MagicMock, sample_job_dict: dict +): + """The sequences are the request body, not a file upload.""" + mock_session.post.return_value.json.return_value = sample_job_dict + abnumber_post(mock_session, SEQUENCES, names=["h", "l"]) + + _args, kwargs = mock_session.post.call_args + assert kwargs["json"] == {"sequences": SEQUENCES, "names": ["h", "l"]} def test_abnumber_post_default_drop_minority_chains( @@ -146,8 +254,7 @@ def test_abnumber_post_default_drop_minority_chains( ): """abnumber_post should default drop_minority_chains to False.""" mock_session.post.return_value.json.return_value = sample_job_dict - sequence_file = io.BytesIO(b"test") - abnumber_post(mock_session, sequence_file) + abnumber_post(mock_session, SEQUENCES) args, kwargs = mock_session.post.call_args assert args[0] == "v1/align/abnumber" @@ -159,8 +266,7 @@ def test_abnumber_post_with_drop_minority_chains( ): """abnumber_post should forward drop_minority_chains=True.""" mock_session.post.return_value.json.return_value = sample_job_dict - sequence_file = io.BytesIO(b"test") - abnumber_post(mock_session, sequence_file, drop_minority_chains=True) + abnumber_post(mock_session, SEQUENCES, drop_minority_chains=True) args, kwargs = mock_session.post.call_args assert kwargs["params"]["drop_minority_chains"] is True @@ -172,7 +278,7 @@ def test_abnumber_post_default_unnumbered_policy( """abnumber_post should default unnumbered_policy to error, so dropping residues is always a choice the caller made.""" mock_session.post.return_value.json.return_value = sample_job_dict - abnumber_post(mock_session, io.BytesIO(b"test")) + abnumber_post(mock_session, SEQUENCES) _args, kwargs = mock_session.post.call_args assert kwargs["params"]["unnumbered_policy"] == "error" @@ -184,7 +290,7 @@ def test_abnumber_post_forwards_unnumbered_policy( ): """abnumber_post should forward the policy as its wire value.""" mock_session.post.return_value.json.return_value = sample_job_dict - abnumber_post(mock_session, io.BytesIO(b"test"), unnumbered_policy=policy) + abnumber_post(mock_session, SEQUENCES, unnumbered_policy=policy) _args, kwargs = mock_session.post.call_args assert kwargs["params"]["unnumbered_policy"] == policy @@ -195,9 +301,7 @@ def test_abnumber_post_accepts_policy_enum( ): """The enum and its string value are interchangeable on the wire.""" mock_session.post.return_value.json.return_value = sample_job_dict - abnumber_post( - mock_session, io.BytesIO(b"test"), unnumbered_policy=UnnumberedPolicy.RETAIN - ) + abnumber_post(mock_session, SEQUENCES, unnumbered_policy=UnnumberedPolicy.RETAIN) _args, kwargs = mock_session.post.call_args assert kwargs["params"]["unnumbered_policy"] == "retain" @@ -208,7 +312,7 @@ def test_abnumber_post_invalid_unnumbered_policy(mock_session: MagicMock): with pytest.raises( Exception, match="Unnumbered residue policy maybe not recognized" ): - abnumber_post(mock_session, io.BytesIO(), unnumbered_policy="maybe") + abnumber_post(mock_session, SEQUENCES, unnumbered_policy="maybe") def test_antibody_schema_get(mock_session: MagicMock): @@ -223,30 +327,142 @@ def test_antibody_schema_get(mock_session: MagicMock): assert kwargs["params"] == {"job_id": "job123"} -def test_prompt_post_valid(mock_session: MagicMock, sample_job_dict: dict): - """Test prompt_post with valid parameters.""" +@pytest.fixture +def sample_prompt_metadata() -> dict: + """A PENDING prompt-metadata response from sampling an MSA.""" + return { + "id": "prompt123", + "name": "prompt123", + "description": None, + "created_date": "2023-01-01T00:00:00", + "num_replicates": 1, + "job_id": "prompt123", + "status": JobStatus.PENDING, + } + + +def test_prompt_post_warns_and_samples_through_the_align_route( + mock_session: MagicMock, sample_job_dict: dict +): mock_session.post.return_value.json.return_value = sample_job_dict - prompt_post(mock_session, "msa123", num_sequences=10) + with pytest.warns(FutureWarning) as record: + job = prompt_post(mock_session, "msa123", num_sequences=10) + + assert str(record[0].message) == ( + "`openprotein.align.api.prompt_post` is deprecated since 0.18.0 and will be " + "removed in 0.19.0. Use `MSAFuture.sample_prompt` or `MSA.sample_prompt`." + ) + assert record[0].filename == __file__ args, kwargs = mock_session.post.call_args assert args[0] == "v1/align/prompt" assert kwargs["params"]["msa_id"] == "msa123" assert kwargs["params"]["max_msa_sequences"] == 10 + assert isinstance(job, Job) -def test_prompt_post_missing_both_sizing_params( - mock_session: MagicMock, sample_job_dict: dict +def test_sampling_a_prompt_returns_its_metadata( + mock_session: MagicMock, sample_prompt_metadata: dict ): - """Test prompt_post uses default if both num_sequences and num_residues are None.""" - mock_session.post.return_value.json.return_value = sample_job_dict - prompt_post(mock_session, "msa123") + mock_session.post.return_value.json.return_value = sample_prompt_metadata + + metadata = _sample_prompt(mock_session, "msa123", num_sequences=10) + + args, kwargs = mock_session.post.call_args + assert args[0] == "v1/prompt/sample_msa" + assert kwargs["params"]["msa_id"] == "msa123" + assert kwargs["params"]["max_msa_sequences"] == 10 + assert isinstance(metadata, PromptMetadata) + + +def test_sampling_without_a_size_takes_the_default_token_budget( + mock_session: MagicMock, sample_prompt_metadata: dict +): + mock_session.post.return_value.json.return_value = sample_prompt_metadata + _sample_prompt(mock_session, "msa123") assert mock_session.post.call_args.kwargs["params"]["max_msa_tokens"] == 12288 -def test_prompt_post_invalid_params(mock_session: MagicMock): - """Test prompt_post raises errors for invalid parameter combinations.""" +def test_sampling_refuses_invalid_params_before_any_request(mock_session: MagicMock): with pytest.raises(MissingParameterError): - prompt_post(mock_session, "msa123", num_sequences=10, num_residues=100) - + _sample_prompt(mock_session, "msa123", num_sequences=10, num_residues=100) with pytest.raises(InvalidParameterError): - prompt_post(mock_session, "msa123", homology_level=2.0) + _sample_prompt(mock_session, "msa123", homology_level=2.0) + mock_session.post.assert_not_called() + + +def test_msa_post_warns_and_posts_the_file_as_a_ready_made_msa( + mock_session: MagicMock, sample_job_dict: dict +): + mock_session.post.return_value.json.return_value = sample_job_dict + msa_file = MagicMock() + + with pytest.warns(FutureWarning) as record: + job = msa_post(mock_session, msa_file) + + expected = ( + "`openprotein.align.api.msa_post` is deprecated since 0.18.0 and will be " + "removed in 0.19.0. Use `session.data.MSA.create` for a ready-made MSA, " + "or `session.align.create_msa` for a seed." + ) + assert [str(w.message) for w in record] == [expected] + mock_session.post.assert_called_once_with( + "v1/align/msa", files={"msa_file": msa_file}, params={"is_seed": False} + ) + assert job.job_id == "job123" + + +@pytest.mark.parametrize("seed", ["ACDE", b"ACDE"]) +def test_msa_post_posts_a_seed_as_the_seed_file( + mock_session: MagicMock, sample_job_dict: dict, seed +): + mock_session.post.return_value.json.return_value = sample_job_dict + + with pytest.warns(FutureWarning) as record: + job = msa_post(mock_session, seed=seed) + + assert len(record) == 1 + args, kwargs = mock_session.post.call_args + assert args[0] == "v1/align/msa" + assert kwargs["params"] == {"is_seed": True} + assert kwargs["files"]["msa_file"].read() == b">seed\nACDE" + assert job.job_id == "job123" + + +def test_msa_post_requires_exactly_one_of_msa_file_and_seed(mock_session: MagicMock): + with ( + pytest.warns(FutureWarning) as record, + pytest.raises(MissingParameterError, match="seed OR msa_file"), + ): + msa_post(mock_session) + assert len(record) == 1 + + with ( + pytest.warns(FutureWarning) as record, + pytest.raises(MissingParameterError, match="seed OR msa_file"), + ): + msa_post(mock_session, MagicMock(), seed="ACDE") + assert len(record) == 1 + mock_session.post.assert_not_called() + + +def test_a_tuple_of_sequences_is_not_taken_for_a_sequence_file( + mock_session: MagicMock, sample_job_dict: dict +): + """A tuple of strings is a batch of sequences and sends with no warning.""" + mock_session.post.return_value.json.return_value = sample_job_dict + with warnings.catch_warnings(): + warnings.simplefilter("error") + mafft_post(mock_session, ("ACDE", "ACDF")) + assert mock_session.post.call_args.kwargs["json"] == {"sequences": ("ACDE", "ACDF")} + + +def test_a_named_file_tuple_is_a_sequence_file( + mock_session: MagicMock, sample_job_dict: dict +): + """A ``(name, file)`` tuple reads as a sequence file.""" + mock_session.post.return_value.json.return_value = sample_job_dict + file = ("seqs.fasta", BytesIO(b">first\nACDE\n>second\nACDF\n")) + with pytest.warns(FutureWarning, match=r"0\.18\.0"): + mafft_post(mock_session, file) + assert mock_session.post.call_args.kwargs["json"]["sequences"] == ["ACDE", "ACDF"] diff --git a/tests/align/test_align_msa.py b/tests/align/test_align_msa.py index fbdcc37..21785ac 100644 --- a/tests/align/test_align_msa.py +++ b/tests/align/test_align_msa.py @@ -1,11 +1,9 @@ -from datetime import datetime import warnings -import pytest +from datetime import datetime from unittest.mock import MagicMock, patch -from openprotein.base import APISession -from openprotein.errors import APIError -from openprotein.jobs import Job, JobStatus, JobType +import pytest + from openprotein.align.msa import MSAFuture from openprotein.align.schemas import ( AbNumberJob, @@ -13,7 +11,10 @@ MafftJob, MSASamplingMethod, ) -from openprotein.prompt import Prompt +from openprotein.base import APISession +from openprotein.errors import APIError +from openprotein.jobs import JobStatus, JobType +from openprotein.prompt import Prompt, PromptMetadata @pytest.fixture @@ -39,30 +40,30 @@ def msa_future(mock_session: MagicMock, mafft_job: MafftJob) -> MSAFuture: return MSAFuture(mock_session, mafft_job) -@patch("openprotein.align.api.get_msa") -def test_msa_future_get(mock_get_msa, msa_future: MSAFuture): +@patch("openprotein.align.api._read_msa") +def test_msa_future_get(mock_read_msa, msa_future: MSAFuture): """Test the get method of MSAFuture.""" msa_future.get() - mock_get_msa.assert_called_once_with( - session=msa_future.session, job_id=msa_future.job.job_id + mock_read_msa.assert_called_once_with( + session=msa_future.session, msa_id=msa_future.job.msa_id, format="fasta" ) -@patch("openprotein.align.api.prompt_post") -@patch("openprotein.prompt.Prompt.create") +@patch("openprotein.align.api._sample_prompt") +@patch("openprotein.align.msa.Prompt") def test_msa_future_sample_prompt( - mock_prompt_create, mock_prompt_post, msa_future: MSAFuture + mock_prompt_cls, mock_sample_prompt, msa_future: MSAFuture ): """Test the sample_prompt method of MSAFuture.""" - mock_job = MagicMock(spec=Job) - mock_prompt_post.return_value = mock_job + mock_metadata = MagicMock(spec=PromptMetadata) + mock_sample_prompt.return_value = mock_metadata - mock_prompt_future = MagicMock(spec=Prompt) - mock_prompt_create.return_value = mock_prompt_future + mock_prompt = MagicMock(spec=Prompt) + mock_prompt_cls.return_value = mock_prompt prompt = msa_future.sample_prompt(num_sequences=10, method=MSASamplingMethod.RANDOM) - mock_prompt_post.assert_called_once_with( + mock_sample_prompt.assert_called_once_with( msa_future.session, msa_id=msa_future.msa_id, num_sequences=10, @@ -76,11 +77,11 @@ def test_msa_future_sample_prompt( random_seed=None, ) - mock_prompt_create.assert_called_once_with( - session=msa_future.session, job=mock_job, num_replicates=1 + mock_prompt_cls.assert_called_once_with( + session=msa_future.session, metadata=mock_metadata ) - assert prompt == mock_prompt_future + assert prompt == mock_prompt _UNNUMBERED_WARNING = { @@ -159,10 +160,10 @@ def abnumber_future(mock_session: MagicMock, abnumber_job: AbNumberJob) -> MSAFu return MSAFuture(mock_session, abnumber_job) -@patch("openprotein.align.api.get_msa") +@patch("openprotein.align.api._read_msa") @patch("openprotein.align.api.antibody_schema_get") def test_msa_future_get_warns_on_reported_warning( - mock_schema_get, mock_get_msa, abnumber_future: MSAFuture + mock_schema_get, mock_read_msa, abnumber_future: MSAFuture ): """Fetching the results surfaces what the job reported about them.""" mock_schema_get.return_value = { @@ -179,13 +180,13 @@ def test_msa_future_get_warns_on_reported_warning( with pytest.warns(UserWarning, match="UNNUMBERED_RESIDUES_DROPPED"): abnumber_future.get() - mock_get_msa.assert_called_once() + mock_read_msa.assert_called_once() -@patch("openprotein.align.api.get_msa") +@patch("openprotein.align.api._read_msa") @patch("openprotein.align.api.antibody_schema_get") def test_msa_future_wait_warns_on_reported_warning( - mock_schema_get, mock_get_msa, abnumber_future: MSAFuture + mock_schema_get, mock_read_msa, abnumber_future: MSAFuture ): """`wait` reaches the results through `get`, so it warns too.""" mock_schema_get.return_value = { @@ -200,10 +201,10 @@ def test_msa_future_wait_warns_on_reported_warning( abnumber_future.wait() -@patch("openprotein.align.api.get_msa") +@patch("openprotein.align.api._read_msa") @patch("openprotein.align.api.antibody_schema_get") def test_msa_future_get_warns_once_per_future( - mock_schema_get, mock_get_msa, abnumber_future: MSAFuture + mock_schema_get, mock_read_msa, abnumber_future: MSAFuture ): """The schema is fetched once, however many times the results are read.""" mock_schema_get.return_value = { @@ -220,10 +221,10 @@ def test_msa_future_get_warns_once_per_future( mock_schema_get.assert_called_once() -@patch("openprotein.align.api.get_msa") +@patch("openprotein.align.api._read_msa") @patch("openprotein.align.api.antibody_schema_get") def test_msa_future_get_silent_without_warnings( - mock_schema_get, mock_get_msa, abnumber_future: MSAFuture + mock_schema_get, mock_read_msa, abnumber_future: MSAFuture ): """A job that reported nothing warns about nothing.""" mock_schema_get.return_value = {"chains": [], "warnings": []} @@ -235,10 +236,10 @@ def test_msa_future_get_silent_without_warnings( assert caught == [] -@patch("openprotein.align.api.get_msa") +@patch("openprotein.align.api._read_msa") @patch("openprotein.align.api.antibody_schema_get") def test_msa_future_get_skips_schema_for_other_methods( - mock_schema_get, mock_get_msa, msa_future: MSAFuture + mock_schema_get, mock_read_msa, msa_future: MSAFuture ): """Only AbNumber jobs have an antibody schema to read.""" msa_future.get() @@ -246,10 +247,10 @@ def test_msa_future_get_skips_schema_for_other_methods( mock_schema_get.assert_not_called() -@patch("openprotein.align.api.get_msa") +@patch("openprotein.align.api._read_msa") @patch("openprotein.align.api.antibody_schema_get") def test_msa_future_get_survives_unreachable_schema( - mock_schema_get, mock_get_msa, abnumber_future: MSAFuture + mock_schema_get, mock_read_msa, abnumber_future: MSAFuture ): """Results stay readable when the schema endpoint does not answer.""" mock_schema_get.side_effect = APIError("no such endpoint") @@ -259,4 +260,4 @@ def test_msa_future_get_survives_unreachable_schema( abnumber_future.get() assert caught == [] - mock_get_msa.assert_called_once() + mock_read_msa.assert_called_once() diff --git a/tests/align/test_align_schemas.py b/tests/align/test_align_schemas.py index d80c811..1889f59 100644 --- a/tests/align/test_align_schemas.py +++ b/tests/align/test_align_schemas.py @@ -1,23 +1,20 @@ import pytest from pydantic import ValidationError -from openprotein.jobs import JobStatus, JobType from openprotein.align.schemas import ( - PromptPostParams, - MSASamplingMethod, - MSAJob, - MafftJob, - ClustalOJob, AbNumberJob, + ClustalOJob, + MafftJob, + MSAJob, + MSASamplingMethod, + PromptPostParams, ) +from openprotein.jobs import JobStatus, JobType -# =================================== # PromptPostParams Schema Tests -# =================================== def test_prompt_post_params_valid_defaults(): - """Test PromptPostParams with only required fields, relying on defaults.""" params = PromptPostParams( msa_id="msa123", num_sequences=10, @@ -34,7 +31,6 @@ def test_prompt_post_params_valid_defaults(): def test_prompt_post_params_valid_all_fields(): - """Test PromptPostParams with all fields provided.""" data = { "msa_id": "msa123", "num_sequences": 50, @@ -52,7 +48,6 @@ def test_prompt_post_params_valid_all_fields(): def test_prompt_post_params_invalid_range(): - """Test PromptPostParams with out-of-range values.""" with pytest.raises(ValidationError): PromptPostParams( msa_id="msa123", @@ -84,13 +79,8 @@ def test_prompt_post_params_invalid_range(): ) -# =================================== # Job Schemas Tests -# =================================== - - def create_base_job_dict(job_id: str, status: JobStatus) -> dict: - """Helper to create a base dictionary for a Job.""" return { "job_id": job_id, "status": status, @@ -101,7 +91,6 @@ def create_base_job_dict(job_id: str, status: JobStatus) -> dict: def test_msa_job_schema(): - """Test the MSAJob schema.""" job_dict = create_base_job_dict("job1", JobStatus.SUCCESS) job_dict["job_type"] = JobType.align_align @@ -110,8 +99,15 @@ def test_msa_job_schema(): assert msa_job.job_type == JobType.align_align +def test_msa_job_msa_id_is_the_jobs_msa_id_or_its_job_id(): + job_dict = create_base_job_dict("job1", JobStatus.SUCCESS) + job_dict["job_type"] = JobType.align_align + + assert MSAJob.model_validate(job_dict).msa_id == "job1" + assert MSAJob.model_validate({**job_dict, "msa_id": "msa-1"}).msa_id == "msa-1" + + def test_mafft_job_schema(): - """Test the MafftJob schema.""" job_dict = create_base_job_dict("job2", JobStatus.RUNNING) job_dict["job_type"] = JobType.mafft @@ -121,7 +117,6 @@ def test_mafft_job_schema(): def test_clustalo_job_schema(): - """Test the ClustalOJob schema.""" job_dict = create_base_job_dict("job3", JobStatus.FAILURE) job_dict["job_type"] = JobType.clustalo @@ -131,7 +126,6 @@ def test_clustalo_job_schema(): def test_abnumber_job_schema(): - """Test the AbNumberJob schema.""" job_dict = create_base_job_dict("job4", JobStatus.PENDING) job_dict["job_type"] = JobType.abnumber @@ -141,7 +135,6 @@ def test_abnumber_job_schema(): def test_job_schema_invalid_type(): - """Test that validation fails for an incorrect job_type.""" job_dict = create_base_job_dict("job1", JobStatus.SUCCESS) job_dict["job_type"] = "not_a_real_type" # Invalid type diff --git a/tests/align/test_input_deprecations.py b/tests/align/test_input_deprecations.py new file mode 100644 index 0000000..40f70ce --- /dev/null +++ b/tests/align/test_input_deprecations.py @@ -0,0 +1,151 @@ +"""The legacy align input reads are deprecated and keep working.""" + +import time +import warnings +from unittest.mock import MagicMock, patch + +import pytest +import requests + +from openprotein import auth_store +from openprotein.align import api +from openprotein.align.future import AlignFuture +from openprotein.align.schemas import AlignType +from openprotein.base import APISession +from openprotein.jobs import Job +from tests.conf import BACKEND + +MSA_TEXT = ( + "`MSAFuture.wait()` for the generated MSA, or " + "`session.data.MSA(id=...).to_string()`" +) +PROMPT_TEXT = ( + "`Prompt.get()` for the replicates of a sampled prompt, indexed by replicate" +) +API_SEED_TEXT = ( + "`openprotein.align.api.get_seed` for an MSA job's seed; the input of other " + "align jobs has no read of its own, so keep your own copy of the submitted " + "sequences" +) +FUTURE_SEED_TEXT = "`MSAFuture.get_seed()` for the seed" +INPUT_TYPES = (AlignType.MSA, AlignType.PROMPT, AlignType.INPUT) +SERVER_WARNING = "GET /align/inputs is deprecated" +JOB = Job.model_validate( + { + "job_id": "job123", + "status": "SUCCESS", + "job_type": "/align/align", + "created_date": "2023-01-01T00:00:00", + } +) + + +@pytest.fixture +def session(tmp_path, monkeypatch): + monkeypatch.setattr( + "openprotein.base.TokenStore", + lambda *a, **k: auth_store.TokenStore(dir=tmp_path), + ) + login = MagicMock(status_code=200, ok=True, headers={}) + login.json.return_value = { + "access_token": "access", + "refresh_token": "refresh", + "expires_in": 900, + } + with patch.object(APISession, "post", return_value=login): + session = APISession("user@x.com", "pw", backend=BACKEND) + session._expires_at = time.time() + 10_000 + return session + + +def _inputs_response() -> MagicMock: + response = MagicMock( + status_code=200, + ok=True, + headers={ + "Content-Type": "text/x-fasta", + "Warning": f'299 - "{SERVER_WARNING}"', + }, + ) + response.iter_lines.return_value = iter([">a", "MKT", ">b", "MKV"]) + return response + + +def _future(session) -> AlignFuture: + future = AlignFuture() + future.session = session + future.job = JOB + return future + + +CALLS = { + "api.get_align_job_inputs": ( + "openprotein.align.api.get_align_job_inputs", + lambda s, t: api.get_align_job_inputs(s, "job123", t), + ), + "api.get_input": ( + "openprotein.align.api.get_input", + lambda s, t: list(api.get_input(s, "job123", t)), + ), + "AlignFuture.get_input": ( + "openprotein.align.future.AlignFuture.get_input", + lambda s, t: list(_future(s).get_input(t)), + ), +} + + +@pytest.mark.parametrize("input_type", INPUT_TYPES, ids=lambda t: t.name) +@pytest.mark.parametrize("name", CALLS) +def test_a_legacy_input_read_warns_once_with_the_replacement_for_its_input_type( + session, name, input_type +): + """Each legacy input read emits one versioned warning naming its mode's replacement.""" + qualified, call = CALLS[name] + replacement = { + AlignType.MSA: MSA_TEXT, + AlignType.PROMPT: PROMPT_TEXT, + AlignType.INPUT: ( + FUTURE_SEED_TEXT if name == "AlignFuture.get_input" else API_SEED_TEXT + ), + }[input_type] + with ( + patch.object(requests.Session, "request", return_value=_inputs_response()), + warnings.catch_warnings(record=True) as caught, + ): + warnings.simplefilter("always") + call(session, input_type) + messages = [str(w.message) for w in caught if w.category is FutureWarning] + assert messages == [ + ( + f"`{qualified}` is deprecated since 0.18.0 and will be removed in " + f"0.19.0. Use {replacement}." + ) + ] + + +def test_the_legacy_input_reads_keep_their_return_values(session): + """The deprecated reads still return the response and the parsed pairs.""" + with ( + patch.object(requests.Session, "request", return_value=_inputs_response()), + warnings.catch_warnings(), + ): + warnings.simplefilter("ignore", FutureWarning) + pairs = list(api.get_input(session, "job123", AlignType.MSA)) + response = api.get_align_job_inputs(session, "job123", AlignType.MSA) + assert pairs == [("a", "MKT"), ("b", "MKV")] + assert response.ok + + +def test_get_seed_is_not_deprecated(session): + """`get_seed` emits no deprecation warning and surfaces server warnings.""" + response = MagicMock( + status_code=200, ok=True, headers={"Warning": f'299 - "{SERVER_WARNING}"'} + ) + response.json.return_value = {"sequence": "MKT"} + with ( + patch.object(requests.Session, "request", return_value=response), + warnings.catch_warnings(record=True) as caught, + ): + warnings.simplefilter("always") + api.get_seed(session, "job123") + assert [str(w.message) for w in caught] == [SERVER_WARNING] diff --git a/tests/align/test_msa_read.py b/tests/align/test_msa_read.py new file mode 100644 index 0000000..efbd281 --- /dev/null +++ b/tests/align/test_msa_read.py @@ -0,0 +1,136 @@ +"""A generated MSA is read from the stored MSA in the format its job type names.""" + +import inspect +from datetime import datetime +from unittest.mock import MagicMock + +import pytest + +from openprotein.align import api +from openprotein.align.msa import MSAFuture +from openprotein.align.schemas import AbNumberJob, ClustalOJob, MafftJob, MSAJob +from openprotein.errors import HTTPError + +A3M = b"#12\t1\n>query\nMKTAYIAKQR\n>hit_1\nMKT-YIAkqR\n>hit_2\nMKTAYIA\nKQR\n" +FASTA = b">query\nMKTAYIAKQR\n>hit_1\nMKT-YIAKQR\n" + + +def _job_json(job_type: str) -> dict: + return { + "job_id": "msa1", + "job_type": job_type, + "status": "SUCCESS", + "created_date": datetime(2023, 1, 1).isoformat(), + } + + +def _stored(session: MagicMock, body: bytes, job_type: str = "/align/align") -> None: + """Serve the job record at ``v1/jobs/...`` and the MSA bytes elsewhere.""" + + def get(endpoint, **kwargs): + if endpoint.startswith("v1/jobs/"): + return MagicMock(status_code=200, json=lambda: _job_json(job_type)) + return MagicMock(status_code=200, content=body) + + session.get.side_effect = get + + +def _msa_request(session: MagicMock): + return next(c for c in session.get.call_args_list if "data/msa" in c.args[0]) + + +def test_get_msa_reads_the_stored_msa_as_names_and_sequences(mock_session): + """The a3m header is skipped and insertions and wrapped lines are kept.""" + _stored(mock_session, A3M) + pairs = list(api.get_msa(mock_session, "msa1")) + assert pairs == [ + ("query", "MKTAYIAKQR"), + ("hit_1", "MKT-YIAkqR"), + ("hit_2", "MKTAYIAKQR"), + ] + assert _msa_request(mock_session).kwargs["params"] == {"format": "a3m"} + + +def test_get_msa_reads_a_fasta_body(mock_session): + """A FASTA body reads as the same pairs.""" + _stored(mock_session, FASTA) + assert list(api.get_msa(mock_session, "msa1")) == [ + ("query", "MKTAYIAKQR"), + ("hit_1", "MKT-YIAKQR"), + ] + + +def test_get_msa_raises_the_session_error_for_a_missing_msa(mock_session): + """A 404 from the stored MSA raises `HTTPError` with that status.""" + _stored(mock_session, FASTA) + stored = mock_session.get.side_effect + missing = MagicMock(status_code=404, text="not found") + missing.url = "v1/data/msa/msa1" + + def get(endpoint, **kwargs): + if endpoint.startswith("v1/data/msa/"): + raise HTTPError(missing) + return stored(endpoint, **kwargs) + + mock_session.get.side_effect = get + with pytest.raises(HTTPError) as raised: + api.get_msa(mock_session, "msa1") + assert raised.value.status_code == 404 + assert "data/msa/msa1" in _msa_request(mock_session).args[0] + + +def test_an_msa_future_reads_its_msa_id_from_the_stored_msa(mock_session): + """`MSAFuture.get()` reads `v1/data/msa/` and parses it.""" + job = MSAJob.model_validate( + { + "job_id": "job1", + "job_type": "/align/align", + "status": "SUCCESS", + "created_date": datetime(2023, 1, 1).isoformat(), + } + ) + _stored(mock_session, A3M) + future = MSAFuture(mock_session, job) + assert next(iter(future.get())) == ("query", "MKTAYIAKQR") + assert mock_session.get.call_args.args[0] == f"v1/data/msa/{job.msa_id}" + + +@pytest.mark.parametrize( + ("job_type", "job_class", "expected"), + [ + ("/align/align", MSAJob, "a3m"), + ("/align/mafft", MafftJob, "fasta"), + ("/align/clustalo", ClustalOJob, "fasta"), + ("/align/abnumber", AbNumberJob, "fasta"), + ], +) +def test_an_msa_is_requested_in_the_format_its_job_type_names( + mock_session, job_type, job_class, expected +): + """`MSAFuture.get()` and `get_msa(job_id)` request the same format per job type.""" + body = A3M if expected == "a3m" else FASTA + _stored(mock_session, body, job_type) + job = job_class.model_validate(_job_json(job_type)) + + from_future = list(MSAFuture(mock_session, job).get()) + assert _msa_request(mock_session).kwargs["params"] == {"format": expected} + + mock_session.get.reset_mock() + from_id = list(api.get_msa(mock_session, "msa1")) + assert _msa_request(mock_session).kwargs["params"] == {"format": expected} + assert from_id == from_future + assert from_id[0] == ("query", "MKTAYIAKQR") + + +def test_reading_an_msa_with_its_format_makes_no_job_lookup(mock_session): + """`_read_msa` requests the MSA in the given format and nothing else.""" + _stored(mock_session, FASTA) + pairs = list(api._read_msa(mock_session, "msa1", "fasta")) + mock_session.get.assert_called_once() + assert _msa_request(mock_session).kwargs["params"] == {"format": "fasta"} + assert pairs[0] == ("query", "MKTAYIAKQR") + + +def test_get_msa_takes_a_session_and_a_job_id_only(): + """`get_msa` has the parameters `session` and `job_id`.""" + assert list(inspect.signature(api.get_msa).parameters) == ["session", "job_id"] diff --git a/tests/align/test_server_warnings.py b/tests/align/test_server_warnings.py new file mode 100644 index 0000000..b1e52fa --- /dev/null +++ b/tests/align/test_server_warnings.py @@ -0,0 +1,150 @@ +"""Server deprecation warnings on align calls that carry an SDK deprecation.""" + +import io +import threading +import time +import warnings +from unittest.mock import MagicMock, patch + +import pytest +import requests +from pydantic import ValidationError + +from openprotein import auth_store +from openprotein.align import api +from openprotein.base import APISession +from tests.conf import BACKEND + +SERVER_WARNING = "POST /align/prompt is deprecated; use POST /prompt/sample_msa" +JOB = { + "job_id": "job123", + "status": "PENDING", + "job_type": "/align/align", + "created_date": "2023-01-01T00:00:00", +} + + +@pytest.fixture +def session(tmp_path, monkeypatch): + monkeypatch.setattr( + "openprotein.base.TokenStore", + lambda *a, **k: auth_store.TokenStore(dir=tmp_path), + ) + login = MagicMock(status_code=200, ok=True, headers={}) + login.json.return_value = { + "access_token": "access", + "refresh_token": "refresh", + "expires_in": 900, + } + with patch.object(APISession, "post", return_value=login): + session = APISession("user@x.com", "pw", backend=BACKEND) + session._expires_at = time.time() + 10_000 + return session + + +def _answer(body: dict) -> MagicMock: + response = MagicMock( + status_code=200, + ok=True, + headers={"Warning": f'299 - "{SERVER_WARNING}"'}, + ) + response.json.return_value = body + return response + + +def _warnings(call) -> list[str]: + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + call() + return [str(w.message) for w in caught if issubclass(w.category, FutureWarning)] + + +def _send(session, body): + return patch.object(requests.Session, "request", return_value=_answer(body)) + + +def test_prompt_post_warns_only_with_its_own_deprecation(session): + """A deprecated `prompt_post` surfaces its SDK warning, not the server's.""" + with _send(session, JOB): + messages = _warnings(lambda: api.prompt_post(session, "msa1", num_sequences=5)) + assert len(messages) == 1 + assert "openprotein.align.api.prompt_post" in messages[0] + + +def test_msa_post_warns_only_with_its_own_deprecation(session): + """A deprecated `msa_post` surfaces its SDK warning, not the server's.""" + with _send(session, JOB): + messages = _warnings(lambda: api.msa_post(session, seed="MKT")) + assert len(messages) == 1 + assert "openprotein.align.api.msa_post" in messages[0] + + +def test_the_msa_file_upload_surfaces_no_server_warning(session): + """The upload helper behind `AlignAPI.upload_msa` surfaces no server warning.""" + with _send(session, JOB): + messages = _warnings(lambda: api._msa_post(session, io.BytesIO(b">a\nMKT"))) + assert messages == [] + + +def test_other_align_calls_surface_the_server_warning(session): + """A call without an SDK deprecation still surfaces the server's warning.""" + with _send(session, {"sequence": "MKT"}): + messages = _warnings(lambda: api.get_seed(session, "msa1")) + assert messages == [SERVER_WARNING] + + +def test_server_warnings_return_after_a_deprecated_call_fails(session): + """Calls after a failed deprecated call surface server warnings again.""" + with _send(session, {"sequence": "MKT"}): + with pytest.raises(ValidationError): + api.prompt_post(session, "msa1", num_sequences=5) + messages = _warnings(lambda: api.get_seed(session, "msa1")) + assert messages == [SERVER_WARNING] + + +def _by_url(responses: dict[str, MagicMock]): + def request(self, method, url, *args, **kwargs): + return next(r for suffix, r in responses.items() if url.endswith(suffix)) + + return patch.object(requests.Session, "request", request) + + +def test_a_token_refresh_inside_a_silenced_call_surfaces_its_server_warning(session): + """Only the silenced request drops the server warning, not a refresh it triggers.""" + session._expires_at = time.time() - 1 + refreshed = _answer( + {"access_token": "new", "refresh_token": "next", "expires_in": 900} + ) + with ( + patch.object(session._token_store, "load", return_value=None), + _by_url({"v1/auth/refresh": refreshed, "v1/align/msa": _answer(JOB)}), + ): + + def silenced_call(): + with api._silence_server_warnings(): + session.post("v1/align/msa") + + messages = _warnings(silenced_call) + assert messages == [SERVER_WARNING] + + +def test_a_call_on_another_thread_during_a_silenced_call_surfaces_its_warning( + session, +): + """Silencing applies to the calling thread's requests only.""" + other: list[str] = [] + + def on_another_thread(): + thread = threading.Thread( + target=lambda: other.extend( + _warnings(lambda: api.get_seed(session, "msa1")) + ) + ) + thread.start() + thread.join() + + with _send(session, {"sequence": "MKT"}), api._silence_server_warnings(): + on_another_thread() + inside = _warnings(lambda: api.get_seed(session, "msa1")) + assert inside == [] + assert other == [SERVER_WARNING] diff --git a/tests/clustering/test_clustering.py b/tests/clustering/test_clustering.py index 188b545..da48fc3 100644 --- a/tests/clustering/test_clustering.py +++ b/tests/clustering/test_clustering.py @@ -8,7 +8,6 @@ from openprotein.clustering.clustering import ClusteringAPI from openprotein.clustering.models import HierarchicalClusteringFuture from openprotein.clustering.schemas import ClusteringMetadata, HierarchicalFitJob -from openprotein.common import FeatureType from openprotein.embeddings import EmbeddingModel from openprotein.errors import InvalidParameterError from openprotein.jobs import JobsAPI, JobStatus diff --git a/tests/clustering/test_clustering_schemas.py b/tests/clustering/test_clustering_schemas.py index ed937e1..664bf11 100644 --- a/tests/clustering/test_clustering_schemas.py +++ b/tests/clustering/test_clustering_schemas.py @@ -28,8 +28,15 @@ def test_linkage_method_is_str(): def test_metric_values(): expected = { - "euclidean", "cosine", "correlation", "hamming", "chebyshev", - "cityblock", "sqeuclidean", "canberra", "braycurtis", + "euclidean", + "cosine", + "correlation", + "hamming", + "chebyshev", + "cityblock", + "sqeuclidean", + "canberra", + "braycurtis", } assert {m.value for m in Metric} == expected @@ -109,7 +116,5 @@ def test_clustering_result_linkage_becomes_ndarray(): def test_clustering_result_accepts_ndarray(): arr = np.asarray([[0.0, 1.0, 0.12, 2.0]]) - r = HierarchicalClusteringResult( - n_leaves=2, linkage=arr, leaf_order=[0, 1] - ) + r = HierarchicalClusteringResult(n_leaves=2, linkage=arr, leaf_order=[0, 1]) assert r.linkage is arr diff --git a/tests/codecs/fixtures/msa_multichain_chain_copies.parquet b/tests/codecs/fixtures/msa_multichain_chain_copies.parquet new file mode 100644 index 0000000000000000000000000000000000000000..aa4d703eefccf75eaf15d2e341d805218b39fe52 GIT binary patch literal 1234 zcmZ`(U2oD*7(NBk!GdNpwrLYCFmYrtu+eUqxy*~h$Cw!);8s9mNLxNlTd>d#cI9vJ z+FSpE_ul&pc4fRb@qJGROx;d$+V|sm-{(1RIaFy~5kf*%I4cRfKpqjY{dM`a?;vO>Eu%7ERLIU9M zTp;+A0BKb){vzF`9Ekv+d|J{DX)a$_XO7OiQ~^^dSS)o1_j>ts0hJ<4;QjpaQHDtT z#2j>OT?i2&x)qQ@j&66iNGS$fED)Y_KYCrqTm(g4j>*Xci3w3TL--BZFA<_5FMi|1 zYc4TMgzue%oP=W&Awb}<0k0$Rnas-xg7dxIbIHp3{@}z1;unXV?>*=L-4B-C z#m_;JPlUzmAdxNUp?~W3Mc17SM~)O!c2pugn2bEv?6!L&*Vd;}P~WqOwCQ+u8(eeH zHb<6cI}?dJ04#(_Ej$vH-Z1zr^W5RmMk-;aeEYGn3^TRp6VgeBhz< zcrq{L=&T9hJmQO$QLABjO|^1i7A?zUbh!dbWlel3sF{{oE)7=J>ok;}scN%ML-Sgy zc7=JD@u7u!VIg&%>8+z{ING$SDuWJiBA;=hO%11vpw>TpOj_%#GNqL9T^W1Y9C&(f z?H6;Sag0Hl14&2%?^o!rNd2Rg-|WwEzM%K2r4B5p>ve2xZmQOWfwFKHR`XF%Kc2C6 z&Vnaku093hqx7U=nN7_y?25(GRx*MlwY?#G5&%nXdiIcw#Y uFzS~?ijQ>{F5om}j>jq8bw`)+n;&gl-QP*?q~#>sRlKg>gM?J!-|P?D5haKK literal 0 HcmV?d00001 diff --git a/tests/codecs/fixtures/msa_single_chain_annotated.parquet b/tests/codecs/fixtures/msa_single_chain_annotated.parquet new file mode 100644 index 0000000000000000000000000000000000000000..391fac6afb285d30372755649684b9f6da4185f5 GIT binary patch literal 2178 zcmb_eOK%%h6uvWdjDymuNtw}Dgvbo-5VdjQ8QW=H6^ZLdl1XgGaq0&NQRKv>1l{&72ez;ga^UL@t#`*AS??Xo`dlAkAw^+z$3d6%9Lnm zgJwcJdF;RbyZ?%k6IrmAqzUHsk}A(R;cG4f<;GO?cX;x`a~BHj?#ijOybzR!@Y@}y zTeEC=Zy~rV(_~)NBGH(oyV|PVCYf0P$`pRL22HTd zb4tGMp7r7DoslT|0<(dPLS}`jK#cfq1cnKPDbXkX#))6>%IBQof8_`U7H|Lr07+nI zdGb(P4)_8J@d2u{$;aSWf$ur-XHNNpSH9x0!o`WZoOJHWq(F|P`(oX&Ttt=AuG!<&-opS>dhe-RSivnB3>F6i z^xEErLbiLlNY98gMGJ+^@`E92=}X@de!?_KDcynxKO2-rX`)V7D6P|Eo#_&ZbM`(e z(_{Mz1vAPNRabiRY&1yMnRZ3xq)iK`Q0WOU^q#l4c;>Ws_ zLcBDGhhdkxl}N5>R!U8y1>eYO;|bzn{bYECtx?fGjoQ_iYLw#Lk1BPq~`&<3he zjy*xUcCjAjTg!!w{;-~@#Z?pPRJ5IAv!yl;FbM7`#qhy>p?Ib!#rRaZm#x!HG?`k? z*(s}yN@S;L+PSu&VcQT?vWWH)9!YjJ?7of=4~knw#s`K11$MFn?|b#&1d2w%bIJXG z{=hY9qQ82V}@-Dn>^YH8AUm+m;XaE2J literal 0 HcmV?d00001 diff --git a/tests/codecs/fixtures/prompt_sequences_only.npz b/tests/codecs/fixtures/prompt_sequences_only.npz new file mode 100644 index 0000000000000000000000000000000000000000..3b3510543e70e01a5e74c80c02d78a2adcae9113 GIT binary patch literal 451 zcmWIWW@gc4U|`??Vnqhm&WrEA*ONei4j5pXPE?Yv1*b7Gd{EnN^7oV8-z;sx`j#fJnpptntrTZ;^``4OPGF2O|zP1#kG}7gh4Mpf4+fxy0&;YLja1Sm^B(^!W<=v?x>v9 zykeM}CP3Zdh0jfSlQS0*a+4d}O=4^u39Xla4q{}|WkwArkk3J(AO^J!L^UviNbI48 pZU)F(AeVw%Eeg^G1r3Z-fh-g=V4e){W@Q7ZVgkZ;Agu?EU=r{N*+ z>4Tq)O22id!ck`@6{ST^PA)Z?`+D5mj~{c}|BFqeU9N6E`@Ht_O1t%WdTSr`*_@bM zc4xt(*IO>l%nFkB3YV_Cy#4)qseO<2zE|#++wrD(*4v$DK28pH)-BFivF+BXZ>gaV zCC{pG7#&^YYeVYh7V*Sa0E6Z_)-I2I}GzHyjQ$>NCMqJR!XK4wmp ziB4>4=K>F~>cl)2Q=Rf~L7SD0$;S>cr;?97a=$7LYTx_N$6u4!kk4ayNMiDxwEh3* zv!X_$%fs7$VWB3B5^4oGDJdneNZbMqr)2z*n6`*eBqF6QHa32Bwl)a`J%&eW3hx*n zWjgF(=m=;0D5hW+(BH!t;LXUS%Z!>8K#3ca(8Zw608tH$AQF4VKsN)FXhG=^lqN+% z+Mu9;aTbt;Vg@V;qZK+g#d3>Hjp|NAmj(y#K{ce0RY|7VD$h1 literal 0 HcmV?d00001 diff --git a/tests/codecs/test_codec_fixtures.py b/tests/codecs/test_codec_fixtures.py new file mode 100644 index 0000000..aa4e810 --- /dev/null +++ b/tests/codecs/test_codec_fixtures.py @@ -0,0 +1,129 @@ +"""Fixture files written by the server's codecs decode identically here.""" + +import io +from pathlib import Path + +import numpy as np +import pytest + +from openprotein.codecs import MSA, MSARecord, msa_parquet_v1, prompt_npz_v1 + +pq = pytest.importorskip("pyarrow.parquet") + +FIXTURES = Path(__file__).parent / "fixtures" + +SINGLE_CHAIN = MSA( + records=[ + MSARecord( + name="query desc\twith tab", + sequence="MK-LV", + annotations=[("DE", "query protein"), ("AC", "P12345")], + column_annotations={"SS": "HH-EE", "PP": "99*87"}, + ), + MSARecord(name="hit1", sequence="MKALV"), + MSARecord(name="hit2", sequence="-KAL-", annotations=[("DE", "second hit")]), + ], + source_format="sto", + num_match_columns=5, + annotations=[("ID", "fixture"), ("AU", "openprotein")], + column_annotations={"RF": "xx.xx", "SS_cons": "HH-EE"}, +) +MULTICHAIN = MSA( + records=[ + MSARecord(name="101\t102", sequence="MKLV:ACDE"), + MSARecord(name="paired", sequence="MKaLV:AC-E"), + MSARecord(name="unpaired", sequence="----:ACDE"), + ], + source_format="a3m", + num_match_columns=8, + chain_copies=[2, 1], +) + + +@pytest.mark.parametrize( + "filename, expected, footer_keys", + [ + ( + "msa_single_chain_annotated.parquet", + SINGLE_CHAIN, + {"gf", "gc"}, + ), + ( + "msa_multichain_chain_copies.parquet", + MULTICHAIN, + {"chain_copies"}, + ), + ], +) +def test_msa_parquet_fixture_decodes_and_reencodes(filename, expected, footer_keys): + data = (FIXTURES / filename).read_bytes() + decoded = msa_parquet_v1.decode(data) + assert decoded == expected + assert msa_parquet_v1.decode(msa_parquet_v1.encode(decoded)) == expected + + for payload in (data, msa_parquet_v1.encode(decoded)): + parquet = pq.ParquetFile(io.BytesIO(payload)) + metadata = parquet.schema_arrow.metadata + assert set(metadata) == { + b"schema_version", + b"source_format", + b"num_match_columns", + b"num_sequences", + } | {key.encode() for key in footer_keys} + assert metadata[b"schema_version"] == b"1.2" + assert metadata[b"num_sequences"] == str(expected.num_sequences).encode() + assert parquet.metadata.row_group(0).column(0).compression == "ZSTD" + + +def test_msa_parquet_fixture_columns(): + single = pq.read_table(FIXTURES / "msa_single_chain_annotated.parquet") + multi = pq.read_table(FIXTURES / "msa_multichain_chain_copies.parquet") + assert single.column_names == ["name", "sequence", "gs", "gr"] + assert multi.column_names == ["name", "sequence"] + + +def _assert_prompt_round_trips(data): + decoded = prompt_npz_v1.decode(data) + again = prompt_npz_v1.decode(prompt_npz_v1.encode(decoded)) + for left, right in zip(decoded.complexes, again.complexes, strict=True): + assert left.sequence == right.sequence + for a, b in ((left.coordinates, right.coordinates), (left.plddt, right.plddt)): + assert (a is None) == (b is None) + if a is not None: + np.testing.assert_array_equal(a, b) + return decoded + + +def test_prompt_npz_fixture_with_coordinates(): + data = (FIXTURES / "prompt_with_coordinates.npz").read_bytes() + decoded = _assert_prompt_round_trips(data) + first, second = decoded.complexes + assert (first.sequence, second.sequence) == ("MK:LVACDE", "GHIK") + + coordinates = np.arange(81, dtype=np.float32).reshape(9, 3, 3) + coordinates[2] = np.nan + np.testing.assert_array_equal(first.coordinates, coordinates) + np.testing.assert_array_equal(first.plddt, np.linspace(50, 90, 9, dtype=np.float32)) + assert second.coordinates is not None and second.coordinates.shape == (4, 3, 3) + assert np.isnan(second.coordinates).all() + assert second.plddt is not None and np.isnan(second.plddt).all() + + with np.load(FIXTURES / "prompt_with_coordinates.npz") as npz: + assert sorted(npz.files) == [ + "context_0_coordinates", + "context_0_plddt", + "context_0_seqlens", + "context_0_sequence", + ] + np.testing.assert_array_equal(npz["context_0_seqlens"], [9, 4]) + + +def test_prompt_npz_fixture_sequences_only(): + data = (FIXTURES / "prompt_sequences_only.npz").read_bytes() + decoded = _assert_prompt_round_trips(data) + assert [c.sequence for c in decoded.complexes] == ["MKLV", "AC:DE"] + assert all(c.coordinates is None and c.plddt is None for c in decoded.complexes) + + with np.load(FIXTURES / "prompt_sequences_only.npz") as npz: + assert sorted(npz.files) == ["context_0_seqlens", "context_0_sequence"] + assert npz["context_0_sequence"].dtype == np.uint8 diff --git a/tests/codecs/test_codecs.py b/tests/codecs/test_codecs.py new file mode 100644 index 0000000..6059d4b --- /dev/null +++ b/tests/codecs/test_codecs.py @@ -0,0 +1,250 @@ +import subprocess +import sys +import textwrap + +import numpy as np +import pytest + +from openprotein import codecs +from openprotein.codecs import ( + MSA, + Codec, + InvalidPrompt, + MSARecord, + PromptComplex, + PromptReplicate, + fasta_utf8_v1, + json_utf8_v1, + mmcif_utf8_v1, + msa_parquet_v1, + ndarray_v1, + prompt_npz_v1, +) + + +@pytest.mark.parametrize( + "codec", + [ + ndarray_v1, + mmcif_utf8_v1, + fasta_utf8_v1, + json_utf8_v1, + msa_parquet_v1, + prompt_npz_v1, + ], + ids=lambda codec: codec.name, +) +def test_builtins_are_registered_by_name(codec): + assert codecs.get(codec.name) is codec + + +def test_get_returns_none_for_unknown_name(): + assert codecs.get("unknown-v1") is None + + +def test_register_binds_a_name_to_one_codec(): + codec = Codec(name="test/register@v1", encode=bytes, decode=bytes) + codecs._register(codec) + codecs._register(codec) + assert codecs.get("test/register@v1") is codec + with pytest.raises(ValueError, match="already registered"): + codecs._register(Codec(name="test/register@v1", encode=bytes, decode=bytes)) + with pytest.raises(ValueError, match="already registered"): + codecs._register(Codec(name="ndarray-v1", encode=bytes, decode=bytes)) + + +def test_ndarray_v1_encodes_npy_bytes(): + header = b"{'descr': 'q é\nMK\n") == b">q \xc3\xa9\nMK\n" + assert codec.decode(b">q \xc3\xa9\nMK\n") == ">q é\nMK\n" + + +@pytest.mark.parametrize( + "codec", [mmcif_utf8_v1, fasta_utf8_v1], ids=lambda codec: codec.name +) +def test_text_codecs_reject_invalid_utf8(codec): + with pytest.raises(UnicodeDecodeError): + codec.decode(b"\xff") + + +def test_json_utf8_v1_encodes_compact_utf8(): + assert json_utf8_v1.encode({"a": [1, 2.5, None], "é": True}) == ( + b'{"a":[1,2.5,null],"\\u00e9":true}' + ) + + +@pytest.mark.parametrize( + "value", + [ + [{"chain_ids": ["A", "B"], "ptm": 0.5, "iptm": None}], + {"nested": {"list": [[1, 2], [3.25, None]]}}, + None, + "text", + ], +) +def test_json_utf8_v1_round_trips(value): + assert json_utf8_v1.decode(json_utf8_v1.encode(value)) == value + + +@pytest.mark.parametrize("value", [float("nan"), float("inf"), [1.0, -float("inf")]]) +def test_json_utf8_v1_refuses_non_finite_numbers(value): + with pytest.raises(ValueError): + json_utf8_v1.encode(value) + + +def test_json_utf8_v1_rejects_invalid_utf8(): + with pytest.raises(UnicodeDecodeError): + json_utf8_v1.decode(b'"\xff"') + + +def test_msa_parquet_v1_round_trips(): + pytest.importorskip("pyarrow") + msa = MSA( + records=[ + MSARecord("q", "MKLV", [("DE", "x")], {"SS": "HHEE"}), + MSARecord("h", "MK-v"), + ], + source_format="sto", + num_match_columns=4, + annotations=[("ID", "a")], + column_annotations={"RF": "xxxx"}, + chain_copies=[1], + ) + assert msa_parquet_v1.decode(msa_parquet_v1.encode(msa)) == msa + + +def test_prompt_npz_v1_round_trips(): + coordinates = np.ones((4, 3, 3), dtype=np.float32) + plddt = np.full(4, 70.0, dtype=np.float32) + replicate = prompt_npz_v1.decode( + prompt_npz_v1.encode( + PromptReplicate( + [PromptComplex("MK:L", coordinates, plddt), PromptComplex("AC")] + ) + ) + ) + first, second = replicate.complexes + assert (first.sequence, second.sequence) == ("MK:L", "AC") + np.testing.assert_array_equal(first.coordinates, coordinates) + np.testing.assert_array_equal(first.plddt, plddt) + assert second.coordinates is not None and np.isnan(second.coordinates).all() + assert second.plddt is not None and np.isnan(second.plddt).all() + + +def test_prompt_npz_v1_round_trips_names(): + replicate = prompt_npz_v1.decode( + prompt_npz_v1.encode( + PromptReplicate( + [ + PromptComplex("MK:L", name="UniRef100_A0A8B9J8Y4"), + PromptComplex("AC"), + ] + ) + ) + ) + + assert [c.name for c in replicate.complexes] == ["UniRef100_A0A8B9J8Y4", None] + + +def test_prompt_npz_v1_writes_no_names_for_unnamed_complexes(): + import io + + data = prompt_npz_v1.encode(PromptReplicate([PromptComplex("MK")])) + + with np.load(io.BytesIO(data), allow_pickle=False) as npz: + assert "context_0_names" not in npz.files + + +def test_prompt_npz_v1_rejects_names_that_do_not_match_the_complexes(): + import io + + buf = io.BytesIO() + np.savez( + buf, + context_0_sequence=np.frombuffer(b"MKLV", dtype=np.uint8), + context_0_seqlens=np.array([2, 2], dtype=np.int64), + context_0_names=np.array(["only-one"], dtype=np.str_), + ) + with pytest.raises(InvalidPrompt, match="names"): + prompt_npz_v1.decode(buf.getvalue()) + + +def test_prompt_npz_v1_rejects_an_empty_replicate(): + with pytest.raises(InvalidPrompt): + prompt_npz_v1.encode(PromptReplicate([])) + + +def test_prompt_npz_v1_rejects_seqlens_that_do_not_sum_to_the_sequence(): + import io + + buf = io.BytesIO() + np.savez( + buf, + context_0_sequence=np.frombuffer(b"MKLV", dtype=np.uint8), + context_0_seqlens=np.array([3], dtype=np.int64), + ) + with pytest.raises(InvalidPrompt, match="sum"): + prompt_npz_v1.decode(buf.getvalue()) + + +def test_import_does_not_require_pyarrow(): + script = textwrap.dedent( + """ + import sys + sys.modules["pyarrow"] = None + import openprotein.codecs as codecs + msa = codecs.MSA(records=[], source_format="a3m", num_match_columns=0) + try: + codecs.msa_parquet_v1.encode(msa) + except ImportError as exc: + assert "openprotein-python[msa]" in str(exc), exc + else: + raise AssertionError("expected ImportError") + """ + ) + subprocess.run([sys.executable, "-c", script], check=True) diff --git a/tests/conftest.py b/tests/conftest.py index 7267f1d..64a017e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -7,8 +7,8 @@ @pytest.fixture def mock_session(): - """Returns a MagicMock to be used as a session object.""" session = MagicMock(spec=APISession) + session.timeout = 180 # To handle cases where the mock is used in a context manager session.__enter__.return_value = session return session diff --git a/tests/context.py b/tests/context.py index cdd7a78..b7452a6 100644 --- a/tests/context.py +++ b/tests/context.py @@ -3,7 +3,5 @@ # Add the project root directory to the Python path sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) - # Now you can import your project modules # For example: -# from openprotein import jobs diff --git a/tests/data/ensemble_cards.json b/tests/data/ensemble_cards.json new file mode 100644 index 0000000..d650a59 --- /dev/null +++ b/tests/data/ensemble_cards.json @@ -0,0 +1,67 @@ +{ + "bioemu-v1-1": { + "input_types": [ + "protein" + ], + "multichain": false, + "tags": [ + "structure", + "ensemble" + ], + "variant": null, + "base": true, + "max_sequence_length": 600 + }, + "alphaflow-md-base-v1": { + "input_types": [ + "protein" + ], + "multichain": false, + "tags": [ + "structure", + "ensemble" + ], + "variant": null, + "base": true, + "max_sequence_length": 600 + }, + "alphaflow-md-distilled-v1": { + "input_types": [ + "protein" + ], + "multichain": false, + "tags": [ + "structure", + "ensemble" + ], + "variant": "distilled", + "base": false, + "max_sequence_length": 600 + }, + "esmflow-md-base-v1": { + "input_types": [ + "protein" + ], + "multichain": false, + "tags": [ + "structure", + "ensemble" + ], + "variant": null, + "base": true, + "max_sequence_length": 600 + }, + "esmflow-md-distilled-v1": { + "input_types": [ + "protein" + ], + "multichain": false, + "tags": [ + "structure", + "ensemble" + ], + "variant": "distilled", + "base": false, + "max_sequence_length": 600 + } +} diff --git a/tests/data/model_result_contracts/quoted_predictions.csv b/tests/data/model_result_contracts/quoted_predictions.csv new file mode 100644 index 0000000..9fc203e --- /dev/null +++ b/tests/data/model_result_contracts/quoted_predictions.csv @@ -0,0 +1,2 @@ +"sequence","00000000-0000-0000-0000-000000000002:a""b:p""q:y_mu","00000000-0000-0000-0000-000000000002:a""b:p""q:y_var" +AA,1.5,2.5 diff --git a/tests/data/model_result_contracts/quoted_predictions.json b/tests/data/model_result_contracts/quoted_predictions.json new file mode 100644 index 0000000..1c73a08 --- /dev/null +++ b/tests/data/model_result_contracts/quoted_predictions.json @@ -0,0 +1,8 @@ +[ + { + "p\"q": { + "mean": 1.5, + "variance": 2.5 + } + } +] diff --git a/tests/data/model_result_contracts/replicate_none.npy b/tests/data/model_result_contracts/replicate_none.npy new file mode 100644 index 0000000000000000000000000000000000000000..b1ad31f7ae56fad1a00051d0fca22273bb2f7cb2 GIT binary patch literal 132 zcmbR27wQ`j$;eQ~P_3SlTAW;@Zl$1ZlV+r@qoAIaUsO_*m=~X4l#&V(cT3DEP6dh= ZXCxM+0{I$7I+{8PwF(pfE(RNh0|3C298&-Q literal 0 HcmV?d00001 diff --git a/tests/data/model_result_contracts/replicate_one.npy b/tests/data/model_result_contracts/replicate_one.npy new file mode 100644 index 0000000000000000000000000000000000000000..b1ad31f7ae56fad1a00051d0fca22273bb2f7cb2 GIT binary patch literal 132 zcmbR27wQ`j$;eQ~P_3SlTAW;@Zl$1ZlV+r@qoAIaUsO_*m=~X4l#&V(cT3DEP6dh= ZXCxM+0{I$7I+{8PwF(pfE(RNh0|3C298&-Q literal 0 HcmV?d00001 diff --git a/tests/data/model_result_contracts/replicate_selected.npy b/tests/data/model_result_contracts/replicate_selected.npy new file mode 100644 index 0000000000000000000000000000000000000000..eda9a95d962028c382a82d6a3dc1750928d5f03c GIT binary patch literal 132 zcmbR27wQ`j$;eQ~P_3SlTAW;@Zl$1ZlV+r@qoAIaUsO_*m=~X4l#&V(cT3DEP6dh= ZXCxM+0{I$7I+{8PwF(pfE(RwC7XZL18{Gf^ literal 0 HcmV?d00001 diff --git a/tests/data/model_result_contracts/replicate_two.npy b/tests/data/model_result_contracts/replicate_two.npy new file mode 100644 index 0000000000000000000000000000000000000000..91763237d326dd25fc11c61f2beab5fa40c49643 GIT binary patch literal 136 zcmbR27wQ`j$;eQ~P_3SlTAW;@Zl$1ZlV+r@qoAIaUsO_*m=~X4l#&V(cT3DEP6dh= fXCxM+0{I$7ItoUbItsN4WCJb+8-@c6P7E#pHzXYE literal 0 HcmV?d00001 diff --git a/tests/data/models_params.json b/tests/data/models_params.json new file mode 100644 index 0000000..d74c727 --- /dev/null +++ b/tests/data/models_params.json @@ -0,0 +1,9847 @@ +{ + "fits": { + "gp": { + "$defs": { + "FitFeatures": { + "additionalProperties": false, + "description": "Features of a GP to train; `type` may be left out.", + "properties": { + "decoder_type": { + "anyOf": [ + { + "enum": [ + "mlm", + "clm" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + }, + "model_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Embedding model behind PLM or SVD features: a system model id, or `svd/` for a fitted SVD." + }, + "prompt_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + }, + "query_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + }, + "reduction": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + }, + "type": { + "anyOf": [ + { + "enum": [ + "1-HOT", + "PLM", + "SVD" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Taken from `model_id` when left out: none is 1-HOT, `svd/` is SVD, a system model is PLM." + }, + "use_query_structure_in_decoder": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null + }, + "version": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Version of the embedding method the model was fit on." + } + }, + "type": "object" + }, + "FitKernel": { + "description": "Kernel of a Gaussian process predictor to train.", + "properties": { + "alpha": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Scale-mixture parameter; rational_quadratic only." + }, + "multitask": { + "default": false, + "type": "boolean" + }, + "period": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Period length; periodic kernels only." + }, + "type": { + "enum": [ + "linear", + "rbf", + "matern12", + "matern32", + "matern52", + "periodic", + "rational_quadratic" + ], + "type": "string" + } + }, + "required": [ + "type" + ], + "type": "object" + }, + "TrainingDataset": { + "additionalProperties": false, + "description": "The assay property a new predictor is trained on.", + "properties": { + "assay_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The assay to train on; defaults to the one `embeddings_job_id` embedded." + }, + "properties": { + "description": "The one property to train on; multitask fits are unsupported.", + "items": { + "type": "string" + }, + "maxItems": 1, + "minItems": 1, + "type": "array" + } + }, + "required": [ + "properties" + ], + "type": "object" + } + }, + "additionalProperties": false, + "description": "A Gaussian process predictor to train on an assay property.", + "properties": { + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + }, + "embeddings_job_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "An embeddings job, SVD projection or SVD fit whose features to train with." + }, + "features": { + "anyOf": [ + { + "$ref": "#/$defs/FitFeatures" + }, + { + "type": "null" + } + ], + "default": null + }, + "kernel": { + "$ref": "#/$defs/FitKernel" + }, + "name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + }, + "training_dataset": { + "$ref": "#/$defs/TrainingDataset" + }, + "type": { + "const": "gp", + "default": "gp", + "type": "string" + } + }, + "required": [ + "kernel", + "training_dataset" + ], + "type": "object" + }, + "gp/crossvalidate": { + "additionalProperties": false, + "description": "How a cross-validation run splits the training rows.", + "properties": { + "folds": { + "anyOf": [ + { + "items": { + "type": "integer" + }, + "minItems": 1, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Test fold of each assay row, in assay order; -1 excludes a row.", + "title": "Folds" + }, + "n_splits": { + "anyOf": [ + { + "maximum": 10, + "minimum": 2, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Random splits; 5 when unset.", + "title": "N Splits" + } + }, + "title": "CrossvalidateRequest", + "type": "object" + }, + "svd": { + "additionalProperties": false, + "description": "One stored fit over embedded sequences.\n\nIts source is `embeddings_job_id`, an earlier embeddings job whose features and\nsequences it fits on, or `model_id` with `sequences` or `assay_id`. The embedding\nparams are those of the feature model's `batch/embeddings`.", + "properties": { + "assay_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + }, + "decoder_type": { + "anyOf": [ + { + "enum": [ + "mlm", + "clm" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + }, + "embeddings_job_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + }, + "model_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "System embeddings model behind the fit." + }, + "n_components": { + "default": 1024, + "exclusiveMinimum": 0, + "type": "integer" + }, + "output": { + "default": "embeddings", + "type": "string" + }, + "prompt_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + }, + "query_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + }, + "reduction": { + "anyOf": [ + { + "enum": [ + "MEAN", + "SUM" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + }, + "seed": { + "default": 0, + "type": "integer" + }, + "sequences": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null + }, + "type": { + "const": "svd", + "default": "svd", + "type": "string" + }, + "use_query_structure_in_decoder": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "type": "object" + }, + "umap": { + "additionalProperties": false, + "description": "A UMAP fit of embedded sequences.\n\nIts source is `embeddings_job_id`, or `model_id` with `sequences` or `assay_id`.\n`model_id` is a system model (PLM features) or a fitted SVD (SVD features).", + "properties": { + "assay_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + }, + "decoder_type": { + "anyOf": [ + { + "enum": [ + "mlm", + "clm" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + }, + "embeddings_job_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "An embeddings job, SVD projection or SVD fit whose features and sequences to fit on." + }, + "min_dist": { + "default": 0.1, + "minimum": 0, + "type": "number" + }, + "model_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A system model id, or `svd/` for a fitted SVD." + }, + "n_components": { + "default": 2, + "exclusiveMinimum": 0, + "type": "integer" + }, + "n_neighbors": { + "default": 15, + "exclusiveMinimum": 0, + "type": "integer" + }, + "prompt_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + }, + "query_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + }, + "reduction": { + "anyOf": [ + { + "enum": [ + "MEAN", + "SUM" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + }, + "sequences": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null + }, + "type": { + "const": "umap", + "default": "umap", + "type": "string" + }, + "use_query_structure_in_decoder": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "type": "object" + } + }, + "methods": { + "ablang2/batch/embeddings": { + "outputs": [ + "embeddings" + ], + "params": { + "additionalProperties": false, + "properties": { + "assay_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of an assay whose sequences to run, in place of `sequences`." + }, + "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" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Sequences to run. Use ':' to delimit chains. Null with `assay_id`." + } + }, + "type": "object" + } + }, + "ablang2/batch/logits": { + "outputs": [ + "logits" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "alphaflow-md-base-v1/batch/structures": { + "params": { + "$defs": { + "FlowReference": { + "additionalProperties": false, + "properties": { + "structure_file": { + "description": "Reference structure as PDB text.", + "minLength": 1, + "type": "string" + } + }, + "required": [ + "structure_file" + ], + "type": "object" + }, + "MsaRequiredChain": { + "additionalProperties": false, + "properties": { + "protein": { + "anyOf": [ + { + "$ref": "#/$defs/MsaRequiredProtein" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "type": "object" + }, + "MsaRequiredProtein": { + "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" + }, + "msa_id": { + "format": "uuid", + "type": "string" + } + }, + "required": [ + "id", + "sequence", + "msa_id" + ], + "type": "object" + } + }, + "additionalProperties": false, + "properties": { + "complexes": { + "description": "Protein chains to sample, one per complex; every protein names an MSA, the same one in every complex.", + "items": { + "items": { + "$ref": "#/$defs/MsaRequiredChain" + }, + "type": "array" + }, + "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.", + "maximum": 250, + "minimum": 1, + "type": "integer" + }, + "num_steps": { + "default": 10, + "description": "Number of flow steps.", + "maximum": 100, + "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": { + "anyOf": [ + { + "minimum": 2, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Caps the MSA depth the model reads; null keeps the checkpoint's default." + }, + "self_cond": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Feed each step's prediction back in as the next step's input; null uses the checkpoint's default." + }, + "resample": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Redraw the MSA clusters for each conformation; null uses the checkpoint's default." + }, + "random_seed": { + "anyOf": [ + { + "maximum": 2147483647, + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Random seed; null for a random seed." + } + }, + "required": [ + "complexes" + ], + "type": "object" + }, + "outputs": [ + "structures", + "plddt", + "confidence" + ] + }, + "alphaflow-md-distilled-v1/batch/structures": { + "params": { + "$defs": { + "FlowReference": { + "additionalProperties": false, + "properties": { + "structure_file": { + "description": "Reference structure as PDB text.", + "minLength": 1, + "type": "string" + } + }, + "required": [ + "structure_file" + ], + "type": "object" + }, + "MsaRequiredChain": { + "additionalProperties": false, + "properties": { + "protein": { + "anyOf": [ + { + "$ref": "#/$defs/MsaRequiredProtein" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "type": "object" + }, + "MsaRequiredProtein": { + "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" + }, + "msa_id": { + "format": "uuid", + "type": "string" + } + }, + "required": [ + "id", + "sequence", + "msa_id" + ], + "type": "object" + } + }, + "additionalProperties": false, + "properties": { + "complexes": { + "description": "Protein chains to sample, one per complex; every protein names an MSA, the same one in every complex.", + "items": { + "items": { + "$ref": "#/$defs/MsaRequiredChain" + }, + "type": "array" + }, + "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.", + "maximum": 250, + "minimum": 1, + "type": "integer" + }, + "num_steps": { + "default": 10, + "description": "Number of flow steps.", + "maximum": 100, + "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": { + "anyOf": [ + { + "minimum": 2, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Caps the MSA depth the model reads; null keeps the checkpoint's default." + }, + "self_cond": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Feed each step's prediction back in as the next step's input; null uses the checkpoint's default." + }, + "resample": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Redraw the MSA clusters for each conformation; null uses the checkpoint's default." + }, + "random_seed": { + "anyOf": [ + { + "maximum": 2147483647, + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Random seed; null for a random seed." + } + }, + "required": [ + "complexes" + ], + "type": "object" + }, + "outputs": [ + "structures", + "plddt", + "confidence" + ] + }, + "alphafold2/batch/structures": { + "outputs": [ + "structures", + "plddt", + "pae", + "ptm", + "ipae" + ], + "params": { + "$defs": { + "MsaProteinChain": { + "additionalProperties": false, + "description": "A protein-only chain, with an optional MSA.", + "properties": { + "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": "object" + } + }, + "additionalProperties": false, + "properties": { + "complexes": { + "description": "Protein complexes to fold, each with an optional MSA.", + "items": { + "items": { + "$ref": "#/$defs/MsaProteinChain" + }, + "type": "array" + }, + "type": "array" + }, + "num_models": { + "default": 1, + "description": "Number of models.", + "maximum": 5, + "minimum": 1, + "type": "integer" + }, + "num_recycles": { + "anyOf": [ + { + "maximum": 48, + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Number of recycles; null lets the system decide." + }, + "num_relax": { + "default": 0, + "description": "Number of relaxation steps.", + "maximum": 5, + "minimum": 0, + "type": "integer" + } + }, + "required": [ + "complexes" + ], + "type": "object" + } + }, + "bioemu-v1-1/batch/structures": { + "params": { + "$defs": { + "MsaProteinChain": { + "additionalProperties": false, + "description": "A protein-only chain, with an optional MSA.", + "properties": { + "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." + }, + "sequence": { + "type": "string" + }, + "msa_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "required": [ + "id", + "sequence" + ], + "type": "object" + } + }, + "additionalProperties": false, + "properties": { + "complexes": { + "description": "Protein chains to sample, one per complex; every protein names the same MSA, or none does.", + "items": { + "items": { + "$ref": "#/$defs/MsaProteinChain" + }, + "type": "array" + }, + "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.", + "enum": [ + "dpm", + "heun", + "physical" + ], + "type": "string" + }, + "filter_samples": { + "default": true, + "description": "Drop samples that fail BioEmu's physicality checks, so a complex can come back with fewer models.", + "type": "boolean" + }, + "random_seed": { + "anyOf": [ + { + "maximum": 2147483647, + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Random seed; null for a random seed." + } + }, + "required": [ + "complexes" + ], + "type": "object" + }, + "outputs": [ + "structures" + ] + }, + "boltz-1/batch/structures": { + "outputs": [ + "structures", + "plddt", + "pae", + "pde", + "confidence", + "ipae" + ], + "params": { + "$defs": { + "Bond": { + "additionalProperties": false, + "properties": { + "atom1": { + "description": "[chain_id, residue_index, atom_name].", + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "type": "array" + }, + "atom2": { + "description": "[chain_id, residue_index, atom_name].", + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "type": "array" + } + }, + "required": [ + "atom1", + "atom2" + ], + "type": "object" + }, + "BondConstraint": { + "additionalProperties": false, + "properties": { + "bond": { + "$ref": "#/$defs/Bond" + } + }, + "required": [ + "bond" + ], + "type": "object" + }, + "Chain": { + "additionalProperties": false, + "properties": { + "dna": { + "anyOf": [ + { + "$ref": "#/$defs/DNA" + }, + { + "type": "null" + } + ], + "default": null + }, + "ligand": { + "anyOf": [ + { + "$ref": "#/$defs/Ligand" + }, + { + "type": "null" + } + ], + "default": null + }, + "protein": { + "anyOf": [ + { + "$ref": "#/$defs/Protein" + }, + { + "type": "null" + } + ], + "default": null + }, + "rna": { + "anyOf": [ + { + "$ref": "#/$defs/RNA" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "type": "object" + }, + "Contact": { + "additionalProperties": false, + "properties": { + "force": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null + }, + "max_distance": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "default": null + }, + "token1": { + "description": "[chain_id, residue_index or atom_name].", + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "type": "array" + }, + "token2": { + "description": "[chain_id, residue_index or atom_name].", + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "type": "array" + } + }, + "required": [ + "token1", + "token2" + ], + "type": "object" + }, + "ContactConstraint": { + "additionalProperties": false, + "properties": { + "contact": { + "$ref": "#/$defs/Contact" + } + }, + "required": [ + "contact" + ], + "type": "object" + }, + "DNA": { + "additionalProperties": false, + "properties": { + "cyclic": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null + }, + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "description": "Unique chain identifier(s); a list for identical chains." + }, + "modifications": { + "anyOf": [ + { + "items": { + "$ref": "#/$defs/Modification" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null + }, + "sequence": { + "type": "string" + } + }, + "required": [ + "id", + "sequence" + ], + "type": "object" + }, + "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." + }, + "smiles": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "required": [ + "id" + ], + "type": "object" + }, + "Modification": { + "additionalProperties": false, + "properties": { + "ccd": { + "type": "string" + }, + "position": { + "description": "1-based residue position.", + "type": "integer" + } + }, + "required": [ + "position", + "ccd" + ], + "type": "object" + }, + "Pocket": { + "additionalProperties": false, + "properties": { + "binder": { + "type": "string" + }, + "contacts": { + "items": { + "description": "[chain_id, residue_index or atom_name].", + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "type": "array" + }, + "type": "array" + }, + "force": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null + }, + "max_distance": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "required": [ + "binder", + "contacts" + ], + "type": "object" + }, + "PocketConstraint": { + "additionalProperties": false, + "properties": { + "pocket": { + "$ref": "#/$defs/Pocket" + } + }, + "required": [ + "pocket" + ], + "type": "object" + }, + "Protein": { + "additionalProperties": false, + "properties": { + "cyclic": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null + }, + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "description": "Unique chain identifier(s); a list for identical chains." + }, + "modifications": { + "anyOf": [ + { + "items": { + "$ref": "#/$defs/Modification" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null + }, + "msa_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + }, + "sequence": { + "type": "string" + } + }, + "required": [ + "id", + "sequence" + ], + "type": "object" + }, + "RNA": { + "additionalProperties": false, + "properties": { + "cyclic": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null + }, + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "description": "Unique chain identifier(s); a list for identical chains." + }, + "modifications": { + "anyOf": [ + { + "items": { + "$ref": "#/$defs/Modification" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null + }, + "msa_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + }, + "sequence": { + "type": "string" + } + }, + "required": [ + "id", + "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": "Complexes to fold. Each complex is a list of chain entities.", + "items": { + "items": { + "$ref": "#/$defs/Chain" + }, + "type": "array" + }, + "type": "array" + }, + "constraints": { + "anyOf": [ + { + "description": "Optional constraints: bonds, pockets, or contacts.", + "items": { + "anyOf": [ + { + "$ref": "#/$defs/BondConstraint" + }, + { + "$ref": "#/$defs/PocketConstraint" + }, + { + "$ref": "#/$defs/ContactConstraint" + } + ] + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null + }, + "num_recycles": { + "default": 3, + "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": 200, + "description": "Number of sampling steps to use.", + "minimum": 1, + "type": "integer" + }, + "random_seed": { + "anyOf": [ + { + "maximum": 2147483647, + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Random seed. Not used yet by this model, so runs are not reproducible." + }, + "step_scale": { + "default": 1.638, + "description": "Scaling factor for diffusion steps.", + "type": "number" + }, + "use_potentials": { + "default": false, + "description": "Steer sampling with inference-time potentials.", + "type": "boolean" + } + }, + "required": [ + "complexes" + ], + "type": "object" + } + }, + "boltz-1x/batch/structures": { + "outputs": [ + "structures", + "plddt", + "pae", + "pde", + "confidence", + "ipae" + ], + "params": { + "$defs": { + "Bond": { + "additionalProperties": false, + "properties": { + "atom1": { + "description": "[chain_id, residue_index, atom_name].", + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "type": "array" + }, + "atom2": { + "description": "[chain_id, residue_index, atom_name].", + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "type": "array" + } + }, + "required": [ + "atom1", + "atom2" + ], + "type": "object" + }, + "BondConstraint": { + "additionalProperties": false, + "properties": { + "bond": { + "$ref": "#/$defs/Bond" + } + }, + "required": [ + "bond" + ], + "type": "object" + }, + "Chain": { + "additionalProperties": false, + "properties": { + "dna": { + "anyOf": [ + { + "$ref": "#/$defs/DNA" + }, + { + "type": "null" + } + ], + "default": null + }, + "ligand": { + "anyOf": [ + { + "$ref": "#/$defs/Ligand" + }, + { + "type": "null" + } + ], + "default": null + }, + "protein": { + "anyOf": [ + { + "$ref": "#/$defs/Protein" + }, + { + "type": "null" + } + ], + "default": null + }, + "rna": { + "anyOf": [ + { + "$ref": "#/$defs/RNA" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "type": "object" + }, + "Contact": { + "additionalProperties": false, + "properties": { + "force": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null + }, + "max_distance": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "default": null + }, + "token1": { + "description": "[chain_id, residue_index or atom_name].", + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "type": "array" + }, + "token2": { + "description": "[chain_id, residue_index or atom_name].", + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "type": "array" + } + }, + "required": [ + "token1", + "token2" + ], + "type": "object" + }, + "ContactConstraint": { + "additionalProperties": false, + "properties": { + "contact": { + "$ref": "#/$defs/Contact" + } + }, + "required": [ + "contact" + ], + "type": "object" + }, + "DNA": { + "additionalProperties": false, + "properties": { + "cyclic": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null + }, + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "description": "Unique chain identifier(s); a list for identical chains." + }, + "modifications": { + "anyOf": [ + { + "items": { + "$ref": "#/$defs/Modification" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null + }, + "sequence": { + "type": "string" + } + }, + "required": [ + "id", + "sequence" + ], + "type": "object" + }, + "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." + }, + "smiles": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "required": [ + "id" + ], + "type": "object" + }, + "Modification": { + "additionalProperties": false, + "properties": { + "ccd": { + "type": "string" + }, + "position": { + "description": "1-based residue position.", + "type": "integer" + } + }, + "required": [ + "position", + "ccd" + ], + "type": "object" + }, + "Pocket": { + "additionalProperties": false, + "properties": { + "binder": { + "type": "string" + }, + "contacts": { + "items": { + "description": "[chain_id, residue_index or atom_name].", + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "type": "array" + }, + "type": "array" + }, + "force": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null + }, + "max_distance": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "required": [ + "binder", + "contacts" + ], + "type": "object" + }, + "PocketConstraint": { + "additionalProperties": false, + "properties": { + "pocket": { + "$ref": "#/$defs/Pocket" + } + }, + "required": [ + "pocket" + ], + "type": "object" + }, + "Protein": { + "additionalProperties": false, + "properties": { + "cyclic": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null + }, + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "description": "Unique chain identifier(s); a list for identical chains." + }, + "modifications": { + "anyOf": [ + { + "items": { + "$ref": "#/$defs/Modification" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null + }, + "msa_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + }, + "sequence": { + "type": "string" + } + }, + "required": [ + "id", + "sequence" + ], + "type": "object" + }, + "RNA": { + "additionalProperties": false, + "properties": { + "cyclic": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null + }, + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "description": "Unique chain identifier(s); a list for identical chains." + }, + "modifications": { + "anyOf": [ + { + "items": { + "$ref": "#/$defs/Modification" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null + }, + "msa_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + }, + "sequence": { + "type": "string" + } + }, + "required": [ + "id", + "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": "Complexes to fold. Each complex is a list of chain entities.", + "items": { + "items": { + "$ref": "#/$defs/Chain" + }, + "type": "array" + }, + "type": "array" + }, + "constraints": { + "anyOf": [ + { + "description": "Optional constraints: bonds, pockets, or contacts.", + "items": { + "anyOf": [ + { + "$ref": "#/$defs/BondConstraint" + }, + { + "$ref": "#/$defs/PocketConstraint" + }, + { + "$ref": "#/$defs/ContactConstraint" + } + ] + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null + }, + "num_recycles": { + "default": 3, + "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": 200, + "description": "Number of sampling steps to use.", + "minimum": 1, + "type": "integer" + }, + "random_seed": { + "anyOf": [ + { + "maximum": 2147483647, + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Random seed. Not used yet by this model, so runs are not reproducible." + }, + "step_scale": { + "default": 1.638, + "description": "Scaling factor for diffusion steps.", + "type": "number" + } + }, + "required": [ + "complexes" + ], + "type": "object" + } + }, + "boltz-2/batch/structures": { + "outputs": [ + "structures", + "plddt", + "pae", + "pde", + "confidence", + "ipae", + "affinity" + ], + "params": { + "$defs": { + "Affinity": { + "additionalProperties": false, + "properties": { + "binder": { + "description": "Chain id of the ligand to score.", + "type": "string" + } + }, + "required": [ + "binder" + ], + "type": "object" + }, + "Bond": { + "additionalProperties": false, + "properties": { + "atom1": { + "description": "[chain_id, residue_index, atom_name].", + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "type": "array" + }, + "atom2": { + "description": "[chain_id, residue_index, atom_name].", + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "type": "array" + } + }, + "required": [ + "atom1", + "atom2" + ], + "type": "object" + }, + "BondConstraint": { + "additionalProperties": false, + "properties": { + "bond": { + "$ref": "#/$defs/Bond" + } + }, + "required": [ + "bond" + ], + "type": "object" + }, + "Chain": { + "additionalProperties": false, + "properties": { + "dna": { + "anyOf": [ + { + "$ref": "#/$defs/DNA" + }, + { + "type": "null" + } + ], + "default": null + }, + "ligand": { + "anyOf": [ + { + "$ref": "#/$defs/Ligand" + }, + { + "type": "null" + } + ], + "default": null + }, + "protein": { + "anyOf": [ + { + "$ref": "#/$defs/Protein" + }, + { + "type": "null" + } + ], + "default": null + }, + "rna": { + "anyOf": [ + { + "$ref": "#/$defs/RNA" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "type": "object" + }, + "Contact": { + "additionalProperties": false, + "properties": { + "force": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null + }, + "max_distance": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "default": null + }, + "token1": { + "description": "[chain_id, residue_index or atom_name].", + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "type": "array" + }, + "token2": { + "description": "[chain_id, residue_index or atom_name].", + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "type": "array" + } + }, + "required": [ + "token1", + "token2" + ], + "type": "object" + }, + "ContactConstraint": { + "additionalProperties": false, + "properties": { + "contact": { + "$ref": "#/$defs/Contact" + } + }, + "required": [ + "contact" + ], + "type": "object" + }, + "DNA": { + "additionalProperties": false, + "properties": { + "cyclic": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null + }, + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "description": "Unique chain identifier(s); a list for identical chains." + }, + "modifications": { + "anyOf": [ + { + "items": { + "$ref": "#/$defs/Modification" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null + }, + "sequence": { + "type": "string" + } + }, + "required": [ + "id", + "sequence" + ], + "type": "object" + }, + "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." + }, + "smiles": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "required": [ + "id" + ], + "type": "object" + }, + "Modification": { + "additionalProperties": false, + "properties": { + "ccd": { + "type": "string" + }, + "position": { + "description": "1-based residue position.", + "type": "integer" + } + }, + "required": [ + "position", + "ccd" + ], + "type": "object" + }, + "Pocket": { + "additionalProperties": false, + "properties": { + "binder": { + "type": "string" + }, + "contacts": { + "items": { + "description": "[chain_id, residue_index or atom_name].", + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "type": "array" + }, + "type": "array" + }, + "force": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null + }, + "max_distance": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "required": [ + "binder", + "contacts" + ], + "type": "object" + }, + "PocketConstraint": { + "additionalProperties": false, + "properties": { + "pocket": { + "$ref": "#/$defs/Pocket" + } + }, + "required": [ + "pocket" + ], + "type": "object" + }, + "Property": { + "additionalProperties": false, + "properties": { + "affinity": { + "$ref": "#/$defs/Affinity" + } + }, + "required": [ + "affinity" + ], + "type": "object" + }, + "Protein": { + "additionalProperties": false, + "properties": { + "cyclic": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null + }, + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "description": "Unique chain identifier(s); a list for identical chains." + }, + "modifications": { + "anyOf": [ + { + "items": { + "$ref": "#/$defs/Modification" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null + }, + "msa_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + }, + "sequence": { + "type": "string" + } + }, + "required": [ + "id", + "sequence" + ], + "type": "object" + }, + "RNA": { + "additionalProperties": false, + "properties": { + "cyclic": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null + }, + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "description": "Unique chain identifier(s); a list for identical chains." + }, + "modifications": { + "anyOf": [ + { + "items": { + "$ref": "#/$defs/Modification" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null + }, + "msa_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + }, + "sequence": { + "type": "string" + } + }, + "required": [ + "id", + "sequence" + ], + "type": "object" + }, + "Template": { + "additionalProperties": false, + "properties": { + "chain_id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null + }, + "force": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null + }, + "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 + }, + "threshold": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "required": [ + "query_id" + ], + "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": "Complexes to fold. Each complex is a list of chain entities.", + "items": { + "items": { + "$ref": "#/$defs/Chain" + }, + "type": "array" + }, + "type": "array" + }, + "constraints": { + "anyOf": [ + { + "description": "Optional constraints: bonds, pockets, or contacts.", + "items": { + "anyOf": [ + { + "$ref": "#/$defs/BondConstraint" + }, + { + "$ref": "#/$defs/PocketConstraint" + }, + { + "$ref": "#/$defs/ContactConstraint" + } + ] + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null + }, + "method": { + "anyOf": [ + { + "enum": [ + "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" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Experimental method to condition on." + }, + "num_recycles": { + "default": 3, + "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": 200, + "description": "Number of sampling steps to use.", + "minimum": 1, + "type": "integer" + }, + "properties": { + "anyOf": [ + { + "description": "Optional properties to compute, such as affinity.", + "items": { + "$ref": "#/$defs/Property" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null + }, + "random_seed": { + "anyOf": [ + { + "maximum": 2147483647, + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Random seed. Not used yet by this model, so runs are not reproducible." + }, + "step_scale": { + "default": 1.638, + "description": "Scaling factor for diffusion steps.", + "type": "number" + }, + "templates": { + "anyOf": [ + { + "description": "Optional structural templates for prediction.", + "items": { + "$ref": "#/$defs/Template" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "required": [ + "complexes" + ], + "type": "object" + } + }, + "boltzgen/generate/structures": { + "outputs": [ + "structures" + ], + "params": { + "additionalProperties": false, + "properties": { + "diffusion_batch_size": { + "anyOf": [ + { + "minimum": 1, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Samples diffused in parallel." + }, + "noise_scale": { + "anyOf": [ + { + "exclusiveMinimum": 0, + "maximum": 1, + "type": "number" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Scaling factor for the noise schedule." + }, + "num_samples": { + "default": 1, + "description": "Number of designs.", + "minimum": 1, + "type": "integer" + }, + "query_id": { + "description": "Structure query naming the design.", + "format": "uuid", + "type": "string" + }, + "random_seed": { + "anyOf": [ + { + "maximum": 4294967296, + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Random seed; design i draws with seed + i. Not used yet by this model, so runs are not reproducible." + }, + "step_scale": { + "anyOf": [ + { + "exclusiveMinimum": 0, + "type": "number" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Scaling factor for diffusion steps." + } + }, + "required": [ + "query_id" + ], + "type": "object" + } + }, + "esm-if1/batch/loglikelihood": { + "outputs": [ + "loglikelihood" + ], + "params": { + "additionalProperties": false, + "properties": { + "query_id": { + "description": "ID of a query (sequence or structure) to condition on.", + "format": "uuid", + "type": "string" + }, + "sequences": { + "description": "Sequences to score, one ':'-delimited segment per query chain in chain-id order.", + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + } + }, + "required": [ + "query_id", + "sequences" + ], + "type": "object" + } + }, + "esm-if1/generate/sequences": { + "outputs": [ + "sequences", + "loglikelihood" + ], + "params": { + "additionalProperties": false, + "properties": { + "design_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "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." + }, + "num_samples": { + "default": 100, + "description": "Number of designs.", + "minimum": 1, + "type": "integer" + }, + "query_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of the structure query to design for. Pass this or design_id." + }, + "random_seed": { + "anyOf": [ + { + "maximum": 4294967296, + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Random seed; sample i draws with seed + i. Null for a random seed." + }, + "temperature": { + "default": 1.0, + "description": "Sampling temperature; low favours recovery, high favours diversity.", + "maximum": 1000000.0, + "minimum": 1e-06, + "type": "number" + } + }, + "type": "object" + } + }, + "esm-if1/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.", + "type": "string" + }, + "query_id": { + "description": "ID of a query (sequence or structure) to condition on.", + "format": "uuid", + "type": "string" + } + }, + "required": [ + "query_id", + "base_sequence" + ], + "type": "object" + } + }, + "esm1b_t33_650M_UR50S/batch/attn": { + "outputs": [ + "attn" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esm1b_t33_650M_UR50S/batch/embeddings": { + "outputs": [ + "embeddings" + ], + "params": { + "additionalProperties": false, + "properties": { + "assay_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of an assay whose sequences to run, in place of `sequences`." + }, + "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" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Sequences to run. Use ':' to delimit chains. Null with `assay_id`." + } + }, + "type": "object" + } + }, + "esm1b_t33_650M_UR50S/batch/logits": { + "outputs": [ + "logits" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esm1v_t33_650M_UR90S_1/batch/attn": { + "outputs": [ + "attn" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esm1v_t33_650M_UR90S_1/batch/embeddings": { + "outputs": [ + "embeddings" + ], + "params": { + "additionalProperties": false, + "properties": { + "assay_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of an assay whose sequences to run, in place of `sequences`." + }, + "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" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Sequences to run. Use ':' to delimit chains. Null with `assay_id`." + } + }, + "type": "object" + } + }, + "esm1v_t33_650M_UR90S_1/batch/logits": { + "outputs": [ + "logits" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esm1v_t33_650M_UR90S_2/batch/attn": { + "outputs": [ + "attn" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esm1v_t33_650M_UR90S_2/batch/embeddings": { + "outputs": [ + "embeddings" + ], + "params": { + "additionalProperties": false, + "properties": { + "assay_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of an assay whose sequences to run, in place of `sequences`." + }, + "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" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Sequences to run. Use ':' to delimit chains. Null with `assay_id`." + } + }, + "type": "object" + } + }, + "esm1v_t33_650M_UR90S_2/batch/logits": { + "outputs": [ + "logits" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esm1v_t33_650M_UR90S_3/batch/attn": { + "outputs": [ + "attn" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esm1v_t33_650M_UR90S_3/batch/embeddings": { + "outputs": [ + "embeddings" + ], + "params": { + "additionalProperties": false, + "properties": { + "assay_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of an assay whose sequences to run, in place of `sequences`." + }, + "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" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Sequences to run. Use ':' to delimit chains. Null with `assay_id`." + } + }, + "type": "object" + } + }, + "esm1v_t33_650M_UR90S_3/batch/logits": { + "outputs": [ + "logits" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esm1v_t33_650M_UR90S_4/batch/attn": { + "outputs": [ + "attn" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esm1v_t33_650M_UR90S_4/batch/embeddings": { + "outputs": [ + "embeddings" + ], + "params": { + "additionalProperties": false, + "properties": { + "assay_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of an assay whose sequences to run, in place of `sequences`." + }, + "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" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Sequences to run. Use ':' to delimit chains. Null with `assay_id`." + } + }, + "type": "object" + } + }, + "esm1v_t33_650M_UR90S_4/batch/logits": { + "outputs": [ + "logits" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esm1v_t33_650M_UR90S_5/batch/attn": { + "outputs": [ + "attn" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esm1v_t33_650M_UR90S_5/batch/embeddings": { + "outputs": [ + "embeddings" + ], + "params": { + "additionalProperties": false, + "properties": { + "assay_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of an assay whose sequences to run, in place of `sequences`." + }, + "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" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Sequences to run. Use ':' to delimit chains. Null with `assay_id`." + } + }, + "type": "object" + } + }, + "esm1v_t33_650M_UR90S_5/batch/logits": { + "outputs": [ + "logits" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esm2_t12_35M_UR50D/batch/attn": { + "outputs": [ + "attn" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esm2_t12_35M_UR50D/batch/embeddings": { + "outputs": [ + "embeddings" + ], + "params": { + "additionalProperties": false, + "properties": { + "assay_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of an assay whose sequences to run, in place of `sequences`." + }, + "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" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Sequences to run. Use ':' to delimit chains. Null with `assay_id`." + } + }, + "type": "object" + } + }, + "esm2_t12_35M_UR50D/batch/logits": { + "outputs": [ + "logits" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esm2_t12_35M_UR50D/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_t30_150M_UR50D/batch/attn": { + "outputs": [ + "attn" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esm2_t30_150M_UR50D/batch/embeddings": { + "outputs": [ + "embeddings" + ], + "params": { + "additionalProperties": false, + "properties": { + "assay_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of an assay whose sequences to run, in place of `sequences`." + }, + "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" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Sequences to run. Use ':' to delimit chains. Null with `assay_id`." + } + }, + "type": "object" + } + }, + "esm2_t30_150M_UR50D/batch/logits": { + "outputs": [ + "logits" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esm2_t30_150M_UR50D/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_t33_650M_UR50D/batch/attn": { + "outputs": [ + "attn" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esm2_t33_650M_UR50D/batch/embeddings": { + "outputs": [ + "embeddings" + ], + "params": { + "additionalProperties": false, + "properties": { + "assay_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of an assay whose sequences to run, in place of `sequences`." + }, + "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" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Sequences to run. Use ':' to delimit chains. Null with `assay_id`." + } + }, + "type": "object" + } + }, + "esm2_t33_650M_UR50D/batch/logits": { + "outputs": [ + "logits" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esm2_t33_650M_UR50D/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_t36_3B_UR50D/batch/attn": { + "outputs": [ + "attn" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esm2_t36_3B_UR50D/batch/embeddings": { + "outputs": [ + "embeddings" + ], + "params": { + "additionalProperties": false, + "properties": { + "assay_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of an assay whose sequences to run, in place of `sequences`." + }, + "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" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Sequences to run. Use ':' to delimit chains. Null with `assay_id`." + } + }, + "type": "object" + } + }, + "esm2_t36_3B_UR50D/batch/logits": { + "outputs": [ + "logits" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esm2_t36_3B_UR50D/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_t6_8M_UR50D/batch/attn": { + "outputs": [ + "attn" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esm2_t6_8M_UR50D/batch/embeddings": { + "outputs": [ + "embeddings" + ], + "params": { + "additionalProperties": false, + "properties": { + "assay_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of an assay whose sequences to run, in place of `sequences`." + }, + "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" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Sequences to run. Use ':' to delimit chains. Null with `assay_id`." + } + }, + "type": "object" + } + }, + "esm2_t6_8M_UR50D/batch/logits": { + "outputs": [ + "logits" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esm2_t6_8M_UR50D/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" + } + }, + "esmc-300m/batch/attn": { + "outputs": [ + "attn" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esmc-300m/batch/embeddings": { + "outputs": [ + "embeddings" + ], + "params": { + "additionalProperties": false, + "properties": { + "assay_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of an assay whose sequences to run, in place of `sequences`." + }, + "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" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Sequences to run. Use ':' to delimit chains. Null with `assay_id`." + } + }, + "type": "object" + } + }, + "esmc-300m/batch/logits": { + "outputs": [ + "logits" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esmc-300m/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" + } + }, + "esmc-600m/batch/attn": { + "outputs": [ + "attn" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esmc-600m/batch/embeddings": { + "outputs": [ + "embeddings" + ], + "params": { + "additionalProperties": false, + "properties": { + "assay_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of an assay whose sequences to run, in place of `sequences`." + }, + "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" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Sequences to run. Use ':' to delimit chains. Null with `assay_id`." + } + }, + "type": "object" + } + }, + "esmc-600m/batch/logits": { + "outputs": [ + "logits" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esmc-600m/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" + } + }, + "esmc-6b/batch/attn": { + "outputs": [ + "attn" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esmc-6b/batch/embeddings": { + "outputs": [ + "embeddings" + ], + "params": { + "additionalProperties": false, + "properties": { + "assay_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of an assay whose sequences to run, in place of `sequences`." + }, + "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" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Sequences to run. Use ':' to delimit chains. Null with `assay_id`." + } + }, + "type": "object" + } + }, + "esmc-6b/batch/logits": { + "outputs": [ + "logits" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "esmc-6b/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" + } + }, + "esmflow-md-base-v1/batch/structures": { + "params": { + "$defs": { + "FlowReference": { + "additionalProperties": false, + "properties": { + "structure_file": { + "description": "Reference structure as PDB text.", + "minLength": 1, + "type": "string" + } + }, + "required": [ + "structure_file" + ], + "type": "object" + }, + "Protein": { + "additionalProperties": false, + "description": "Protein 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" + ], + "type": "object" + }, + "ProteinChain": { + "additionalProperties": false, + "description": "A protein-only chain (no MSA).", + "properties": { + "protein": { + "anyOf": [ + { + "$ref": "#/$defs/Protein" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "type": "object" + } + }, + "additionalProperties": false, + "properties": { + "complexes": { + "description": "Protein chains to sample, one per complex.", + "items": { + "items": { + "$ref": "#/$defs/ProteinChain" + }, + "type": "array" + }, + "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.", + "maximum": 250, + "minimum": 1, + "type": "integer" + }, + "num_steps": { + "default": 10, + "description": "Number of flow steps.", + "maximum": 100, + "minimum": 1, + "type": "integer" + }, + "tmax": { + "default": 1.0, + "description": "Noise level the flow starts from, in (0, 1].", + "exclusiveMinimum": 0, + "maximum": 1, + "type": "number" + }, + "self_cond": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Feed each step's prediction back in as the next step's input; null uses the checkpoint's default." + }, + "random_seed": { + "anyOf": [ + { + "maximum": 2147483647, + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Random seed; null for a random seed." + } + }, + "required": [ + "complexes" + ], + "type": "object" + }, + "outputs": [ + "structures", + "plddt", + "confidence" + ] + }, + "esmflow-md-distilled-v1/batch/structures": { + "params": { + "$defs": { + "FlowReference": { + "additionalProperties": false, + "properties": { + "structure_file": { + "description": "Reference structure as PDB text.", + "minLength": 1, + "type": "string" + } + }, + "required": [ + "structure_file" + ], + "type": "object" + }, + "Protein": { + "additionalProperties": false, + "description": "Protein 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" + ], + "type": "object" + }, + "ProteinChain": { + "additionalProperties": false, + "description": "A protein-only chain (no MSA).", + "properties": { + "protein": { + "anyOf": [ + { + "$ref": "#/$defs/Protein" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "type": "object" + } + }, + "additionalProperties": false, + "properties": { + "complexes": { + "description": "Protein chains to sample, one per complex.", + "items": { + "items": { + "$ref": "#/$defs/ProteinChain" + }, + "type": "array" + }, + "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.", + "maximum": 250, + "minimum": 1, + "type": "integer" + }, + "num_steps": { + "default": 10, + "description": "Number of flow steps.", + "maximum": 100, + "minimum": 1, + "type": "integer" + }, + "tmax": { + "default": 1.0, + "description": "Noise level the flow starts from, in (0, 1].", + "exclusiveMinimum": 0, + "maximum": 1, + "type": "number" + }, + "self_cond": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Feed each step's prediction back in as the next step's input; null uses the checkpoint's default." + }, + "random_seed": { + "anyOf": [ + { + "maximum": 2147483647, + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Random seed; null for a random seed." + } + }, + "required": [ + "complexes" + ], + "type": "object" + }, + "outputs": [ + "structures", + "plddt", + "confidence" + ] + }, + "esmfold/batch/structures": { + "outputs": [ + "structures", + "pae", + "ipae" + ], + "params": { + "$defs": { + "Protein": { + "additionalProperties": false, + "description": "Protein 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" + ], + "type": "object" + }, + "ProteinChain": { + "additionalProperties": false, + "description": "A protein-only chain (no MSA).", + "properties": { + "protein": { + "anyOf": [ + { + "$ref": "#/$defs/Protein" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "type": "object" + } + }, + "additionalProperties": false, + "properties": { + "complexes": { + "description": "Protein complexes to fold.", + "items": { + "items": { + "$ref": "#/$defs/ProteinChain" + }, + "type": "array" + }, + "type": "array" + }, + "num_recycles": { + "anyOf": [ + { + "maximum": 48, + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Number of recycles; null lets the system decide." + } + }, + "required": [ + "complexes" + ], + "type": "object" + } + }, + "esmfold2-fast/batch/structures": { + "outputs": [ + "structures", + "plddt", + "pae", + "confidence", + "ipae" + ], + "params": { + "$defs": { + "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" + ], + "type": "object" + }, + "Ligand": { + "additionalProperties": false, + "properties": { + "ccd": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": 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" + ], + "type": "object" + }, + "Protein": { + "additionalProperties": false, + "description": "Protein 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" + ], + "type": "object" + }, + "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" + } + }, + "required": [ + "id", + "sequence" + ], + "type": "object" + }, + "SingleSequenceChain": { + "additionalProperties": false, + "properties": { + "dna": { + "anyOf": [ + { + "$ref": "#/$defs/DNA" + }, + { + "type": "null" + } + ], + "default": null + }, + "ligand": { + "anyOf": [ + { + "$ref": "#/$defs/Ligand" + }, + { + "type": "null" + } + ], + "default": null + }, + "protein": { + "anyOf": [ + { + "$ref": "#/$defs/Protein" + }, + { + "type": "null" + } + ], + "default": null + }, + "rna": { + "anyOf": [ + { + "$ref": "#/$defs/RNA" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "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": "Complexes to fold (single-sequence; no MSA).", + "items": { + "items": { + "$ref": "#/$defs/SingleSequenceChain" + }, + "type": "array" + }, + "type": "array" + }, + "num_recycles": { + "default": 3, + "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": 100, + "description": "Number of sampling steps to use.", + "minimum": 1, + "type": "integer" + }, + "random_seed": { + "anyOf": [ + { + "maximum": 2147483647, + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Random seed; null for a random seed." + } + }, + "required": [ + "complexes" + ], + "type": "object" + } + }, + "esmfold2/batch/structures": { + "outputs": [ + "structures", + "plddt", + "pae", + "confidence", + "ipae" + ], + "params": { + "$defs": { + "Chain": { + "additionalProperties": false, + "properties": { + "dna": { + "anyOf": [ + { + "$ref": "#/$defs/DNA" + }, + { + "type": "null" + } + ], + "default": 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 + } + }, + "type": "object" + }, + "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" + ], + "type": "object" + }, + "Ligand": { + "additionalProperties": false, + "properties": { + "ccd": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": 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" + ], + "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": "object" + }, + "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" + } + }, + "required": [ + "id", + "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": "Complexes to fold. Each complex is a list of chain entities.", + "items": { + "items": { + "$ref": "#/$defs/Chain" + }, + "type": "array" + }, + "type": "array" + }, + "num_recycles": { + "default": 3, + "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": 100, + "description": "Number of sampling steps to use.", + "minimum": 1, + "type": "integer" + }, + "random_seed": { + "anyOf": [ + { + "maximum": 2147483647, + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Random seed; null for a random seed." + } + }, + "required": [ + "complexes" + ], + "type": "object" + } + }, + "gp/batch/predictions": { + "outputs": [ + "predictions" + ], + "params": { + "additionalProperties": false, + "properties": { + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "gp/single-site/predictions": { + "outputs": [ + "predictions" + ], + "params": { + "additionalProperties": false, + "properties": { + "base_sequence": { + "description": "Sequence whose single-site variants are predicted.", + "type": "string" + } + }, + "required": [ + "base_sequence" + ], + "type": "object" + } + }, + "minifold/batch/structures": { + "outputs": [ + "structures" + ], + "params": { + "$defs": { + "Protein": { + "additionalProperties": false, + "description": "Protein 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" + ], + "type": "object" + }, + "ProteinChain": { + "additionalProperties": false, + "description": "A protein-only chain (no MSA).", + "properties": { + "protein": { + "anyOf": [ + { + "$ref": "#/$defs/Protein" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "type": "object" + } + }, + "additionalProperties": false, + "properties": { + "complexes": { + "description": "Protein complexes to fold.", + "items": { + "items": { + "$ref": "#/$defs/ProteinChain" + }, + "type": "array" + }, + "type": "array" + }, + "num_recycles": { + "anyOf": [ + { + "maximum": 48, + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Number of recycles; null lets the system decide." + } + }, + "required": [ + "complexes" + ], + "type": "object" + } + }, + "poet-2/batch/embeddings": { + "outputs": [ + "embeddings" + ], + "params": { + "additionalProperties": false, + "properties": { + "assay_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of an assay whose sequences to run, in place of `sequences`." + }, + "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" + }, + { + "type": "null" + } + ], + "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": [ + { + "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" + }, + { + "type": "null" + } + ], + "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-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": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "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": [ + "sequences" + ], + "type": "object" + } + }, + "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": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "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": [ + "sequences" + ], + "type": "object" + } + }, + "poet-2/generate/sequences": { + "outputs": [ + "sequences", + "loglikelihood" + ], + "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": "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." + }, + "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": [ + { + "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." + }, + "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" + } + }, + "poet-2/indel/scores": { + "outputs": [ + "score" + ], + "params": { + "additionalProperties": false, + "properties": { + "base_sequence": { + "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": [ + { + "items": { + "minimum": 0, + "type": "integer" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Sizes of the fragment deleted at each site." + }, + "insert": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Fragment inserted at, or in place of, each site." + }, + "prompt_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of the prompt to condition on; null runs unconditioned." + } + }, + "required": [ + "base_sequence" + ], + "type": "object" + } + }, + "poet-2/single-site/scores": { + "outputs": [ + "score" + ], + "params": { + "additionalProperties": false, + "properties": { + "base_sequence": { + "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.", + "type": "boolean" + }, + "prompt_id": { + "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" + }, + { + "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": [ + "base_sequence" + ], + "type": "object" + } + }, + "poet/batch/embeddings": { + "outputs": [ + "embeddings" + ], + "params": { + "additionalProperties": false, + "properties": { + "assay_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of an assay whose sequences to run, in place of `sequences`." + }, + "prompt_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of the prompt to condition on; null runs unconditioned." + }, + "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" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Sequences to run. Use ':' to delimit chains. Null with `assay_id`." + } + }, + "type": "object" + } + }, + "poet/batch/logits": { + "outputs": [ + "logits" + ], + "params": { + "additionalProperties": false, + "properties": { + "prompt_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of the prompt to condition on; null runs unconditioned." + }, + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "poet/batch/loglikelihood": { + "outputs": [ + "loglikelihood" + ], + "params": { + "additionalProperties": false, + "properties": { + "prompt_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of the prompt to condition on; null runs unconditioned." + }, + "sequences": { + "description": "Sequences to run. Use ':' to delimit chains.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "sequences" + ], + "type": "object" + } + }, + "poet/generate/sequences": { + "outputs": [ + "sequences", + "loglikelihood" + ], + "params": { + "additionalProperties": false, + "properties": { + "max_length": { + "default": 1000, + "description": "A sample holds at most max_length + 1 residues.", + "maximum": 15999, + "minimum": 1, + "type": "integer" + }, + "num_samples": { + "default": 100, + "description": "Number of samples.", + "minimum": 1, + "type": "integer" + }, + "prompt_id": { + "description": "ID of the prompt to sample from.", + "type": "string" + }, + "random_seed": { + "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." + }, + "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" + } + }, + "required": [ + "prompt_id" + ], + "type": "object" + } + }, + "poet/indel/scores": { + "outputs": [ + "score" + ], + "params": { + "additionalProperties": false, + "properties": { + "base_sequence": { + "description": "Sequence whose variants are scored, ':' delimiting chains.", + "type": "string" + }, + "delete": { + "anyOf": [ + { + "items": { + "minimum": 0, + "type": "integer" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Sizes of the fragment deleted at each site." + }, + "insert": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Fragment inserted at, or in place of, each site." + }, + "prompt_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "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": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "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" + }, + "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": [ + { + "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" + }, + { + "type": "null" + } + ], + "default": null, + "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" + }, + "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" + } + }, + "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": [ + { + "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": { + "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" + } + }, + "proteinmpnn/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" + }, + "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" + }, + "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" + } + }, + "required": [ + "query_id", + "sequences" + ], + "type": "object" + } + }, + "proteinmpnn/generate/sequences": { + "outputs": [ + "sequences", + "loglikelihood" + ], + "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": { + "anyOf": [ + { + "additionalProperties": { + "items": { + "items": { + "type": "number" + }, + "type": "array" + }, + "type": "array" + }, + "type": "object" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Per chain, one 21-element logit bias row per residue." + }, + "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" + }, + { + "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" + }, + "type": "array" + }, + "type": "array" + }, + { + "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" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Amino acids to exclude from every position." + }, + "omit_aas_per_chain_position": { + "anyOf": [ + { + "additionalProperties": { + "items": { + "maxItems": 2, + "minItems": 2, + "prefixItems": [ + { + "items": { + "type": "integer" + }, + "type": "array" + }, + { + "type": "string" + } + ], + "type": "array" + }, + "type": "array" + }, + "type": "object" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Per chain, [positions, amino acids] pairs excluding those amino acids at those positions." + }, + "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": "number" + }, + "type": "array" + }, + "type": "object" + }, + "type": "object" + }, + { + "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" + }, + "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." + }, + "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" + } + }, + "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": [ + "query_id", + "base_sequence" + ], + "type": "object" + } + }, + "protenix-v2/batch/structures": { + "outputs": [ + "structures", + "plddt", + "pae", + "pde", + "confidence", + "ipae" + ], + "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 + }, + "rna": { + "anyOf": [ + { + "$ref": "#/$defs/RNA" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "type": "object" + }, + "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" + ], + "type": "object" + }, + "Ion": { + "additionalProperties": false, + "properties": { + "ccd": { + "type": "string" + }, + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "description": "Unique chain identifier(s); a list for identical chains." + } + }, + "required": [ + "id", + "ccd" + ], + "type": "object" + }, + "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." + }, + "smiles": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "required": [ + "id" + ], + "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": "object" + }, + "RNA": { + "additionalProperties": false, + "description": "RNA 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": "object" + }, + "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." + }, + "force": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null + }, + "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 + } + }, + "required": [ + "query_id" + ], + "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": "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": [ + { + "maximum": 2147483647, + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Random seed. Not used yet by this model, so runs are not reproducible." + }, + "templates": { + "anyOf": [ + { + "description": "Optional structural templates for prediction.", + "items": { + "$ref": "#/$defs/Template" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "required": [ + "complexes" + ], + "type": "object" + } + }, + "protenix/batch/structures": { + "outputs": [ + "structures", + "plddt", + "pae", + "pde", + "confidence", + "ipae" + ], + "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 + }, + "rna": { + "anyOf": [ + { + "$ref": "#/$defs/RNA" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "type": "object" + }, + "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" + ], + "type": "object" + }, + "Ion": { + "additionalProperties": false, + "properties": { + "ccd": { + "type": "string" + }, + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "description": "Unique chain identifier(s); a list for identical chains." + } + }, + "required": [ + "id", + "ccd" + ], + "type": "object" + }, + "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." + }, + "smiles": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "required": [ + "id" + ], + "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": "object" + }, + "RNA": { + "additionalProperties": false, + "description": "RNA 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": "object" + }, + "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." + }, + "force": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null + }, + "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 + } + }, + "required": [ + "query_id" + ], + "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": "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": [ + { + "maximum": 2147483647, + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Random seed. Not used yet by this model, so runs are not reproducible." + }, + "templates": { + "anyOf": [ + { + "description": "Optional structural templates for prediction.", + "items": { + "$ref": "#/$defs/Template" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "required": [ + "complexes" + ], + "type": "object" + } + }, + "prott5-xl/batch/embeddings": { + "outputs": [ + "embeddings" + ], + "params": { + "additionalProperties": false, + "properties": { + "assay_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "ID of an assay whose sequences to run, in place of `sequences`." + }, + "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" + }, + { + "type": "null" + } + ], + "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" + }, + "random_seed": { + "anyOf": [ + { + "maximum": 4294967296, + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "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": { + "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." + }, + "smiles": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "required": [ + "id" + ], + "type": "object" + }, + "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": "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" + }, + { + "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" + }, + { + "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" + }, + { + "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": [ + { + "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" + }, + { + "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" + }, + "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" + }, + "query_id": { + "description": "ID of a query (sequence or structure) to condition on.", + "format": "uuid", + "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": { + "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" + }, + "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" + }, + "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" + } + }, + "required": [ + "query_id", + "sequences" + ], + "type": "object" + } + }, + "solublempnn/generate/sequences": { + "outputs": [ + "sequences", + "loglikelihood" + ], + "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": { + "anyOf": [ + { + "additionalProperties": { + "items": { + "items": { + "type": "number" + }, + "type": "array" + }, + "type": "array" + }, + "type": "object" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Per chain, one 21-element logit bias row per residue." + }, + "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" + }, + { + "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" + }, + "type": "array" + }, + "type": "array" + }, + { + "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" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Amino acids to exclude from every position." + }, + "omit_aas_per_chain_position": { + "anyOf": [ + { + "additionalProperties": { + "items": { + "maxItems": 2, + "minItems": 2, + "prefixItems": [ + { + "items": { + "type": "integer" + }, + "type": "array" + }, + { + "type": "string" + } + ], + "type": "array" + }, + "type": "array" + }, + "type": "object" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Per chain, [positions, amino acids] pairs excluding those amino acids at those positions." + }, + "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": "number" + }, + "type": "array" + }, + "type": "object" + }, + "type": "object" + }, + { + "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" + }, + "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." + }, + "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": [ + "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" + } + }, + "opendde/batch/structures": { + "outputs": [ + "structures" + ], + "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 + }, + "rna": { + "anyOf": [ + { + "$ref": "#/$defs/RNA" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "type": "object" + }, + "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" + ], + "type": "object" + }, + "Ion": { + "additionalProperties": false, + "properties": { + "ccd": { + "type": "string" + }, + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "description": "Unique chain identifier(s); a list for identical chains." + } + }, + "required": [ + "id", + "ccd" + ], + "type": "object" + }, + "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." + }, + "smiles": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "required": [ + "id" + ], + "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": "object" + }, + "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" + } + }, + "required": [ + "id", + "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": "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": [ + { + "maximum": 2147483647, + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Random seed; null for a random seed." + } + }, + "required": [ + "complexes" + ], + "type": "object" + } + }, + "opendde-abag/batch/structures": { + "outputs": [ + "structures" + ], + "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 + }, + "rna": { + "anyOf": [ + { + "$ref": "#/$defs/RNA" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "type": "object" + }, + "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" + ], + "type": "object" + }, + "Ion": { + "additionalProperties": false, + "properties": { + "ccd": { + "type": "string" + }, + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "description": "Unique chain identifier(s); a list for identical chains." + } + }, + "required": [ + "id", + "ccd" + ], + "type": "object" + }, + "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." + }, + "smiles": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "required": [ + "id" + ], + "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": "object" + }, + "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" + } + }, + "required": [ + "id", + "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": "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": [ + { + "maximum": 2147483647, + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Random seed; null for a random seed." + } + }, + "required": [ + "complexes" + ], + "type": "object" + } + } + } +} diff --git a/tests/data/test_accessors.py b/tests/data/test_accessors.py new file mode 100644 index 0000000..8a1168a --- /dev/null +++ b/tests/data/test_accessors.py @@ -0,0 +1,26 @@ +"""Stored msas and prompts are reached only through ``session.data.MSA`` and ``session.data.Prompt``.""" + +import pytest + +import openprotein.data +import openprotein.data.msa +import openprotein.data.prompts +from openprotein.data import DataAPI + + +@pytest.mark.parametrize("name", ["msa", "prompts"]) +def test_session_data_has_no_accessor_object(name): + assert not hasattr(DataAPI, name) + + +@pytest.mark.parametrize( + ("module", "name"), + [ + (openprotein.data, "MSADataAPI"), + (openprotein.data, "PromptsAPI"), + (openprotein.data.msa, "MSADataAPI"), + (openprotein.data.prompts, "PromptsAPI"), + ], +) +def test_the_accessor_classes_are_gone(module, name): + assert not hasattr(module, name) diff --git a/tests/data/test_assay_resource.py b/tests/data/test_assay_resource.py new file mode 100644 index 0000000..db7d22c --- /dev/null +++ b/tests/data/test_assay_resource.py @@ -0,0 +1,208 @@ +"""Assays through ``session.data.Assay``.""" + +import pickle +import warnings +from unittest.mock import MagicMock + +import pandas as pd +import pytest + +from openprotein.data import Assay, AssayDataset, DataAPI +from openprotein.data.schemas import AssayMetadata +from openprotein.errors import HTTPError +from openprotein.jobs.schemas import JobStatus + +METADATA = { + "assay_name": "stability", + "assay_description": "d", + "assay_id": "a1", + "original_filename": "data.csv", + "created_date": "2023-01-01T00:00:00", + "num_rows": 100, + "num_entries": 200, + "measurement_names": ["activity"], + "sequence_length": 4, +} + + +def _response(payload=None, status=200): + response = MagicMock(status_code=status) + response.json.return_value = payload + return response + + +@pytest.fixture +def session() -> MagicMock: + return MagicMock() + + +@pytest.fixture +def assay(session) -> Assay: + return Assay(session, AssayMetadata.model_validate(METADATA)) + + +def test_assay_dataset_is_the_same_class(): + assert AssayDataset is Assay + + +def test_session_data_hands_out_one_bound_assay_class(session): + data = DataAPI(session) + assert data.Assay is data.Assay + assert issubclass(data.Assay, AssayDataset) + + +def test_a_session_and_metadata_construct_an_assay_dataset(session): + dataset = AssayDataset(session, AssayMetadata.model_validate(METADATA)) + assert (dataset.id, dataset.session, dataset.page_size) == ("a1", session, 1000) + + +def test_create_uploads_the_table_and_returns_the_handle(session): + session.post.return_value = _response(METADATA) + table = pd.DataFrame({"sequence": ["ACDE"], "activity": [1.0], "notes": ["x"]}) + assay = DataAPI(session).Assay.create( + table, "stability", metadata_columns=["notes"] + ) + assert isinstance(assay, Assay) and assay.id == "a1" + args, kwargs = session.post.call_args + assert args == ("v1/assaydata",) + assert kwargs["data"] == { + "assay_name": "stability", + "assay_description": None, + "metadata_columns": '["notes"]', + } + + +def test_create_keeps_the_stored_sequence_length(session): + session.post.return_value = _response(METADATA | {"sequence_length": None}) + table = pd.DataFrame({"Sequence": ["ACDE", "AC"], "activity": [1.0, 2.0]}) + + assay = DataAPI(session).Assay.create(table, "stability") + + assert assay.sequence_length is None + assert list(table.columns) == ["Sequence", "activity"] + + +def test_list_follows_every_page(session, monkeypatch): + monkeypatch.setattr("openprotein.data.assaydataset._LIST_PAGE", 2) + rows = [METADATA | {"assay_id": f"a{i}"} for i in range(3)] + session.get.side_effect = [_response(rows[:2]), _response(rows[2:])] + assert [a.id for a in DataAPI(session).Assay.list()] == ["a0", "a1", "a2"] + assert [c.kwargs["params"] for c in session.get.call_args_list] == [ + {"limit": 2, "offset": 0}, + {"limit": 2, "offset": 2}, + ] + + +def test_list_stops_at_the_limit_and_starts_at_the_offset(session): + rows = [METADATA | {"assay_id": f"a{i}"} for i in range(3)] + session.get.return_value = _response(rows) + assert len(DataAPI(session).Assay.list(limit=3, offset=5)) == 3 + session.get.assert_called_once_with( + "v1/assaydata", params={"limit": 3, "offset": 5} + ) + + +def test_id_loads_one_assay(session): + session.get.return_value = _response(METADATA) + assay = DataAPI(session).Assay(id="a1") + assert (assay.id, assay.name, assay.description) == ("a1", "stability", "d") + assert (assay.status, assay.job_id) == (JobStatus.SUCCESS, None) + assert assay.created_at.year == 2023 + session.get.assert_called_once_with( + "v1/assaydata/metadata", params={"assay_id": "a1"} + ) + + +def test_an_unknown_id_raises_the_404(session): + session.get.side_effect = HTTPError(_response({"detail": "x"}, status=404)) + with pytest.raises(HTTPError) as error: + DataAPI(session).Assay(id="nope") + assert error.value.status_code == 404 + + +def test_len_is_the_row_count_without_a_request(assay, session): + assert len(assay) == 100 + session.get.assert_not_called() + + +def test_an_assay_is_true_when_it_has_rows(session): + empty = Assay(session, AssayMetadata.model_validate(METADATA | {"num_rows": 0})) + assert not empty + assert Assay(session, AssayMetadata.model_validate(METADATA)) + session.get.assert_not_called() + + +def test_update_sends_only_the_given_fields_and_returns_the_handle(assay, session): + session.put.return_value = _response(METADATA | {"assay_name": "new"}) + with warnings.catch_warnings(): + warnings.simplefilter("error") + assert assay.update(name="new") is assay + session.put.assert_called_once_with("v1/assaydata/a1", json={"assay_name": "new"}) + assert assay.name == "new" + + +def test_update_takes_the_assay_prefixed_keywords_with_a_warning(assay, session): + session.put.return_value = _response(METADATA) + with pytest.warns(FutureWarning, match=r"Use `Assay\.update\(name=") as record: + assay.update(assay_name="new", assay_description="e") + assert record[0].filename == __file__ + assert session.put.call_args.kwargs["json"] == { + "assay_name": "new", + "assay_description": "e", + } + + +def test_updating_a_pending_assay_keeps_its_job(session): + pending = METADATA | {"status": "RUNNING", "align_job_id": "job-1"} + assay = Assay(session, AssayMetadata.model_validate(pending)) + session.put.return_value = _response(METADATA | {"assay_name": "new"}) + session.get.return_value = _response(pending | {"assay_name": "new"}) + + assay.update(name="new") + + assert (assay.name, assay.status, assay.job_id) == ( + "new", + JobStatus.RUNNING, + "job-1", + ) + assert not assay.done() + session.get.assert_called_once_with( + "v1/assaydata/metadata", params={"assay_id": "a1"} + ) + + +def test_update_refuses_both_keywords_for_one_field(assay, session): + with pytest.raises(TypeError, match="without assay_name"): + assay.update(name="a", assay_name="b") + session.put.assert_not_called() + + +def test_delete_deletes_the_assay(assay, session): + assay.delete() + session.delete.assert_called_once_with("v1/assaydata/a1") + + +def test_refresh_reads_the_metadata_again(assay, session): + session.get.return_value = _response(METADATA | {"num_rows": 7}) + assert assay.refresh() is assay + assert len(assay) == 7 + + +def test_wait_on_a_ready_assay_returns_it(assay, session): + assert assay.wait() is assay + session.get.assert_not_called() + + +def test_an_assay_has_no_upload(): + assert not hasattr(Assay, "upload") + + +def test_an_assay_from_session_data_pickles(): + from openprotein.base import APISession + + session = APISession.__new__(APISession) + assay = DataAPI(session).Assay(session, AssayMetadata.model_validate(METADATA)) + assay.page_size = 10 + restored = pickle.loads(pickle.dumps(assay)) + assert isinstance(restored, Assay) + assert (restored.id, len(restored), restored.page_size) == ("a1", 100, 10) diff --git a/tests/data/test_data.py b/tests/data/test_data.py index 8225fc6..995a4cb 100644 --- a/tests/data/test_data.py +++ b/tests/data/test_data.py @@ -4,7 +4,6 @@ correctly call the low-level API functions, mocking only the session calls. """ -from datetime import datetime from unittest.mock import MagicMock import pandas as pd @@ -12,12 +11,13 @@ from openprotein.data.assaydataset import AssayDataset from openprotein.data.data import DataAPI -from openprotein.data.schemas import AssayDataPage, AssayDataRow, AssayMetadata +from openprotein.data.schemas import AssayMetadata +from openprotein.errors import HTTPError +from openprotein.jobs.schemas import JobStatus @pytest.fixture def sample_assay_metadata_dict() -> dict: - """Fixture for a sample AssayMetadata dictionary.""" return { "assay_name": "Test Assay", "assay_description": "A test assay", @@ -31,27 +31,23 @@ def sample_assay_metadata_dict() -> dict: } -# =================================== # DataAPI Tests -# =================================== - - def test_data_api_list(mock_session: MagicMock, sample_assay_metadata_dict: dict): - """Test DataAPI.list() method.""" mock_session.get.return_value.status_code = 200 mock_session.get.return_value.json.return_value = [sample_assay_metadata_dict] data_api = DataAPI(mock_session) result = data_api.list() - mock_session.get.assert_called_once_with("v1/assaydata", params={}) + mock_session.get.assert_called_once_with( + "v1/assaydata", params={"limit": 1000, "offset": 0} + ) assert len(result) == 1 assert isinstance(result[0], AssayDataset) assert result[0].id == "assay123" def test_data_api_create(mock_session: MagicMock, sample_assay_metadata_dict: dict): - """Test DataAPI.create() method.""" mock_session.post.return_value.status_code = 200 mock_session.post.return_value.json.return_value = sample_assay_metadata_dict data_api = DataAPI(mock_session) @@ -65,7 +61,6 @@ def test_data_api_create(mock_session: MagicMock, sample_assay_metadata_dict: di def test_data_api_get(mock_session: MagicMock, sample_assay_metadata_dict: dict): - """Test DataAPI.get() method.""" mock_session.get.return_value.status_code = 200 mock_session.get.return_value.json.return_value = sample_assay_metadata_dict data_api = DataAPI(mock_session) @@ -79,15 +74,10 @@ def test_data_api_get(mock_session: MagicMock, sample_assay_metadata_dict: dict) assert dataset.id == "assay123" -# =================================== # AssayDataset Tests -# =================================== - - def test_assay_dataset_update( mock_session: MagicMock, sample_assay_metadata_dict: dict ): - """Test AssayDataset.update() method.""" updated_meta_dict = sample_assay_metadata_dict.copy() updated_meta_dict["assay_name"] = "Updated Name" mock_session.put.return_value.status_code = 200 @@ -97,7 +87,7 @@ def test_assay_dataset_update( dataset.update(assay_name="Updated Name") mock_session.put.assert_called_once_with( - "v1/assaydata/assay123", data={"assay_name": "Updated Name"} + "v1/assaydata/assay123", json={"assay_name": "Updated Name"} ) assert dataset.name == "Updated Name" @@ -105,7 +95,6 @@ def test_assay_dataset_update( def test_assay_dataset_get_slice( mock_session: MagicMock, sample_assay_metadata_dict: dict ): - """Test AssayDataset.get_slice() method.""" row = {"mut_sequence": "SEQ", "measurement_values": [1.0]} page_data = { "assaymetadata": sample_assay_metadata_dict, @@ -126,3 +115,162 @@ def test_assay_dataset_get_slice( assert isinstance(df, pd.DataFrame) assert df.shape == (1, 2) assert "sequence" in df.columns + + +def test_data_api_create_metadata_columns( + mock_session: MagicMock, sample_assay_metadata_dict: dict +): + mock_session.post.return_value.status_code = 200 + mock_session.post.return_value.json.return_value = { + **sample_assay_metadata_dict, + "metadata_names": ["notes"], + } + data_api = DataAPI(mock_session) + df = pd.DataFrame({"sequence": ["SEQ"], "activity": [1.0], "notes": ["run 1"]}) + + result = data_api.create(df, "New Assay", metadata_columns=["notes"]) + + sent = mock_session.post.call_args.kwargs["data"] + assert sent["metadata_columns"] == '["notes"]' + assert result.metadata_names == ["notes"] + + +def test_assay_dataset_get_slice_include_metadata( + mock_session: MagicMock, sample_assay_metadata_dict: dict +): + metadata = {**sample_assay_metadata_dict, "metadata_names": ["notes", "run"]} + mock_session.get.return_value.status_code = 200 + mock_session.get.return_value.json.return_value = { + "assaymetadata": metadata, + "page_size": 2, + "page_offset": 0, + "assaydata": [ + { + "mut_sequence": "SEQ", + "measurement_values": [1.0], + "metadata_values": ["007", "r1"], + }, + { + "mut_sequence": "SEQ", + "measurement_values": [None], + "metadata_values": [None, "r2"], + }, + ], + } + + dataset = AssayDataset(mock_session, AssayMetadata(**metadata)) + df = dataset.get_slice(0, 2, include_metadata=True) + + assert mock_session.get.call_args.kwargs["params"]["include_metadata"] is True + assert list(df.columns) == ["sequence", "activity", "notes", "run"] + assert df["notes"].tolist() == ["007", None] + assert df["run"].tolist() == ["r1", "r2"] + + +@pytest.mark.parametrize("metadata_values", [None, [], ["007"]]) +def test_a_row_with_missing_metadata_reads_none_for_each_missing_value( + mock_session: MagicMock, sample_assay_metadata_dict: dict, metadata_values +): + metadata = {**sample_assay_metadata_dict, "metadata_names": ["notes", "run"]} + mock_session.get.return_value.status_code = 200 + mock_session.get.return_value.json.return_value = { + "assaymetadata": metadata, + "page_size": 1, + "page_offset": 0, + "assaydata": [ + { + "mut_sequence": "SEQ", + "measurement_values": [1.0], + "metadata_values": metadata_values, + } + ], + } + + dataset = AssayDataset(mock_session, AssayMetadata.model_validate(metadata)) + df = dataset.get_slice(0, 1, include_metadata=True) + + expected = (metadata_values or []) + [None] * (2 - len(metadata_values or [])) + assert [df["notes"][0], df["run"][0]] == expected + + +def test_assay_dataset_metadata_names_default(sample_assay_metadata_dict: dict): + dataset = AssayDataset(MagicMock(), AssayMetadata(**sample_assay_metadata_dict)) + assert dataset.metadata_names == [] + + +def test_data_api_create_empty_metadata_columns( + mock_session: MagicMock, sample_assay_metadata_dict: dict +): + mock_session.post.return_value.status_code = 200 + mock_session.post.return_value.json.return_value = sample_assay_metadata_dict + data_api = DataAPI(mock_session) + df = pd.DataFrame({"sequence": ["SEQ"], "activity": [1.0]}) + + data_api.create(df, "New Assay", metadata_columns=[]) + + sent = mock_session.post.call_args.kwargs["data"] + assert sent["metadata_columns"] == "[]" + + +def test_data_api_create_metadata_columns_rejects_str(mock_session: MagicMock): + data_api = DataAPI(mock_session) + df = pd.DataFrame({"sequence": ["SEQ"], "notes": ["run 1"]}) + + with pytest.raises(TypeError, match="list of column names"): + data_api.create(df, "New Assay", metadata_columns="notes") + + mock_session.post.assert_not_called() + + +def test_assay_dataset_get_slice_include_metadata_without_metadata( + mock_session: MagicMock, sample_assay_metadata_dict: dict +): + mock_session.get.return_value.status_code = 200 + mock_session.get.return_value.json.return_value = { + "assaymetadata": sample_assay_metadata_dict, + "page_size": 1, + "page_offset": 0, + "assaydata": [{"mut_sequence": "SEQ", "measurement_values": [1.0]}], + } + + dataset = AssayDataset(mock_session, AssayMetadata(**sample_assay_metadata_dict)) + df = dataset.get_slice(0, 1, include_metadata=True) + + assert list(df.columns) == ["sequence", "activity"] + assert df["activity"].tolist() == [1.0] + + +def test_assay_dataset_exposes_status_and_job_id( + mock_session: MagicMock, sample_assay_metadata_dict: dict +): + dataset = AssayDataset( + mock_session, + AssayMetadata( + **sample_assay_metadata_dict, status="RUNNING", align_job_id="job1" + ), + ) + assert dataset.status == JobStatus.RUNNING + assert dataset.job_id == "job1" + + +def test_assay_dataset_without_a_job_reads_success_and_no_job_id( + mock_session: MagicMock, sample_assay_metadata_dict: dict +): + dataset = AssayDataset( + mock_session, AssayMetadata(**sample_assay_metadata_dict, status=None) + ) + assert dataset.status == JobStatus.SUCCESS + assert dataset.job_id is None + + +def test_assay_dataset_get_slice_raises_a_409_for_a_dataset_that_is_not_ready( + mock_session: MagicMock, sample_assay_metadata_dict: dict +): + response = MagicMock() + response.status_code = 409 + response.json.return_value = {} + mock_session.get.side_effect = HTTPError(response) + dataset = AssayDataset(mock_session, AssayMetadata(**sample_assay_metadata_dict)) + with pytest.raises(HTTPError) as raised: + dataset.get_slice(0, 1) + assert raised.value.status_code == 409 diff --git a/tests/data/test_data_api.py b/tests/data/test_data_api.py index 9584ee0..1260f8c 100644 --- a/tests/data/test_data_api.py +++ b/tests/data/test_data_api.py @@ -1,9 +1,7 @@ from unittest.mock import MagicMock import pytest -from pydantic import TypeAdapter -from openprotein.base import APISession from openprotein.data.api import ( assaydata_list, assaydata_page_get, @@ -18,7 +16,6 @@ @pytest.fixture def sample_assay_metadata() -> dict: - """Fixture for sample assay metadata dictionary.""" return { "assay_name": "Test Assay", "assay_description": "A test assay", @@ -33,7 +30,6 @@ def sample_assay_metadata() -> dict: def test_list_models(mock_session: MagicMock) -> None: - """Test the list_models API function.""" mock_session.get.return_value.json.return_value = [{"model_id": "1"}] result = list_models(mock_session, "assay123") mock_session.get.assert_called_once_with( @@ -43,7 +39,6 @@ def test_list_models(mock_session: MagicMock) -> None: def test_assaydata_post(mock_session: MagicMock, sample_assay_metadata: dict) -> None: - """Test the assaydata_post API function.""" mock_response = MagicMock() mock_response.status_code = 200 mock_response.json.return_value = sample_assay_metadata @@ -62,7 +57,6 @@ def test_assaydata_post(mock_session: MagicMock, sample_assay_metadata: dict) -> def test_assaydata_post_error(mock_session: MagicMock) -> None: - """Test assaydata_post for non-200 response.""" mock_response = MagicMock() mock_response.status_code = 400 mock_session.post.return_value = mock_response @@ -71,7 +65,6 @@ def test_assaydata_post_error(mock_session: MagicMock) -> None: def test_assaydata_list(mock_session: MagicMock, sample_assay_metadata: dict) -> None: - """Test the assaydata_list API function.""" mock_response = MagicMock() mock_response.status_code = 200 mock_response.json.return_value = [sample_assay_metadata] @@ -84,7 +77,6 @@ def test_assaydata_list(mock_session: MagicMock, sample_assay_metadata: dict) -> def test_assaydata_list_error(mock_session: MagicMock) -> None: - """Test assaydata_list for non-200 response.""" mock_response = MagicMock() mock_response.status_code = 500 mock_session.get.return_value = mock_response @@ -95,7 +87,6 @@ def test_assaydata_list_error(mock_session: MagicMock) -> None: def test_get_assay_metadata( mock_session: MagicMock, sample_assay_metadata: dict ) -> None: - """Test the get_assay_metadata API function.""" mock_response = MagicMock() mock_response.status_code = 200 mock_response.json.return_value = sample_assay_metadata @@ -110,7 +101,6 @@ def test_get_assay_metadata( def test_get_assay_metadata_not_found(mock_session: MagicMock) -> None: - """Test get_assay_metadata for an empty response.""" mock_response = MagicMock() mock_response.status_code = 200 mock_response.json.return_value = [] # Simulate not found @@ -120,7 +110,6 @@ def test_get_assay_metadata_not_found(mock_session: MagicMock) -> None: def test_assaydata_put(mock_session: MagicMock, sample_assay_metadata: dict) -> None: - """Test the assaydata_put API function.""" mock_response = MagicMock() mock_response.status_code = 200 mock_response.json.return_value = sample_assay_metadata @@ -128,7 +117,7 @@ def test_assaydata_put(mock_session: MagicMock, sample_assay_metadata: dict) -> result = assaydata_put(mock_session, "assay123", "New Name") mock_session.put.assert_called_once_with( - "v1/assaydata/assay123", data={"assay_name": "New Name"} + "v1/assaydata/assay123", json={"assay_name": "New Name"} ) assert isinstance(result, AssayMetadata) @@ -136,7 +125,6 @@ def test_assaydata_put(mock_session: MagicMock, sample_assay_metadata: dict) -> def test_assaydata_page_get( mock_session: MagicMock, sample_assay_metadata: dict ) -> None: - """Test the assaydata_page_get API function.""" page_data = { "assaymetadata": sample_assay_metadata, "page_size": 1, @@ -156,3 +144,59 @@ def test_assaydata_page_get( ) assert isinstance(result, AssayDataPage) assert result.page_size == 1 + + +def test_assaydata_post_metadata_columns( + mock_session: MagicMock, sample_assay_metadata: dict +) -> None: + mock_session.post.return_value.status_code = 200 + mock_session.post.return_value.json.return_value = { + **sample_assay_metadata, + "metadata_names": ["notes"], + } + + result = assaydata_post( + mock_session, "file_content", "Test Assay", metadata_columns=["notes"] + ) + + mock_session.post.assert_called_once_with( + "v1/assaydata", + files={"assay_data": "file_content"}, + data={ + "assay_name": "Test Assay", + "assay_description": "", + "metadata_columns": '["notes"]', + }, + ) + assert result.metadata_names == ["notes"] + + +def test_assaydata_page_get_include_metadata( + mock_session: MagicMock, sample_assay_metadata: dict +) -> None: + mock_session.get.return_value.status_code = 200 + mock_session.get.return_value.json.return_value = { + "assaymetadata": {**sample_assay_metadata, "metadata_names": ["notes"]}, + "page_size": 1, + "page_offset": 0, + "assaydata": [ + { + "mut_sequence": "SEQ", + "measurement_values": [1.0], + "metadata_values": ["007"], + } + ], + } + + result = assaydata_page_get(mock_session, "assay123", include_metadata=True) + + mock_session.get.assert_called_once_with( + "v1/assaydata/assay123", + params={ + "page_offset": 0, + "page_size": 1000, + "format": "wide", + "include_metadata": True, + }, + ) + assert result.assaydata[0].metadata_values == ["007"] diff --git a/tests/data/test_data_deprecations.py b/tests/data/test_data_deprecations.py new file mode 100644 index 0000000..5fe1b67 --- /dev/null +++ b/tests/data/test_data_deprecations.py @@ -0,0 +1,82 @@ +"""The assay verbs on ``session.data`` still work, and say what replaces them.""" + +from unittest.mock import MagicMock + +import pandas as pd +import pytest + +from openprotein.data import AssayDataset, DataAPI + +METADATA = { + "assay_name": "stability", + "assay_description": "d", + "assay_id": "a1", + "original_filename": "data.csv", + "created_date": "2023-01-01T00:00:00", + "num_rows": 100, + "num_entries": 200, + "measurement_names": ["activity"], + "sequence_length": 4, +} + + +@pytest.fixture +def data() -> DataAPI: + session = MagicMock() + for verb in ("get", "post"): + getattr(session, verb).return_value.status_code = 200 + session.get.return_value.json.return_value = METADATA + session.post.return_value.json.return_value = METADATA + return DataAPI(session) + + +def _message(name: str, use: str) -> str: + return ( + f"`{name}` is deprecated since 0.18.0 and will be removed in 0.19.0. " + f"Use `{use}`." + ) + + +def _one_warning(record, name: str, use: str) -> None: + assert [str(warning.message) for warning in record] == [_message(name, use)] + assert record[0].filename == __file__ + + +def test_create_returns_the_assay_and_names_assay_create(data): + table = pd.DataFrame({"sequence": ["ACDE"], "activity": [1.0]}) + with pytest.warns(FutureWarning) as record: + assay = data.create(table, "stability", "d") + assert isinstance(assay, AssayDataset) and assay.id == "a1" + _one_warning(record, "session.data.create", "session.data.Assay.create") + + +@pytest.mark.parametrize("verb", ["get", "load_assay"]) +def test_get_and_load_assay_return_the_assay_and_name_the_id_load(data, verb): + with pytest.warns(FutureWarning) as record: + assay = getattr(data, verb)("a1") + assert isinstance(assay, AssayDataset) and assay.id == "a1" + _one_warning(record, f"session.data.{verb}", "session.data.Assay(id=...)") + + +def test_list_returns_the_assays_and_names_assay_list(data): + data.session.get.return_value.json.return_value = [METADATA] + with pytest.warns(FutureWarning) as record: + assays = data.list(limit=5, offset=2) + assert [assay.id for assay in assays] == ["a1"] + data.session.get.assert_called_once_with( + "v1/assaydata", params={"limit": 5, "offset": 2} + ) + _one_warning(record, "session.data.list", "session.data.Assay.list") + + +def test_len_counts_the_assays_and_names_the_list(data): + data.session.get.return_value.json.return_value = [METADATA, METADATA] + with pytest.warns(FutureWarning) as record: + count = len(data) + assert count == 2 + _one_warning(record, "len(session.data)", "len(session.data.Assay.list())") + + +@pytest.mark.parametrize("verb", ["create", "get", "list", "load_assay", "__len__"]) +def test_each_docstring_marks_the_deprecation(verb): + assert ".. deprecated:: 0.18.0" in getattr(DataAPI, verb).__doc__ diff --git a/tests/data/test_data_schemas.py b/tests/data/test_data_schemas.py index 97e04fe..2687112 100644 --- a/tests/data/test_data_schemas.py +++ b/tests/data/test_data_schemas.py @@ -4,10 +4,10 @@ from pydantic import ValidationError from openprotein.data.schemas import AssayDataPage, AssayDataRow, AssayMetadata +from openprotein.jobs.schemas import JobStatus def test_assay_metadata_schema_valid() -> None: - """Test AssayMetadata schema with valid data.""" data = { "assay_name": "Test Assay", "assay_description": "A test assay", @@ -25,7 +25,6 @@ def test_assay_metadata_schema_valid() -> None: def test_assay_metadata_schema_optional_fields() -> None: - """Test AssayMetadata with optional sequence_length.""" data = { "assay_name": "Test Assay", "assay_description": "A test assay", @@ -44,7 +43,6 @@ def test_assay_metadata_schema_optional_fields() -> None: @pytest.mark.parametrize("has_name_column", [True, False]) def test_assay_metadata_schema_has_name_column(has_name_column: bool) -> None: - """Test AssayMetadata round-trips the has_name_column flag from the server.""" data = { "assay_name": "Test Assay", "assay_description": "A test assay", @@ -61,7 +59,6 @@ def test_assay_metadata_schema_has_name_column(has_name_column: bool) -> None: def test_assay_metadata_schema_invalid_data() -> None: - """Test AssayMetadata with invalid data types.""" with pytest.raises(ValidationError): AssayMetadata( assay_name="Test Assay", @@ -76,7 +73,6 @@ def test_assay_metadata_schema_invalid_data() -> None: def test_assay_data_row_schema_valid() -> None: - """Test AssayDataRow schema with valid data.""" data = {"mut_sequence": "SEQ", "measurement_values": [1.0, 2.5, None]} assay_data_row = AssayDataRow(**data) assert assay_data_row.mut_sequence == "SEQ" @@ -84,13 +80,11 @@ def test_assay_data_row_schema_valid() -> None: def test_assay_data_row_schema_invalid() -> None: - """Test AssayDataRow with invalid data.""" with pytest.raises(ValidationError): AssayDataRow(mut_sequence="SEQ", measurement_values=["not-a-float"]) # type: ignore - testing invalid type def test_assay_data_page_schema_valid() -> None: - """Test AssayDataPage schema with nested valid data.""" metadata_data = { "assay_name": "Test Assay", "assay_description": "A test assay", @@ -115,3 +109,48 @@ def test_assay_data_page_schema_valid() -> None: assert len(page.assaydata) == 1 assert isinstance(page.assaydata[0], AssayDataRow) assert page.assaydata[0].mut_sequence == "SEQ" + + +_BASE_METADATA = { + "assay_name": "Test Assay", + "assay_description": "A test assay", + "assay_id": "assay123", + "original_filename": "data.csv", + "created_date": "2023-01-01T00:00:00", + "num_rows": 100, + "num_entries": 200, + "measurement_names": ["activity"], +} + + +def test_assay_metadata_null_status_reads_success_with_no_job() -> None: + metadata = AssayMetadata(**_BASE_METADATA, status=None) + assert metadata.status == JobStatus.SUCCESS + assert metadata.align_job_id is None + + +def test_assay_metadata_without_status_reads_success_with_no_job() -> None: + metadata = AssayMetadata(**_BASE_METADATA) + assert metadata.status == JobStatus.SUCCESS + assert metadata.align_job_id is None + + +def test_assay_metadata_parses_a_pending_dataset() -> None: + metadata = AssayMetadata( + **{ + **_BASE_METADATA, + "num_rows": 0, + "num_entries": 0, + "measurement_names": [], + "status": "RUNNING", + "align_job_id": "job1", + } + ) + assert metadata.status == JobStatus.RUNNING + assert metadata.align_job_id == "job1" + assert metadata.measurement_names == [] + + +@pytest.mark.parametrize("status", ["FAILURE", "CANCELED"]) +def test_assay_metadata_parses_terminal_job_statuses(status: str) -> None: + assert AssayMetadata(**_BASE_METADATA, status=status).status == JobStatus(status) diff --git a/tests/data/test_internal_assay_loads.py b/tests/data/test_internal_assay_loads.py new file mode 100644 index 0000000..21f6c95 --- /dev/null +++ b/tests/data/test_internal_assay_loads.py @@ -0,0 +1,64 @@ +"""SDK code loads assays through ``session.data.Assay``, so it raises no deprecation warning.""" + +import ast +import pathlib +import warnings +from unittest.mock import MagicMock + +import openprotein +from openprotein.data import AssayDataset +from openprotein.models import _inputs + +DEPRECATED = {"create", "get", "list", "load_assay"} +BRIDGE = pathlib.Path(openprotein.__file__).parent / "data" / "data.py" + + +def _deprecated_calls(path: pathlib.Path) -> list[str]: + calls = [] + for node in ast.walk(ast.parse(path.read_text())): + if not ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr in DEPRECATED + ): + continue + receiver = node.func.value + named = isinstance(receiver, ast.Name) and receiver.id == "data_api" + built = ( + isinstance(receiver, ast.Call) + and isinstance(receiver.func, ast.Name) + and receiver.func.id == "DataAPI" + ) + if named or built: + calls.append(f"{path.name}:{node.lineno} .{node.func.attr}()") + return calls + + +def test_no_sdk_module_calls_the_deprecated_assay_verbs(): + root = BRIDGE.parent.parent + found = [ + call + for path in sorted(root.rglob("*.py")) + if path != BRIDGE + for call in _deprecated_calls(path) + ] + assert found == [] + + +def test_an_assay_id_loads_without_a_warning(): + session = MagicMock() + session.get.return_value.status_code = 200 + session.get.return_value.json.return_value = { + "assay_name": "n", + "assay_description": "d", + "assay_id": "a1", + "original_filename": "f.csv", + "created_date": "2023-01-01T00:00:00", + "num_rows": 1, + "num_entries": 1, + "measurement_names": ["y"], + } + with warnings.catch_warnings(): + warnings.simplefilter("error") + assay = _inputs.as_dataset(session, "a1") + assert isinstance(assay, AssayDataset) and assay.id == "a1" diff --git a/tests/data/test_msa_api.py b/tests/data/test_msa_api.py new file mode 100644 index 0000000..8f42c69 --- /dev/null +++ b/tests/data/test_msa_api.py @@ -0,0 +1,292 @@ +"""Tests for the MSA data client.""" + +import inspect +from unittest.mock import MagicMock + +import pytest + +from openprotein.data.msa import MSA, MSAMetadata +from openprotein.data.msa._api import ( + MSAPage, + msa_delete, + msa_download, + msa_get_metadata, + msa_list, + msa_post, + msa_put, +) +from openprotein.errors import HTTPError +from openprotein.jobs.schemas import JobStatus + + +@pytest.fixture +def sample_metadata() -> dict: + """A stored-MSA metadata record as returned.""" + return { + "msa_id": "job123", + "msa_hash": "deadbeef", + "name": None, + "description": None, + "tags": [], + "project_uuid": "project-1", + "source_format": "a3m", + "num_sequences": 3, + "num_match_columns": 60, + "has_insertions": False, + "original_filename": "aln.a3m", + "digest": "d" * 64, + "created_at": "2026-07-20T00:00:00Z", + "updated_at": "2026-07-20T00:00:00Z", + } + + +@pytest.fixture +def search_metadata(sample_metadata) -> dict: + """A search row: no uploaded original, so no msa_hash or filename.""" + return sample_metadata | {"msa_hash": None, "original_filename": None} + + +@pytest.fixture +def mock_session(sample_metadata) -> MagicMock: + session = MagicMock() + for verb in ("get", "post", "put"): + getattr(session, verb).return_value.json.return_value = sample_metadata + return session + + +def test_msa_post_sends_multipart_file_and_form_fields(mock_session): + """The upload posts the file as multipart and format/name as form data.""" + meta = msa_post(mock_session, b">q\nACDE\n", format="a3m", name="n") + args, kwargs = mock_session.post.call_args + assert args[0] == "v1/data/msa" + assert kwargs["data"] == {"format": "a3m", "name": "n"} + filename, content = kwargs["files"]["file"] + assert content == b">q\nACDE\n" and filename == "msa.a3m" + assert isinstance(meta, MSAMetadata) and meta.msa_id == "job123" + + +def test_msa_post_omits_unset_optional_fields(mock_session): + """Only the fields the caller set are sent (no null name/description).""" + msa_post(mock_session, b">q\nACDE\n", format="fasta") + assert mock_session.post.call_args.kwargs["data"] == {"format": "fasta"} + + +def test_msa_get_metadata_reads_metadata_endpoint(mock_session): + """Metadata is read from the per-MSA metadata path.""" + msa_get_metadata(mock_session, "job123") + assert mock_session.get.call_args[0][0] == "v1/data/msa/job123/metadata" + + +def test_msa_list_passes_pagination(mock_session, sample_metadata): + """list omits limit by default and forwards offset/limit when set.""" + mock_session.get.return_value.json.return_value = { + "items": [sample_metadata], + "total": 1, + "limit": 50, + "offset": 0, + } + page = msa_list(mock_session) + assert mock_session.get.call_args[0][0] == "v1/data/msa" + assert mock_session.get.call_args.kwargs["params"] == {"offset": 0} + + msa_list(mock_session, limit=50, offset=10) + assert mock_session.get.call_args.kwargs["params"] == {"offset": 10, "limit": 50} + assert page.total == 1 and page.items[0].msa_id == "job123" + + +def test_msa_download_defaults_to_stored_format(mock_session): + """download with no format sends no format param and returns raw bytes.""" + mock_session.get.return_value.content = b"A3M-BYTES" + assert msa_download(mock_session, "job123") == b"A3M-BYTES" + args, kwargs = mock_session.get.call_args + assert args[0] == "v1/data/msa/job123" + assert kwargs["params"] is None + + +def test_msa_download_with_format_converts(mock_session): + """download passes the requested format through as a query param.""" + mock_session.get.return_value.content = b"FASTA" + msa_download(mock_session, "job123", format="fasta") + assert mock_session.get.call_args.kwargs["params"] == {"format": "fasta"} + + +def test_msa_put_sends_only_the_given_fields(mock_session): + msa_put(mock_session, "job123", name="new", tags=["x"]) + args, kwargs = mock_session.put.call_args + assert args[0] == "v1/data/msa/job123" + assert kwargs["json"] == {"name": "new", "tags": ["x"]} + + +def test_msa_delete_calls_delete_endpoint(mock_session): + """delete issues a DELETE to the MSA path and returns None.""" + assert msa_delete(mock_session, "job123") is None + assert mock_session.delete.call_args[0][0] == "v1/data/msa/job123" + + +def test_create_encodes_str_and_wraps_result(mock_session): + """create encodes a str body to bytes and returns an MSA wrapper.""" + msa = MSA._bind(mock_session).create(">q\nACDE\n", format="a3m") + _, kwargs = mock_session.post.call_args + assert kwargs["files"]["file"][1] == b">q\nACDE\n" + assert isinstance(msa, MSA) and msa.id == "job123" + + +def _page(items, total, offset=0, limit=50): + return {"items": items, "total": total, "limit": limit, "offset": offset} + + +def test_list_follows_every_page(mock_session, sample_metadata): + second = sample_metadata | {"msa_id": "job456"} + mock_session.get.return_value.json.side_effect = [ + _page([sample_metadata], total=2), + _page([second], total=2, offset=1), + ] + + out = MSA._bind(mock_session).list() + + assert [msa.id for msa in out] == ["job123", "job456"] + assert [c.kwargs["params"] for c in mock_session.get.call_args_list] == [ + {"offset": 0, "limit": 200}, + {"offset": 1, "limit": 200}, + ] + + +def test_list_stops_at_limit(mock_session, sample_metadata): + second = sample_metadata | {"msa_id": "job456"} + mock_session.get.return_value.json.side_effect = [ + _page([sample_metadata], total=3, limit=1), + _page([second], total=3, offset=1, limit=1), + ] + + out = MSA._bind(mock_session).list(limit=2) + + assert [msa.id for msa in out] == ["job123", "job456"] + assert [c.kwargs["params"] for c in mock_session.get.call_args_list] == [ + {"offset": 0, "limit": 2}, + {"offset": 1, "limit": 1}, + ] + + +def test_msa_wrapper_methods_route_to_its_id(mock_session, sample_metadata): + """MSA.to_string/update/delete act on the wrapped msa_id.""" + mock_session.get.return_value.content = b"body" + msa = MSA(mock_session, MSAMetadata.model_validate(sample_metadata)) + + assert msa.to_string() == "body" + assert mock_session.get.call_args[0][0] == "v1/data/msa/job123" + + msa.update(description="d") + assert mock_session.put.call_args.kwargs["json"] == {"description": "d"} + + msa.delete() + assert mock_session.delete.call_args[0][0] == "v1/data/msa/job123" + + +def test_search_rows_read_with_null_hash_and_filename(search_metadata): + meta = MSAMetadata.model_validate(search_metadata) + assert meta.msa_hash is None and meta.original_filename is None + assert meta.digest == "d" * 64 + + +def test_session_data_reaches_msas_only_through_its_class(): + from openprotein.data import DataAPI + + assert not hasattr(DataAPI, "msa") + assert not hasattr(DataAPI, "msas") + + +def _error(status: int) -> HTTPError: + response = MagicMock() + response.status_code = status + return HTTPError(response) + + +@pytest.fixture +def pending_metadata(sample_metadata) -> dict: + """A row whose search hasn't finished: no content, so no stats.""" + return sample_metadata | { + "status": "RUNNING", + "job_id": "job123", + "msa_hash": None, + "source_format": None, + "num_sequences": None, + "num_match_columns": None, + "has_insertions": None, + "original_filename": None, + "digest": None, + } + + +def test_a_pending_row_parses_with_its_status_and_job(mock_session, pending_metadata): + msa = MSA(mock_session, MSAMetadata.model_validate(pending_metadata)) + assert (msa.status, msa.job_id) == (JobStatus.RUNNING, "job123") + assert (msa.source_format, msa.num_sequences, msa.has_insertions) == ( + None, + None, + None, + ) + + +def test_a_row_without_a_status_is_ready(sample_metadata): + meta = MSAMetadata.model_validate(sample_metadata) + assert (meta.status, meta.job_id) == (JobStatus.SUCCESS, None) + + +def test_a_page_mixing_pending_and_ready_rows_parses( + mock_session, sample_metadata, pending_metadata +): + mock_session.get.return_value.json.return_value = { + "items": [pending_metadata, sample_metadata], + "total": 2, + "limit": 50, + "offset": 0, + } + page = msa_list(mock_session) + assert isinstance(page, MSAPage) + assert [item.status for item in page.items] == [ + JobStatus.RUNNING, + JobStatus.SUCCESS, + ] + + +def test_get_returns_a_pending_row(mock_session, pending_metadata): + mock_session.get.return_value.json.return_value = pending_metadata + msa = MSA._bind(mock_session)(id="job123") + assert msa.status == JobStatus.RUNNING + mock_session.get.assert_called_once_with("v1/data/msa/job123/metadata") + + +@pytest.mark.parametrize("status", [404, 425]) +def test_get_raises_a_404_for_a_404_or_425(mock_session, status): + mock_session.get.side_effect = _error(status) + with pytest.raises(HTTPError) as raised: + MSA._bind(mock_session)(id="job123") + assert raised.value.status_code == 404 + assert mock_session.get.call_count == 1 + + +def test_get_returns_a_live_row(mock_session): + msa = MSA._bind(mock_session)(id="job123") + assert msa.metadata.msa_hash == "deadbeef" + mock_session.get.assert_called_once_with("v1/data/msa/job123/metadata") + + +def test_download_reads_only_the_data_route(mock_session): + mock_session.get.return_value.content = b"PAR1...PAR1" + + assert msa_download(mock_session, "job123", format="parquet") == b"PAR1...PAR1" + mock_session.get.assert_called_once_with( + "v1/data/msa/job123", params={"format": "parquet"} + ) + + +def test_an_msa_names_its_row_by_id_and_digest(mock_session, sample_metadata): + msa = MSA(mock_session, MSAMetadata.model_validate(sample_metadata)) + assert (msa.id, msa.digest) == ("job123", "d" * 64) + assert msa.metadata.msa_hash == "deadbeef" + assert not any(hasattr(msa, n) for n in ("msa_id", "msa_hash", "project_uuid")) + + +def test_update_takes_name_description_and_tags(): + params = list(inspect.signature(MSA.update).parameters) + assert params[-3:] == ["name", "description", "tags"] diff --git a/tests/data/test_msa_resource.py b/tests/data/test_msa_resource.py new file mode 100644 index 0000000..2dd375c --- /dev/null +++ b/tests/data/test_msa_resource.py @@ -0,0 +1,261 @@ +"""Stored MSAs through ``session.data.MSA``.""" + +import inspect +from unittest.mock import MagicMock + +import pytest + +from openprotein.data import MSA, DataAPI +from openprotein.data.msa import MSAMetadata +from openprotein.errors import HTTPError, JobOutputsNotReady +from openprotein.jobs.schemas import JobStatus + +METADATA = { + "msa_id": "m1", + "name": "n", + "description": None, + "tags": ["t"], + "source_format": "a3m", + "num_sequences": 3, + "num_match_columns": 4, + "has_insertions": True, + "digest": "d" * 64, + "created_at": "2026-07-20T00:00:00Z", + "updated_at": "2026-07-21T00:00:00Z", +} +FASTA = b">query\nACDE\n>h1 desc\nAC-E\n>h2\n-CDE\n" +ROWS = [("query", "ACDE"), ("h1 desc", "AC-E"), ("h2", "-CDE")] + + +def _response(payload=None, content=b"", status=200): + response = MagicMock(status_code=status, content=content) + response.json.return_value = payload + return response + + +@pytest.fixture +def session() -> MagicMock: + return MagicMock() + + +@pytest.fixture +def msa(session) -> MSA: + session.get.return_value = _response(content=FASTA) + return MSA(session, MSAMetadata.model_validate(METADATA)) + + +def test_session_data_hands_out_one_bound_msa_class(session): + data = DataAPI(session) + assert data.MSA is data.MSA + assert issubclass(data.MSA, MSA) + assert data.MSA._bound() is session + + +def test_create_uploads_and_returns_the_handle(session): + session.post.return_value = _response(METADATA) + msa = DataAPI(session).MSA.create(">q\nACDE\n", format="a3m", name="n") + assert isinstance(msa, MSA) and msa.id == "m1" + _, kwargs = session.post.call_args + assert kwargs["data"] == {"format": "a3m", "name": "n"} + assert kwargs["files"]["file"] == ("msa.a3m", b">q\nACDE\n") + + +def test_list_follows_every_page_up_to_the_limit(session): + rows = [METADATA | {"msa_id": f"m{i}"} for i in range(3)] + session.get.side_effect = [ + _response({"items": rows[:2], "total": 3, "limit": 2, "offset": 0}), + _response({"items": rows[2:], "total": 3, "limit": 2, "offset": 2}), + ] + assert [m.id for m in DataAPI(session).MSA.list()] == ["m0", "m1", "m2"] + assert [c.kwargs["params"]["offset"] for c in session.get.call_args_list] == [0, 2] + + +def test_list_asks_for_at_most_the_routes_page_limit(session): + rows = [METADATA | {"msa_id": f"m{i}"} for i in range(201)] + session.get.side_effect = [ + _response({"items": rows[:200], "total": 300, "limit": 200, "offset": 0}), + _response({"items": rows[200:], "total": 300, "limit": 1, "offset": 200}), + ] + + msas = DataAPI(session).MSA.list(limit=201) + + assert len(msas) == 201 + assert [call.kwargs["params"] for call in session.get.call_args_list] == [ + {"offset": 0, "limit": 200}, + {"offset": 200, "limit": 1}, + ] + + +def test_list_takes_only_a_limit(): + assert list(inspect.signature(MSA.list).parameters) == ["limit"] + + +def test_id_loads_one_msa(session): + session.get.return_value = _response(METADATA) + msa = DataAPI(session).MSA(id="m1") + assert (msa.id, msa.name, msa.tags) == ("m1", "n", ["t"]) + session.get.assert_called_once_with("v1/data/msa/m1/metadata") + + +def test_an_unknown_id_raises_the_404(session): + session.get.side_effect = HTTPError(_response(status=404)) + with pytest.raises(HTTPError) as error: + DataAPI(session).MSA(id="nope") + assert error.value.status_code == 404 + + +def test_the_handle_names_the_shared_fields(msa): + assert (msa.id, msa.name, msa.description) == ("m1", "n", None) + assert (msa.status, msa.job_id) == (JobStatus.SUCCESS, None) + assert msa.created_at.year == 2026 and msa.updated_at.day == 21 + assert msa.metadata.num_match_columns == 4 + + +def test_len_is_the_sequence_count_without_a_request(msa, session): + assert len(msa) == 3 + session.get.assert_not_called() + + +def test_an_a3m_msa_iterates_its_fasta_rendering(msa, session): + assert list(msa) == ROWS + session.get.assert_called_once_with("v1/data/msa/m1", params={"format": "fasta"}) + + +def _stored(session, source_format, match_columns, *bodies): + session.get.side_effect = [_response(content=body) for body in bodies] + metadata = METADATA | { + "source_format": source_format, + "num_match_columns": match_columns, + } + return MSA(session, MSAMetadata.model_validate(metadata)) + + +def _formats(session): + return [call.kwargs["params"]["format"] for call in session.get.call_args_list] + + +def test_an_a2m_msa_iterates_its_match_columns(session): + msa = _stored(session, "a2m", 4, b">query\nAC.DE\n>h1 desc\nACg-E\n>h2\n-C.DE\n") + assert list(msa) == ROWS + assert _formats(session) == ["a2m"] + + +def test_a_complex_keeps_its_chain_breaks_without_its_header(session): + msa = _stored(session, "a2m", 5, b"#4,1\t1,1\n>q\nAC.DE:F\n>h\nACgDE:F\n") + assert list(msa) == [("q", "ACDE:F"), ("h", "ACDE:F")] + + +def test_a_stockholm_msa_with_lowercase_inserts_iterates_its_match_columns(session): + msa = _stored(session, "sto", 4, b">q\nAC..DE\n>s1\nACkkDE\n") + assert list(msa) == [("q", "ACDE"), ("s1", "ACDE")] + assert _formats(session) == ["a2m"] + + +def test_a_stockholm_msa_whose_inserts_are_unmarked_iterates_every_column(session): + msa = _stored(session, "sto", 4, b">q\nACDE\n>s1\nAC.E\n", b">q\nACDE\n>s1\nAC-E\n") + assert list(msa) == [("q", "ACDE"), ("s1", "AC-E")] + assert _formats(session) == ["a2m", "fasta"] + + +@pytest.mark.parametrize( + ("source_format", "match_columns", "a2m", "fasta"), + [ + pytest.param( + "sto", + 9, + b">q\nMKV.LAAGIT\n>s1\nMKVQLA.GIT\n>s2\nMK.ALAAGIT\n", + b">q\nMKV-LAAGIT\n>s1\nMKVQLA-GIT\n>s2\nMK-ALAAGIT\n", + id="sto-dot-gaps", + ), + pytest.param( + "sto", + 7, + b">q\nMKVlaAGIT\n>s1\nMKvqLAGIT\n", + b">q\nMKVLAAGIT\n>s1\nMKVQLAGIT\n", + id="sto-soft-masked", + ), + pytest.param( + "a2m", + 6, + b">q\nACD.EFG\n>s1\nAC.DEFG\n", + b">q\nACD-EFG\n>s1\nAC-DEFG\n", + id="a2m-disagreeing-inserts", + ), + ], +) +def test_rows_that_mark_different_insert_columns_iterate_every_column( + session, source_format, match_columns, a2m, fasta +): + msa = _stored(session, source_format, match_columns, a2m, fasta) + assert [sequence for _, sequence in msa] == fasta.decode().split()[1::2] + assert _formats(session) == ["a2m", "fasta"] + + +def test_an_msa_with_no_match_columns_iterates_every_column(session): + msa = _stored(session, "sto", 0, b">q\nMKVLAAGIT\n>s1\nMKVQLAGIT\n") + assert list(msa) == [("q", "MKVLAAGIT"), ("s1", "MKVQLAGIT")] + assert _formats(session) == ["fasta"] + + +def test_indexing_reads_one_row_or_a_slice(msa): + assert msa[0] == ROWS[0] + assert msa[-1] == ROWS[2] + assert msa[1:] == ROWS[1:] + + +def test_rows_are_downloaded_once_per_handle(msa, session): + assert list(msa) == list(msa) == ROWS + assert dict(msa)["h2"] == "-CDE" + assert session.get.call_count == 1 + + +def test_refresh_makes_the_next_read_download_again(msa, session): + list(msa) + session.get.side_effect = [_response(METADATA), _response(content=FASTA)] + assert msa.refresh() is msa + list(msa) + assert session.get.call_count == 3 + + +def test_to_string_defaults_to_the_stored_format(msa, session): + session.get.return_value = _response(content=b">q\nACaDE\n") + assert msa.to_string() == ">q\nACaDE\n" + session.get.assert_called_once_with("v1/data/msa/m1", params=None) + + +def test_to_string_renders_the_named_format(msa, session): + msa.to_string("sto") + session.get.assert_called_once_with("v1/data/msa/m1", params={"format": "sto"}) + + +def test_to_string_refuses_a_format_it_cannot_render(msa, session): + with pytest.raises(ValueError, match="a2m, a3m, csv, fasta, sto.*'parquet'"): + msa.to_string("parquet") + session.get.assert_not_called() + + +@pytest.mark.parametrize("read", [list, len, lambda m: m[0], lambda m: m.to_string()]) +def test_reading_a_pending_msa_names_its_status_and_downloads_nothing(session, read): + pending = METADATA | {"status": "RUNNING", "job_id": "m1", "num_sequences": None} + session.get.return_value = _response(pending) + msa = MSA(session, MSAMetadata.model_validate(pending)) + with pytest.raises(JobOutputsNotReady, match="MSA m1 is RUNNING"): + read(msa) + session.get.assert_called_once_with("v1/data/msa/m1/metadata") + + +def test_update_sends_only_the_given_fields_and_returns_the_handle(msa, session): + session.put.return_value = _response(METADATA | {"tags": ["x"]}) + assert msa.update(tags=["x"]) is msa + assert session.put.call_args.kwargs["json"] == {"tags": ["x"]} + assert msa.tags == ["x"] + + +def test_delete_deletes_the_row(msa, session): + msa.delete() + session.delete.assert_called_once_with("v1/data/msa/m1") + + +@pytest.mark.parametrize("name", ["download", "upload"]) +def test_an_msa_has_no_download_or_upload(name): + assert not hasattr(MSA, name) diff --git a/tests/data/test_prompt_resource.py b/tests/data/test_prompt_resource.py new file mode 100644 index 0000000..e48f4e3 --- /dev/null +++ b/tests/data/test_prompt_resource.py @@ -0,0 +1,191 @@ +"""Stored prompts through ``session.data.Prompt``.""" + +import inspect +import io +import zipfile +from unittest.mock import MagicMock + +import pytest + +from openprotein.data import DataAPI, Prompt +from openprotein.data.prompts import PromptSummary +from openprotein.errors import HTTPError, JobOutputsNotReady +from openprotein.jobs.schemas import JobStatus +from openprotein.prompt.schemas import PromptMetadata + +SUMMARY = { + "id": "p1", + "owner": "user-1", + "digest": "d" * 64, + "name": "n", + "description": None, + "created_at": "2026-07-20T00:00:00Z", +} +SAMPLED = PromptMetadata( + id="s1", + name="prompt-abc", + description=None, + created_date="2026-09-05T08:00:00Z", + num_replicates=1, + job_id="s1", + status=JobStatus.SUCCESS, +) + + +def _zip(*replicates: bytes) -> bytes: + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w") as archive: + for position, content in enumerate(replicates): + archive.writestr(f"replicate-{position}.fasta", content) + return buffer.getvalue() + + +def _response(payload=None, content=b"", status=200): + response = MagicMock(status_code=status, content=content) + response.json.return_value = payload + return response + + +def _not_found() -> HTTPError: + return HTTPError(_response({"detail": "prompt not found"}, status=404)) + + +@pytest.fixture +def session() -> MagicMock: + return MagicMock() + + +@pytest.fixture +def prompt(session) -> Prompt: + session.get.return_value = _response( + content=_zip(b">a\nACDE\n>b\nAC:DE\n", b">a\nMKVL\n") + ) + return Prompt(session, PromptSummary.model_validate(SUMMARY)) + + +def test_session_data_hands_out_one_bound_prompt_class(session): + data = DataAPI(session) + assert data.Prompt is data.Prompt + assert issubclass(data.Prompt, Prompt) + + +def test_create_uploads_one_file_per_replicate(session): + session.post.return_value = _response(SUMMARY) + prompt = DataAPI(session).Prompt.create([">a\nACDE\n", b">a\nMKVL\n"], name="n") + assert isinstance(prompt, Prompt) and prompt.id == "p1" + _, kwargs = session.post.call_args + assert kwargs["data"] == {"name": "n"} + assert kwargs["files"] == [ + ("replicates", ("replicate-0.fasta", b">a\nACDE\n")), + ("replicates", ("replicate-1.fasta", b">a\nMKVL\n")), + ] + + +@pytest.mark.parametrize("contents", [">a\nAC\n", b">a\nAC\n"], ids=["str", "bytes"]) +def test_create_refuses_a_bare_file_before_any_request(session, contents): + with pytest.raises(TypeError, match=r"create\(\[contents\]\)"): + DataAPI(session).Prompt.create(contents) + assert session.mock_calls == [] + + +def test_list_follows_every_page_up_to_the_limit(session): + rows = [SUMMARY | {"id": f"p{i}"} for i in range(3)] + session.get.side_effect = [ + _response({"items": rows[:2], "next": "cursor"}), + _response({"items": rows[2:], "next": None}), + ] + assert [p.id for p in DataAPI(session).Prompt.list()] == ["p0", "p1", "p2"] + assert session.get.call_args_list[1].kwargs["params"] == { + "after": "cursor", + "limit": 200, + } + assert {call.args[0] for call in session.get.call_args_list} == {"v1/data/prompts"} + + +def test_list_asks_for_at_most_the_routes_page_limit(session): + rows = [SUMMARY | {"id": f"p{i}"} for i in range(201)] + session.get.side_effect = [ + _response({"items": rows[:200], "next": "cursor"}), + _response({"items": rows[200:], "next": "more"}), + ] + + prompts = DataAPI(session).Prompt.list(limit=201) + + assert len(prompts) == 201 + assert [call.kwargs["params"] for call in session.get.call_args_list] == [ + {"limit": 200}, + {"after": "cursor", "limit": 1}, + ] + + +def test_list_takes_only_a_limit(): + assert list(inspect.signature(Prompt.list).parameters) == ["limit"] + + +def test_id_loads_a_stored_prompt(session): + session.get.return_value = _response(SUMMARY) + prompt = DataAPI(session).Prompt(id="p1") + assert (prompt.id, prompt.name, prompt.owner) == ("p1", "n", "user-1") + assert (prompt.status, prompt.job_id) == (JobStatus.SUCCESS, None) + session.get.assert_called_once_with("v1/data/prompts/p1") + + +def test_an_unknown_id_raises_the_404(session): + session.get.side_effect = _not_found() + with pytest.raises(HTTPError) as error: + DataAPI(session).Prompt(id="nope") + assert error.value.status_code == 404 + session.get.assert_called_once_with("v1/data/prompts/nope") + + +def test_reading_a_prompt_the_data_routes_do_not_hold_raises_the_404(session): + session.get.side_effect = _not_found() + prompt = Prompt(session, PromptSummary(id="s1", status=JobStatus.SUCCESS)) + 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") + + +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") + + +def test_len_and_indexing_read_the_replicates(prompt): + assert len(prompt) == 2 + assert prompt[1] == ["MKVL"] + assert prompt[:1] == [["ACDE", "AC:DE"]] + + +def test_replicates_are_read_once_per_handle(prompt, session): + assert list(prompt) == list(prompt) + assert session.get.call_count == 1 + + +@pytest.mark.parametrize("read", [list, len, lambda p: p[0]]) +def test_reading_a_pending_prompt_names_its_status(session, read): + pending = SUMMARY | {"status": "PENDING", "job_id": "p1"} + session.get.return_value = _response(pending) + prompt = Prompt(session, PromptSummary.model_validate(pending)) + with pytest.raises(JobOutputsNotReady, match="Prompt p1 is PENDING"): + read(prompt) + session.get.assert_called_once_with("v1/data/prompts/p1") + + +def test_update_sends_only_the_given_fields_and_returns_the_handle(prompt, session): + session.patch.return_value = _response(SUMMARY | {"name": "new"}) + assert prompt.update(name="new") is prompt + assert session.patch.call_args.kwargs["json"] == {"name": "new"} + assert prompt.name == "new" + + +def test_delete_deletes_the_row(prompt, session): + prompt.delete() + session.delete.assert_called_once_with("v1/data/prompts/p1") + + +@pytest.mark.parametrize("name", ["download", "replicates", "record", "upload"]) +def test_a_prompt_has_no_download_replicates_record_or_upload(name): + assert not hasattr(Prompt, name) + assert not hasattr(Prompt(MagicMock(), PromptSummary(id="p1")), name) diff --git a/tests/data/test_prompts_api.py b/tests/data/test_prompts_api.py new file mode 100644 index 0000000..541b333 --- /dev/null +++ b/tests/data/test_prompts_api.py @@ -0,0 +1,289 @@ +"""Tests for stored prompts (``session.data.Prompt``) and their wire calls.""" + +from unittest.mock import MagicMock + +import pytest + +from openprotein.data.prompts import Prompt, PromptRecord, PromptSummary +from openprotein.data.prompts._api import ( + prompts_delete, + prompts_download, + prompts_get, + prompts_list, + prompts_post, + prompts_put, +) +from openprotein.errors import HTTPError +from openprotein.jobs.schemas import JobStatus + + +@pytest.fixture +def sample_summary() -> dict: + return { + "id": "prompt123", + "owner": "user-1", + "name": None, + "description": None, + "created_at": "2026-07-20T00:00:00Z", + } + + +@pytest.fixture +def sample_record(sample_summary) -> dict: + return { + **sample_summary, + "value": [ + { + "position": 0, + "value": { + "ref": {"download_url": "https://example.test/uploads/deadbeef"} + }, + } + ], + } + + +@pytest.fixture +def mock_session(sample_record) -> MagicMock: + session = MagicMock() + for verb in ("get", "post", "patch"): + getattr(session, verb).return_value.json.return_value = sample_record + return session + + +def _zip_of(replicates: list[bytes]) -> bytes: + import io + import zipfile + + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w") as archive: + for position, content in enumerate(replicates): + archive.writestr(f"replicate-{position}.fasta", content) + return buf.getvalue() + + +def test_prompts_list_passes_pagination(mock_session, sample_summary): + mock_session.get.return_value.json.return_value = { + "items": [sample_summary], + "next": None, + } + page = prompts_list(mock_session) + assert mock_session.get.call_args[0][0] == "v1/data/prompts" + assert mock_session.get.call_args.kwargs["params"] is None + + prompts_list(mock_session, after="cursor-1", limit=10) + assert mock_session.get.call_args.kwargs["params"] == { + "after": "cursor-1", + "limit": 10, + } + assert page.items[0].id == "prompt123" + + +def test_prompts_get_reads_the_row(mock_session): + record = prompts_get(mock_session, "prompt123") + assert mock_session.get.call_args[0][0] == "v1/data/prompts/prompt123" + assert isinstance(record, PromptRecord) + assert record.value[0].position == 0 + + +def test_prompts_put_sends_only_changed_fields(mock_session): + prompts_put(mock_session, "prompt123", name="new") + args, kwargs = mock_session.patch.call_args + assert args[0] == "v1/data/prompts/prompt123" + assert kwargs["json"] == {"name": "new"} + + +def test_prompts_delete_calls_delete_endpoint(mock_session): + assert prompts_delete(mock_session, "prompt123") is None + assert mock_session.delete.call_args[0][0] == "v1/data/prompts/prompt123" + + +def test_prompts_post_sends_one_file_per_replicate_under_one_field(mock_session): + prompts_post(mock_session, [b">c1\nACDE\n", b">c1\nMKVL\n"], name="n") + args, kwargs = mock_session.post.call_args + assert args[0] == "v1/data/prompts" + assert kwargs["data"] == {"name": "n"} + assert [field for field, _ in kwargs["files"]] == ["replicates", "replicates"] + names_and_contents = [value for _, value in kwargs["files"]] + assert names_and_contents == [ + ("replicate-0.fasta", b">c1\nACDE\n"), + ("replicate-1.fasta", b">c1\nMKVL\n"), + ] + + +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" + + +def _http_error(status_code: int, payload: dict) -> HTTPError: + response = MagicMock() + response.status_code = status_code + response.json.return_value = payload + return HTTPError(response) + + +def test_prompts_get_reraises_other_statuses(mock_session): + mock_session.get.side_effect = _http_error(404, {}) + + with pytest.raises(HTTPError): + prompts_get(mock_session, "prompt123") + + +def test_upload_encodes_str_and_wraps_result(mock_session): + api = Prompt._bind(mock_session) + prompt = api.create([">c1\nACDE\n"]) + _, kwargs = mock_session.post.call_args + assert kwargs["files"][0][1] == ("replicate-0.fasta", b">c1\nACDE\n") + assert isinstance(prompt, Prompt) and prompt.id == "prompt123" + + +def test_list_wraps_items(mock_session, sample_summary): + mock_session.get.return_value.json.return_value = { + "items": [sample_summary], + "next": None, + } + api = Prompt._bind(mock_session) + out = api.list() + assert len(out) == 1 and isinstance(out[0], Prompt) + assert out[0].owner == "user-1" + + +def test_list_follows_next_across_two_pages(mock_session, sample_summary): + second_summary = {**sample_summary, "id": "prompt456"} + mock_session.get.side_effect = [ + MagicMock(json=lambda: {"items": [sample_summary], "next": "cursor-1"}), + MagicMock(json=lambda: {"items": [second_summary], "next": None}), + ] + api = Prompt._bind(mock_session) + + out = api.list() + + assert [prompt.id for prompt in out] == ["prompt123", "prompt456"] + assert mock_session.get.call_args_list[0].kwargs["params"] == {"limit": 200} + assert mock_session.get.call_args_list[1].kwargs["params"] == { + "after": "cursor-1", + "limit": 200, + } + + +def test_list_stops_at_limit(mock_session, sample_summary): + second_summary = {**sample_summary, "id": "prompt456"} + mock_session.get.side_effect = [ + MagicMock(json=lambda: {"items": [sample_summary], "next": "cursor-1"}), + MagicMock(json=lambda: {"items": [second_summary], "next": "cursor-2"}), + ] + + out = Prompt._bind(mock_session).list(limit=2) + + assert [prompt.id for prompt in out] == ["prompt123", "prompt456"] + assert [c.kwargs["params"] for c in mock_session.get.call_args_list] == [ + {"limit": 2}, + {"after": "cursor-1", "limit": 1}, + ] + + +def test_get_wraps_the_record(mock_session): + api = Prompt._bind(mock_session) + prompt = api(id="prompt123") + assert isinstance(prompt, Prompt) + assert prompt.id == "prompt123" + + +def test_prompt_wrapper_methods_route_to_its_id(mock_session, sample_record): + payload = _zip_of([b">c1\nACDE\n", b">c1\nMKVL\n"]) + mock_session.get.return_value.content = payload + prompt = Prompt(mock_session, PromptSummary.model_validate(sample_record)) + + assert list(prompt) == [["ACDE"], ["MKVL"]] + assert mock_session.get.call_args[0][0] == "v1/data/prompts/prompt123/download" + + prompt.update(description="d") + assert mock_session.patch.call_args.kwargs["json"] == {"description": "d"} + + prompt.delete() + assert mock_session.delete.call_args[0][0] == "v1/data/prompts/prompt123" + + +@pytest.mark.parametrize("status", [404, 425]) +def test_prompts_get_raises_a_404_for_a_404_or_425(mock_session, status): + mock_session.get.side_effect = _http_error(status, {}) + with pytest.raises(HTTPError) as raised: + prompts_get(mock_session, "prompt123") + assert raised.value.status_code == 404 + assert mock_session.get.call_count == 1 + + +@pytest.fixture +def pending_summary(sample_summary) -> dict: + return {**sample_summary, "status": "RUNNING", "job_id": "job1"} + + +def test_pending_summary_parses_with_its_job_status(mock_session, pending_summary): + summary = PromptSummary.model_validate(pending_summary) + prompt = Prompt(mock_session, summary) + assert summary.status == JobStatus.RUNNING + assert prompt.status == JobStatus.RUNNING + assert prompt.job_id == "job1" + + +def test_summary_without_status_reads_success_and_no_job(mock_session, sample_summary): + prompt = Prompt(mock_session, PromptSummary.model_validate(sample_summary)) + assert prompt.status == JobStatus.SUCCESS + assert prompt.job_id is None + + +@pytest.mark.parametrize("status", ["FAILURE", "CANCELED"]) +def test_summary_parses_terminal_job_statuses(sample_summary, status): + summary = PromptSummary.model_validate({**sample_summary, "status": status}) + assert summary.status == JobStatus(status) + + +def test_prompts_list_returns_pending_and_ready_rows( + mock_session, sample_summary, pending_summary +): + mock_session.get.return_value.json.return_value = { + "items": [pending_summary, {**sample_summary, "id": "prompt456"}], + "next": None, + } + prompts = Prompt._bind(mock_session).list() + assert [p.status for p in prompts] == [JobStatus.RUNNING, JobStatus.SUCCESS] + assert [p.job_id for p in prompts] == ["job1", None] + + +def test_prompts_get_returns_a_pending_record(mock_session, pending_summary): + mock_session.get.return_value.json.return_value = { + **pending_summary, + "value": None, + } + record = prompts_get(mock_session, "prompt123") + assert record.status == JobStatus.RUNNING + assert record.job_id == "job1" + assert record.value is None + + +def test_prompts_download_raises_a_409_for_a_prompt_that_is_not_ready(mock_session): + mock_session.get.side_effect = _http_error(409, {}) + with pytest.raises(HTTPError) as raised: + prompts_download(mock_session, "prompt123") + assert raised.value.status_code == 409 + + +@pytest.mark.parametrize("contents", [">q\nAC\n", b">q\nAC\n"], ids=["str", "bytes"]) +def test_upload_refuses_a_bare_file_before_any_request(mock_session, contents): + api = Prompt._bind(mock_session) + + with pytest.raises(TypeError, match=r"create\(\[contents\]\)"): + api.create(contents) + + assert mock_session.mock_calls == [] + + +@pytest.mark.parametrize("contents", [">q\nAC\n", b">q\nAC\n"], ids=["str", "bytes"]) +def test_upload_sends_one_file_for_a_one_entry_list(mock_session, contents): + Prompt._bind(mock_session).create([contents]) + + _, kwargs = mock_session.post.call_args + assert [file[1] for file in kwargs["files"]] == [("replicate-0.fasta", b">q\nAC\n")] diff --git a/tests/data/test_prompts_replicates.py b/tests/data/test_prompts_replicates.py new file mode 100644 index 0000000..bf956bc --- /dev/null +++ b/tests/data/test_prompts_replicates.py @@ -0,0 +1,36 @@ +"""Tests for parsing the stored-prompt download zip into replicate sequences.""" + +import io +import random +import zipfile + +from openprotein.data.prompts._replicates import parse_replicates + + +def _zip_of(replicates_by_position: dict[int, bytes]) -> bytes: + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w") as archive: + for position, content in replicates_by_position.items(): + archive.writestr(f"replicate-{position}.fasta", content) + return buf.getvalue() + + +def test_parse_replicates_orders_a_shuffled_zip_by_position(): + positions = list(range(11)) + shuffled = positions[:] + random.Random(0).shuffle(shuffled) + payload = _zip_of( + {position: f">c1\nSEQ{position}\n".encode() for position in shuffled} + ) + + replicates = parse_replicates(payload) + + assert [replicate[0] for replicate in replicates] == [ + f"SEQ{position}" for position in positions + ] + + +def test_parse_replicates_keeps_chain_separators_within_one_sequence(): + payload = _zip_of({0: b">c1\nMK:LV\n"}) + + assert parse_replicates(payload) == [["MK:LV"]] diff --git a/tests/data/test_prompts_sample.py b/tests/data/test_prompts_sample.py new file mode 100644 index 0000000..a94778e --- /dev/null +++ b/tests/data/test_prompts_sample.py @@ -0,0 +1,231 @@ +"""Sampling a stored MSA into a prompt, and the prompt it returns.""" + +from typing import Any +from unittest.mock import MagicMock + +import pytest + +from openprotein.align.schemas import MSASamplingMethod +from openprotein.data.msa import MSA, MSAMetadata +from openprotein.data.prompts import Prompt, PromptSummary +from openprotein.errors import HTTPError, MissingParameterError +from openprotein.jobs import JobStatus + +MSA_ID = "e0b1c3d4-0000-4000-8000-000000000001" + +PROMPT_ID = "e0b1c3d4-0000-4000-8000-000000000002" + +JOB: dict[str, Any] = { + "job_id": PROMPT_ID, + "job_type": "/prompt/sample_msa", + "status": "PENDING", + "created_date": "2026-09-05T08:00:00Z", +} + +URL = "v1/data/prompts/sample_msa" + + +def _respond(mock: MagicMock, payload: object, status_code: int = 200) -> None: + mock.return_value.status_code = status_code + mock.return_value.json.return_value = payload + + +def _mock_submission(mock_session, payload: dict[str, Any] = JOB) -> None: + _respond(mock_session.post, payload, status_code=202) + + +def test_sample_msa_posts_one_replicate_and_a_seed_when_options_are_omitted( + mock_session, +): + _mock_submission(mock_session) + + _stored_msa(mock_session).sample_prompt() + + call = mock_session.post.call_args + assert call.args == (URL,) + body = call.kwargs["json"] + assert body["msa_id"] == MSA_ID + assert isinstance(body["seed"], int) + assert body["replicates"] == 1 + assert set(body) == {"msa_id", "seed", "replicates"} + assert "headers" not in call.kwargs + assert "params" not in call.kwargs + + +def test_sample_msa_draws_a_different_seed_each_call(mock_session): + _mock_submission(mock_session) + + msa = _stored_msa(mock_session) + msa.sample_prompt() + first_seed = mock_session.post.call_args.kwargs["json"]["seed"] + msa.sample_prompt() + second_seed = mock_session.post.call_args.kwargs["json"]["seed"] + + assert first_seed != second_seed + + +def test_sample_msa_posts_the_given_options(mock_session): + _mock_submission(mock_session) + + _stored_msa(mock_session).sample_prompt( + replicates=3, + seed=11, + method=MSASamplingMethod.TOP, + homology_level=0.5, + max_similarity=0.9, + min_similarity=0.1, + max_msa_sequences=32, + force_include_first=True, + ) + + call = mock_session.post.call_args + assert call.args == (URL,) + assert call.kwargs["json"] == { + "msa_id": MSA_ID, + "seed": 11, + "replicates": 3, + "method": "TOP", + "homology_level": 0.5, + "max_similarity": 0.9, + "min_similarity": 0.1, + "max_msa_sequences": 32, + "force_include_first": True, + } + + +def test_sample_msa_accepts_a_token_budget_alone(mock_session): + _mock_submission(mock_session) + + _stored_msa(mock_session).sample_prompt(max_msa_tokens=4096) + + body = mock_session.post.call_args.kwargs["json"] + assert body["max_msa_tokens"] == 4096 + assert "max_msa_sequences" not in body + + +@pytest.mark.parametrize("job_type", ["/prompt/sample_msa", "/align/prompt"]) +@pytest.mark.parametrize("status", ["PENDING", "RUNNING", "SUCCESS", "FAILURE"]) +def test_sample_msa_returns_the_prompt_its_job_samples(mock_session, status, job_type): + _mock_submission(mock_session, JOB | {"status": status, "job_type": job_type}) + + prompt = _stored_msa(mock_session).sample_prompt() + + assert isinstance(prompt, Prompt) + assert (prompt.id, prompt.job_id) == (PROMPT_ID, PROMPT_ID) + assert prompt.status.value == status + assert prompt.created_at is not None and prompt.created_at.year == 2026 + mock_session.get.assert_not_called() + + +def _stored_msa(session) -> MSA: + return MSA( + session, + MSAMetadata( + msa_id=MSA_ID, + source_format="a3m", + num_sequences=2, + num_match_columns=5, + has_insertions=False, + created_at="2026-09-05T08:00:00Z", + updated_at="2026-09-05T08:00:00Z", + ), + ) + + +def test_an_msa_samples_itself_into_a_prompt(mock_session): + _mock_submission(mock_session) + + prompt = _stored_msa(mock_session).sample_prompt( + replicates=2, seed=7, max_msa_tokens=4096, force_include_first=True + ) + + assert isinstance(prompt, Prompt) and prompt.id == PROMPT_ID + call = mock_session.post.call_args + assert call.args == (URL,) + assert call.kwargs["json"] == { + "msa_id": MSA_ID, + "seed": 7, + "replicates": 2, + "max_msa_tokens": 4096, + "force_include_first": True, + } + + +def test_an_msa_sampling_takes_one_budget_or_the_other(mock_session): + with pytest.raises(MissingParameterError, match="not both"): + _stored_msa(mock_session).sample_prompt( + max_msa_sequences=32, max_msa_tokens=4096 + ) + mock_session.post.assert_not_called() + + +def _response(status_code: int, content: bytes = b"", payload: dict | None = None): + response = MagicMock() + response.status_code = status_code + response.content = content + response.json.return_value = payload or {} + return response + + +def _route(mock_session, routes: dict[str, MagicMock]) -> None: + """Answer each GET by its path; an unlisted path is a 404.""" + + def get(path, **kwargs): + response = routes.get(path, _response(404, payload={"detail": "not found"})) + if response.status_code >= 400: + raise HTTPError(response) + return response + + mock_session.get.side_effect = get + + +def _sampled(mock_session, status: str = "SUCCESS") -> Prompt: + return Prompt( + mock_session, + PromptSummary(id=PROMPT_ID, status=JobStatus(status), job_id=PROMPT_ID), + ) + + +@pytest.mark.parametrize("job_type", ["/prompt/sample_msa", "/align/prompt"]) +def test_a_sampled_prompt_waits_on_its_job_then_reads_its_row( + mock_session, monkeypatch, job_type +): + monkeypatch.setattr("openprotein.jobs.futures.time.sleep", lambda seconds: None) + stored = {"id": PROMPT_ID, "job_id": PROMPT_ID, "status": "SUCCESS", "name": "s"} + _route( + mock_session, + { + f"v1/jobs/{PROMPT_ID}": _response( + 200, payload=JOB | {"job_type": job_type, "status": "SUCCESS"} + ), + f"v1/data/prompts/{PROMPT_ID}": _response(200, payload=stored), + }, + ) + prompt = _sampled(mock_session, "PENDING") + + assert prompt.wait() is prompt + assert (prompt.status, prompt.name) == (JobStatus.SUCCESS, "s") + assert not any( + call.args[0].startswith("v1/prompt/") + for call in mock_session.get.call_args_list + ) + + +def test_a_sampled_prompt_reads_only_the_data_routes(mock_session): + _route(mock_session, {}) + + with pytest.raises(HTTPError) as excinfo: + list(_sampled(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" + ] + + +def test_a_models_job_still_resolves_to_the_generic_future(): + """Futures without a domain job schema declare no job annotation.""" + from openprotein.jobs.futures import EmbeddingFuture, SVDFitFuture + + for domain in (SVDFitFuture, EmbeddingFuture): + assert domain.__annotations__.get("job") is None diff --git a/tests/data/test_reads.py b/tests/data/test_reads.py new file mode 100644 index 0000000..c0ec122 --- /dev/null +++ b/tests/data/test_reads.py @@ -0,0 +1,64 @@ +"""Reads of stored rows and the jobs that operations submit.""" + +from unittest.mock import MagicMock + +import pytest + +from openprotein.data._reads import read +from openprotein.errors import HTTPError +from openprotein.jobs._api import operation_job + +JOB = { + "job_id": "job-1", + "job_type": "/search/mmseqs2", + "status": "PENDING", + "created_date": "2026-09-05T08:00:00Z", +} + + +def _error(status: int) -> HTTPError: + response = MagicMock() + response.status_code = status + return HTTPError(response) + + +def test_a_live_row_is_returned(): + session = MagicMock() + assert read(session, "v1/data/msa/a", params={"format": "a3m"}) is ( + session.get.return_value + ) + session.get.assert_called_once_with("v1/data/msa/a", params={"format": "a3m"}) + + +@pytest.mark.parametrize("status", [404, 425]) +def test_a_row_that_is_not_live_raises_a_404(status): + session = MagicMock() + original = _error(status) + session.get.side_effect = original + with pytest.raises(HTTPError) as raised: + read(session, "v1/data/msa/a") + assert raised.value.status_code == raised.value.response.status_code == 404 + assert original.response.status_code == status + + +@pytest.mark.parametrize("status", [403, 410, 500]) +def test_other_errors_pass_through(status): + session = MagicMock() + session.get.side_effect = _error(status) + with pytest.raises(HTTPError) as raised: + read(session, "v1/data/msa/a") + assert raised.value.status_code == status + + +def test_a_job_body_is_the_submitted_job(): + session = MagicMock() + assert operation_job(session, JOB, "msa_id") == JOB + session.get.assert_not_called() + + +def test_a_body_naming_only_an_id_reads_the_job(): + session = MagicMock() + session.get.return_value.json.return_value = JOB + job = operation_job(session, {"msa_id": "job-1", "state": "pending"}, "msa_id") + assert job["job_id"] == "job-1" + session.get.assert_called_once_with("v1/jobs/job-1") diff --git a/tests/data/test_resource.py b/tests/data/test_resource.py new file mode 100644 index 0000000..669c2f5 --- /dev/null +++ b/tests/data/test_resource.py @@ -0,0 +1,193 @@ +"""The behaviour every stored-data handle shares.""" + +import pickle +from dataclasses import dataclass +from types import SimpleNamespace +from typing import ClassVar +from unittest.mock import MagicMock + +import pytest + +from openprotein.data._resource import _Resource +from openprotein.errors import JobFailedException, JobOutputsNotReady, TimeoutException +from openprotein.jobs.schemas import JobStatus + + +@dataclass +class _Row: + id: str + status: JobStatus = JobStatus.SUCCESS + job_id: str | None = None + + +class _Thing(_Resource[_Row]): + """A stored thing.""" + + loads: ClassVar[list[_Row]] = [] + + @classmethod + def _load(cls, session, id): + return cls.loads.pop(0) + + @property + def id(self): + return self.metadata.id + + @property + def status(self): + return self.metadata.status + + @property + def job_id(self): + return self.metadata.job_id + + +@pytest.fixture(autouse=True) +def _no_sleep(monkeypatch): + monkeypatch.setattr("openprotein.jobs.futures.time.sleep", lambda seconds: None) + + +def _job(status: str, **extra) -> dict: + return { + "job_id": "j1", + "job_type": "/align/align", + "status": status, + "created_date": "2026-09-05T08:00:00Z", + **extra, + } + + +def _polls(session: MagicMock, *jobs: dict) -> None: + session.get.side_effect = [MagicMock(json=MagicMock(return_value=j)) for j in jobs] + + +def test_a_bound_class_keeps_its_name_and_documentation(): + bound = _Thing._bind(MagicMock()) + assert issubclass(bound, _Thing) + assert (bound.__name__, bound.__qualname__, bound.__doc__) == ( + "_Thing", + _Thing.__qualname__, + "A stored thing.", + ) + + +def test_id_loads_through_the_bound_session(): + session = MagicMock() + _Thing.loads = [_Row("a")] + thing = _Thing._bind(session)(id="a") + assert (thing.id, thing.session) == ("a", session) + assert isinstance(thing, _Thing) + + +def test_id_on_an_unbound_class_names_the_session_accessor(): + with pytest.raises(TypeError, match=r"use session\.data\._Thing"): + _Thing(id="a") + + +def test_a_session_and_metadata_construct_without_a_request(): + session = MagicMock() + thing = _Thing(session, _Row("a")) + assert thing.metadata == _Row("a") + session.get.assert_not_called() + + +@pytest.mark.parametrize("args", [(), (MagicMock(),)]) +def test_construction_needs_an_id_or_a_session_with_metadata(args): + with pytest.raises(TypeError, match="takes id=, or a session and its metadata"): + _Thing(*args) + + +def test_id_with_metadata_is_refused(): + with pytest.raises(TypeError, match="pass id alone"): + _Thing(MagicMock(), _Row("a"), id="a") + + +def test_a_handle_is_truthy(): + assert _Thing(MagicMock(), _Row("a")) + + +def test_refresh_reads_the_metadata_again_and_returns_the_handle(): + thing = _Thing(MagicMock(), _Row("a", JobStatus.PENDING, "j1")) + _Thing.loads = [_Row("a", JobStatus.SUCCESS, "j1")] + assert thing.refresh() is thing + assert thing.status is JobStatus.SUCCESS + + +def test_wait_on_a_ready_row_makes_no_request(): + session = MagicMock() + thing = _Thing(session, _Row("a")) + assert thing.wait() is thing + session.get.assert_not_called() + + +def test_wait_polls_the_job_then_reads_the_metadata(): + session = MagicMock() + _polls(session, _job("RUNNING"), _job("RUNNING"), _job("SUCCESS")) + _Thing.loads = [_Row("a", JobStatus.SUCCESS, "j1")] + thing = _Thing(session, _Row("a", JobStatus.PENDING, "j1")) + assert thing.wait() is thing + assert thing.status is JobStatus.SUCCESS + assert [call.args[0] for call in session.get.call_args_list] == ["v1/jobs/j1"] * 3 + + +def test_wait_raises_the_failure_of_the_job(): + session = MagicMock() + _polls(session, _job("FAILURE", failure_message="no hits")) + _Thing.loads = [_Row("a", JobStatus.FAILURE, "j1")] + thing = _Thing(session, _Row("a", JobStatus.PENDING, "j1")) + with pytest.raises(JobFailedException, match="Job j1 failed: no hits"): + thing.wait() + + +def test_wait_raises_for_a_canceled_job(): + session = MagicMock() + _polls(session, _job("CANCELED")) + _Thing.loads = [_Row("a", JobStatus.CANCELED, "j1")] + thing = _Thing(session, _Row("a", JobStatus.PENDING, "j1")) + with pytest.raises(JobFailedException, match="the job was canceled"): + thing.wait() + + +def test_wait_raises_once_the_timeout_is_exceeded(): + session = MagicMock() + session.timeout = 1 + session.get.return_value.json.return_value = _job("RUNNING") + thing = _Thing(session, _Row("a", JobStatus.PENDING, "j1")) + with pytest.raises(TimeoutException): + thing.wait(timeout=0) + + +def test_content_of_a_row_that_is_not_ready_names_its_status(): + thing = _Thing(MagicMock(), _Row("a", JobStatus.PENDING, "j1")) + _Thing.loads = [_Row("a", JobStatus.RUNNING, "j1")] + with pytest.raises(JobOutputsNotReady, match="_Thing a is RUNNING"): + thing._require_ready() + + +@pytest.mark.parametrize( + ("status", "message"), + [ + (JobStatus.FAILURE, "Job j1 failed"), + (JobStatus.CANCELED, "the job was canceled"), + ], +) +def test_content_of_a_failed_or_canceled_row_raises_the_job_failure(status, message): + thing = _Thing(MagicMock(), _Row("a", status, "j1")) + _Thing.loads = [_Row("a", status, "j1")] + with pytest.raises(JobFailedException, match=message): + thing._require_ready() + + +def test_a_handle_from_a_bound_class_pickles(): + session = SimpleNamespace(name="session") + _Thing.loads = [_Row("a")] + thing = _Thing._bind(session)(id="a") # ty: ignore[invalid-argument-type] + restored = pickle.loads(pickle.dumps(thing)) + assert type(restored) is _Thing + assert restored.metadata == _Row("a") + + +def test_a_pickled_handle_keeps_content_read_earlier(): + thing = _Thing(SimpleNamespace(name="session"), _Row("a")) # ty: ignore[invalid-argument-type] + vars(thing)["cached"] = ["row"] + assert vars(pickle.loads(pickle.dumps(thing)))["cached"] == ["row"] diff --git a/tests/data/test_resource_jobs.py b/tests/data/test_resource_jobs.py new file mode 100644 index 0000000..6fac829 --- /dev/null +++ b/tests/data/test_resource_jobs.py @@ -0,0 +1,268 @@ +"""Stored rows answer the ``Future`` calls, through the job that made them.""" + +from unittest.mock import MagicMock + +import pytest + +from openprotein.data import MSA, Prompt +from openprotein.data.msa import MSAMetadata +from openprotein.data.prompts import PromptSummary +from openprotein.errors import ( + HTTPError, + JobFailedException, + JobOutputsNotReady, + NoJobError, +) +from openprotein.jobs import Future, Job, JobStatus + +PROMPT_ID = "e0b1c3d4-0000-4000-8000-000000000002" + +JOB = { + "job_id": PROMPT_ID, + "job_type": "/prompt/sample_msa", + "status": "SUCCESS", + "created_date": "2026-09-05T08:00:00Z", + "start_date": "2026-09-05T08:00:01Z", + "end_date": "2026-09-05T08:00:09Z", +} + + +def _response(payload: dict) -> MagicMock: + response = MagicMock() + response.status_code = 200 + response.json.return_value = payload + return response + + +def _route(session: MagicMock, routes: dict[str, list[dict]]) -> None: + """Answer each GET by its path, in order; the last answer repeats.""" + + def get(path, **kwargs): + answers = routes[path] + return _response(answers.pop(0) if len(answers) > 1 else answers[0]) + + session.get.side_effect = get + + +def _sampled(session: MagicMock, status: str = "SUCCESS") -> Prompt: + return Prompt( + session, + PromptSummary(id=PROMPT_ID, status=JobStatus(status), job_id=PROMPT_ID), + ) + + +def _uploaded_msa(session: MagicMock) -> MSA: + return MSA( + session, + MSAMetadata( + msa_id="m1", + source_format="a3m", + num_sequences=2, + num_match_columns=5, + has_insertions=False, + created_at="2026-09-05T08:00:00Z", + updated_at="2026-09-05T08:00:00Z", + ), + ) + + +def _missing_row(session: MagicMock, job: dict) -> None: + def get(path, **kwargs): + if path == f"v1/jobs/{PROMPT_ID}": + return _response(job) + raise HTTPError(MagicMock(status_code=404)) + + session.get.side_effect = get + + +def test_a_finished_sampling_whose_prompt_is_gone_is_not_ready(mock_session): + _missing_row(mock_session, JOB) + + prompt = Future.create(mock_session, job=Job.create(JOB)) + + assert isinstance(prompt, Prompt) and prompt.status is JobStatus.SUCCESS + for read in (prompt.get, prompt.wait, lambda: list(prompt)): + with pytest.raises(HTTPError) as caught: + read() + assert caught.value.status_code == 404 + + +@pytest.mark.parametrize( + ("status", "message"), + [("FAILURE", "sampler crashed"), ("CANCELED", "the job was canceled")], +) +def test_an_unsuccessful_sampling_whose_prompt_is_gone_raises_its_failure( + mock_session, status, message +): + job = JOB | {"status": status, "failure_message": "sampler crashed"} + _missing_row(mock_session, job) + + prompt = Future.create(mock_session, job=Job.create(job)) + + for read in (prompt.get, prompt.wait): + with pytest.raises(JobFailedException, match=message): + read() + + +def _job_gone(session: MagicMock, code: int, rows: list[dict]) -> None: + def get(path, **kwargs): + if path == f"v1/jobs/{PROMPT_ID}": + raise HTTPError(MagicMock(status_code=code)) + return _response(rows.pop(0) if len(rows) > 1 else rows[0]) + + session.get.side_effect = get + + +@pytest.mark.parametrize("code", [404, 410]) +def test_a_failed_row_whose_job_is_gone_raises_the_failure(mock_session, code): + failed = {"id": PROMPT_ID, "job_id": PROMPT_ID, "status": "FAILURE"} + _job_gone(mock_session, code, [failed]) + prompt = _sampled(mock_session, "FAILURE") + + for read in (prompt.get, prompt.wait): + with pytest.raises(JobFailedException): + read() + + +@pytest.mark.parametrize("code", [404, 410]) +def test_waiting_on_a_row_whose_job_is_gone_reads_the_row(mock_session, code): + failed = {"id": PROMPT_ID, "job_id": PROMPT_ID, "status": "FAILURE"} + _job_gone(mock_session, code, [failed]) + prompt = _sampled(mock_session, "RUNNING") + + assert prompt.wait_until_done() is True + assert prompt.status is JobStatus.FAILURE + + +def test_a_failed_row_raises_other_job_read_errors(mock_session): + failed = {"id": PROMPT_ID, "job_id": PROMPT_ID, "status": "FAILURE"} + _job_gone(mock_session, 500, [failed]) + + with pytest.raises(HTTPError) as caught: + _sampled(mock_session, "FAILURE").get() + assert caught.value.status_code == 500 + + +def test_a_sampled_prompt_reads_its_job_once(mock_session): + _route(mock_session, {f"v1/jobs/{PROMPT_ID}": [JOB]}) + prompt = _sampled(mock_session) + + assert prompt.job is not None and prompt.job.job_id == PROMPT_ID + assert prompt.job_type == "/prompt/sample_msa" + assert prompt.created_date.year == 2026 + assert prompt.start_date is not None and prompt.end_date is not None + assert mock_session.get.call_count == 1 + + +def test_refresh_reads_the_job_again(mock_session): + stored = {"id": PROMPT_ID, "job_id": PROMPT_ID, "status": "SUCCESS"} + _route( + mock_session, + {f"v1/jobs/{PROMPT_ID}": [JOB], f"v1/data/prompts/{PROMPT_ID}": [stored]}, + ) + prompt = _sampled(mock_session) + assert prompt.job is not None + + prompt.refresh() + assert prompt.job is not None + + paths = [call.args[0] for call in mock_session.get.call_args_list] + assert paths.count(f"v1/jobs/{PROMPT_ID}") == 2 + + +@pytest.mark.parametrize( + "field", ["job_type", "created_date", "start_date", "end_date"] +) +def test_an_upload_has_no_job_fields(mock_session, field): + msa = _uploaded_msa(mock_session) + + assert msa.job is None + with pytest.raises(NoJobError, match="m1 was not made by a job"): + getattr(msa, field) + assert not hasattr(msa, field) + mock_session.get.assert_not_called() + + +def test_an_upload_is_done_and_gets_itself(mock_session): + msa = _uploaded_msa(mock_session) + + assert msa.done() is True + assert msa.wait_until_done() is True + assert msa.get() is msa + assert msa.wait() is msa + mock_session.get.assert_not_called() + + +@pytest.mark.parametrize( + ("status", "done"), + [("PENDING", False), ("RUNNING", False), ("SUCCESS", True), ("FAILURE", True)], +) +def test_done_reads_the_status_it_has(mock_session, status, done): + assert _sampled(mock_session, status).done() is done + mock_session.get.assert_not_called() + + +def test_wait_until_done_polls_the_job_and_reloads(mock_session, monkeypatch): + monkeypatch.setattr("openprotein.jobs.futures.time.sleep", lambda seconds: None) + stored = {"id": PROMPT_ID, "job_id": PROMPT_ID, "status": "SUCCESS"} + _route( + mock_session, + { + f"v1/jobs/{PROMPT_ID}": [JOB | {"status": "RUNNING"}, JOB], + f"v1/data/prompts/{PROMPT_ID}": [stored], + }, + ) + prompt = _sampled(mock_session, "PENDING") + + assert prompt.wait_until_done() is True + assert prompt.status is JobStatus.SUCCESS + assert prompt.job is not None and prompt.job.status is JobStatus.SUCCESS + + +def test_wait_until_done_returns_on_a_failure_and_get_raises_it( + mock_session, monkeypatch +): + monkeypatch.setattr("openprotein.jobs.futures.time.sleep", lambda seconds: None) + failed = JOB | {"status": "FAILURE", "failure_message": "sampler crashed"} + stored = {"id": PROMPT_ID, "job_id": PROMPT_ID, "status": "FAILURE"} + _route( + mock_session, + { + f"v1/jobs/{PROMPT_ID}": [failed], + f"v1/data/prompts/{PROMPT_ID}": [stored], + }, + ) + prompt = _sampled(mock_session, "PENDING") + + assert prompt.wait_until_done() is True + with pytest.raises(JobFailedException, match="sampler crashed"): + prompt.get() + with pytest.raises(JobFailedException, match="sampler crashed"): + prompt.wait() + + +def test_get_returns_the_ready_handle(mock_session): + prompt = _sampled(mock_session) + assert prompt.get() is prompt + mock_session.get.assert_not_called() + + +def test_get_on_a_row_that_is_not_ready_raises(mock_session): + stored = {"id": PROMPT_ID, "job_id": PROMPT_ID, "status": "RUNNING"} + _route(mock_session, {f"v1/data/prompts/{PROMPT_ID}": [stored]}) + + with pytest.raises(JobOutputsNotReady, match="is RUNNING"): + _sampled(mock_session, "RUNNING").get() + + +def test_wait_returns_get(mock_session, monkeypatch): + monkeypatch.setattr("openprotein.jobs.futures.time.sleep", lambda seconds: None) + stored = {"id": PROMPT_ID, "job_id": PROMPT_ID, "status": "SUCCESS"} + _route( + mock_session, + {f"v1/jobs/{PROMPT_ID}": [JOB], f"v1/data/prompts/{PROMPT_ID}": [stored]}, + ) + prompt = _sampled(mock_session, "PENDING") + + assert prompt.wait() is prompt + assert prompt.status is JobStatus.SUCCESS diff --git a/tests/data/test_session_classes.py b/tests/data/test_session_classes.py new file mode 100644 index 0000000..8973e68 --- /dev/null +++ b/tests/data/test_session_classes.py @@ -0,0 +1,75 @@ +"""Every handle a session hands out is an instance of that session's ``session.data`` class.""" + +from unittest.mock import MagicMock + +import pytest + +from openprotein.data import DataAPI +from openprotein.jobs import Future, Job + +MSA_METADATA = { + "msa_id": "m1", + "created_at": "2026-07-20T00:00:00Z", + "updated_at": "2026-07-20T00:00:00Z", +} +SAMPLED = { + "id": "s1", + "job_id": "s1", + "name": "sampled", + "status": "PENDING", + "created_date": "2026-09-05T08:00:00Z", +} + + +@pytest.fixture +def session() -> MagicMock: + session = MagicMock() + session.data = DataAPI(session) + return session + + +def _answer(session: MagicMock, verb: str, payload: dict) -> None: + response = getattr(session, verb).return_value + response.status_code = 200 + response.json.return_value = payload + + +def test_a_sampled_prompt_is_a_session_data_prompt(session): + _answer(session, "get", MSA_METADATA) + msa = session.data.MSA(id="m1") + _answer(session, "post", SAMPLED) + prompt = msa.sample_prompt() + assert type(prompt) is session.data.Prompt + + +def test_a_reloaded_sampling_job_is_a_session_data_prompt(session): + _answer(session, "get", {"id": "s1", "status": "SUCCESS", "job_id": "s1"}) + job = Job.create( + { + "job_id": "s1", + "job_type": "/prompt/sample_msa", + "status": "SUCCESS", + "created_date": "2026-09-05T08:00:00Z", + } + ) + assert type(Future.create(session, job=job)) is session.data.Prompt + + +def test_an_assay_given_by_id_to_a_model_is_a_session_data_assay(session): + from openprotein.models import _inputs + + _answer( + session, + "get", + { + "assay_name": "n", + "assay_description": "d", + "assay_id": "a1", + "original_filename": "f.csv", + "created_date": "2023-01-01T00:00:00", + "num_rows": 1, + "num_entries": 1, + "measurement_names": ["y"], + }, + ) + assert type(_inputs.as_dataset(session, "a1")) is session.data.Assay diff --git a/tests/design/test_design.py b/tests/design/test_design.py index b15f0f3..c8ec1b1 100644 --- a/tests/design/test_design.py +++ b/tests/design/test_design.py @@ -1,4 +1,5 @@ """L2 integration tests for the design domain.""" + from unittest.mock import MagicMock import pytest @@ -6,17 +7,15 @@ from openprotein.design.design import DesignAPI from openprotein.design.future import DesignFuture from openprotein.design.schemas import Criteria, Criterion, ModelCriterion -from openprotein.jobs import JobStatus, JobType +from openprotein.jobs import JobType @pytest.fixture def design_api(mock_session: MagicMock) -> DesignAPI: - """Fixture for a DesignAPI instance.""" return DesignAPI(mock_session) def test_create_design(design_api: DesignAPI, mock_session: MagicMock): - """Test the create_genetic_algorithm_design method.""" # Mock for the POST call that creates the design mock_session.post.return_value.status_code = 200 mock_session.post.return_value.json.return_value = { diff --git a/tests/design/test_design_api.py b/tests/design/test_design_api.py index e1fb3a7..8684789 100644 --- a/tests/design/test_design_api.py +++ b/tests/design/test_design_api.py @@ -1,7 +1,7 @@ """Test the api for the design domain.""" + from unittest.mock import MagicMock -import pytest from openprotein.design import api from openprotein.design.schemas import Criteria, Criterion, ModelCriterion @@ -9,14 +9,12 @@ def test_designs_list(mock_session: MagicMock): - """Test designs_list.""" mock_session.get.return_value.json.return_value = [] api.designs_list(mock_session) mock_session.get.assert_called_once_with("v1/designer/design") def test_designer_create_genetic_algorithm(mock_session: MagicMock): - """Test designer_create_genetic_algorithm.""" mock_session.post.return_value.json.return_value = { "job_id": "job-123", "status": "SUCCESS", diff --git a/tests/design/test_design_future.py b/tests/design/test_design_future.py index 75a940c..4f29725 100644 --- a/tests/design/test_design_future.py +++ b/tests/design/test_design_future.py @@ -12,7 +12,6 @@ @pytest.fixture def mock_design_metadata(): - """Fixture for a valid Design instance.""" return Design( id="design-123", status=JobStatus.SUCCESS, @@ -34,7 +33,6 @@ def mock_design_metadata(): @pytest.fixture def mock_design_job(): - """Fixture for a valid DesignJob instance.""" return DesignJob( job_id="design-123", status=JobStatus.SUCCESS, @@ -44,7 +42,6 @@ def mock_design_job(): def test_design_future_init(mock_session, mock_design_metadata, mock_design_job): - """Test DesignFuture initialization with metadata.""" mock_session.jobs = MagicMock(spec=JobsAPI) mock_session.jobs.get_job.return_value = mock_design_job future = DesignFuture(session=mock_session, metadata=mock_design_metadata) @@ -53,7 +50,6 @@ def test_design_future_init(mock_session, mock_design_metadata, mock_design_job) def test_design_future_stream(mock_session, mock_design_metadata, mock_design_job): - """Test the stream method of DesignFuture.""" mock_session.jobs = MagicMock(spec=JobsAPI) mock_session.jobs.get_job.return_value = mock_design_job future = DesignFuture(session=mock_session, metadata=mock_design_metadata) diff --git a/tests/design/test_design_schemas.py b/tests/design/test_design_schemas.py index e7e9696..a579887 100644 --- a/tests/design/test_design_schemas.py +++ b/tests/design/test_design_schemas.py @@ -1,9 +1,6 @@ """Test the schemas for the design domain.""" -from unittest.mock import MagicMock - import pytest -from pydantic import ValidationError from openprotein.design.schemas import ( Criteria, @@ -16,7 +13,6 @@ def test_model_criterion_operators(): - """Test the overloaded operators for ModelCriterion.""" mc = ModelCriterion(model_id="m1", measurement_name="p1") # Test weighting @@ -40,7 +36,6 @@ def test_model_criterion_operators(): def test_criterion_and_operator(): - """Test the AND (&) operator for combining criteria.""" mc1 = ModelCriterion(model_id="m1", measurement_name="p1") > 1 mc2 = ModelCriterion(model_id="m2", measurement_name="p2") < 2 @@ -50,7 +45,6 @@ def test_criterion_and_operator(): def test_criterion_and_rejects_mixed_types(): - """Test that AND (&) rejects mixing model and n_mutations criteria.""" mc = ModelCriterion(model_id="m1", measurement_name="p1") > 1 nmc = n_mutations() @@ -59,7 +53,6 @@ def test_criterion_and_rejects_mixed_types(): def test_criteria_or_operator(): - """Test the OR (|) operator for combining criteria.""" c1 = ModelCriterion(model_id="m1", measurement_name="p1") > 1 c2 = ModelCriterion(model_id="m2", measurement_name="p2") < 2 c3 = NMutationCriterion() @@ -71,7 +64,6 @@ def test_criteria_or_operator(): def test_design_constraint(): - """Test the DesignConstraint class.""" sequence = "ACGT" dc = DesignConstraint(sequence) @@ -100,3 +92,27 @@ def test_design_constraint(): 3: sorted(["G", "I"]), 4: ["T"], } + + +def test_design_constraint_multichain_omits_chain_breaks(): + """Chain-break columns are absent and ':' is never an allowed token.""" + dc = DesignConstraint("AC:GT") + assert dc.as_dict() == {1: ["A"], 2: ["C"], 4: ["G"], 5: ["T"]} + + dc.allow(positions=[1, 4]) + dc.allow(amino_acids="V") + result = {k: sorted(v) for k, v in dc.as_dict().items()} + assert result == { + 1: sorted("ACGTV"), + 2: ["C", "V"], + 4: sorted("ACGTV"), + 5: ["T", "V"], + } + + +def test_design_constraint_multichain_rejects_chain_break(): + dc = DesignConstraint("AC:GT") + with pytest.raises(ValueError): + dc.allow(amino_acids="V", positions=3) + with pytest.raises(ValueError): + dc.allow(amino_acids=":", positions=1) diff --git a/tests/e2e/README.md b/tests/e2e/README.md index 2189ee0..3f0b27c 100644 --- a/tests/e2e/README.md +++ b/tests/e2e/README.md @@ -6,31 +6,33 @@ This directory contains end-to-end tests for the OpenProtein Python SDK. ### Prerequisites -1. Install dependencies including pytest-xdist for parallel execution: +1. Install the package with the `dev` dependency group, which includes pytest-xdist: ```bash -pip install -e ".[dev]" -# or with pixi -pixi install +uv sync ``` +Prefix the commands below with `uv run`, or activate `.venv`. -2. Set environment variables for authentication: +2. Set credentials as environment variables: ```bash export OPENPROTEIN_USERNAME="your_username" export OPENPROTEIN_PASSWORD="your_password" ``` +or as `username` and `password` in `~/.openprotein/config.toml`. Environment variables take precedence. -### Test Data +3. Choose the backend with `OPENPROTEIN_API_BACKEND`, or `backend` in the config file. With neither set, tests run against `https://api.openprotein.ai/api/`. Tests submit real jobs to that backend. -The test suite uses three dataset sizes: +### Test Data -1. **Small** (~41 sequences): `tests/data/AMIE_PSEAE.csv` (included) -2. **Medium** (~1000 sequences): `tests/data/PLACEHOLDER_MEDIUM_1000.csv` (you need to provide) -3. **Large** (~10000 sequences): `tests/data/PLACEHOLDER_LARGE_10000.csv` (you need to provide) +Assay tests use three dataset sizes, all in `tests/data`: -Tests will skip if medium/large datasets are not available. +1. **Small** (~15 sequences): `AMIE_PSEAE_Whitehead.wide.15.csv` +2. **Medium** (~1000 sequences): `AMIE_PSEAE_Whitehead.wide.1000.csv` +3. **Large** (~6800 sequences): `AMIE_PSEAE_Whitehead.wide.csv` ## Running Tests +`-m e2e` is required: the default pytest options deselect e2e tests. + ### Run all E2E tests ```bash pytest tests/e2e -m e2e @@ -122,9 +124,9 @@ Defined in `conftest.py`: - `session`: Session-scoped OpenProtein connection - `protein_complex_with_msa`: Pre-computed MSA for fold tests -- `assay_small`: Small assay dataset (~41 sequences) +- `assay_small`: Small assay dataset (~15 sequences) - `assay_medium`: Medium assay dataset (~1000 sequences) -- `assay_large`: Large assay dataset (~10000 sequences) +- `assay_large`: Large assay dataset (~6800 sequences) - `test_sequences_varied`: Sequences of varying lengths - `test_sequences_short`: Short sequences for quick tests @@ -135,7 +137,7 @@ The test suite is designed for parallel execution: 1. **Session-scoped fixtures** are shared across all workers 2. **Independent tests** can run concurrently 3. **Parametrized tests** distribute across workers automatically -4. **Backend parallelism**: Multiple models can process jobs concurrently +4. **Server parallelism**: Multiple models can process jobs concurrently ### Recommended Parallel Configurations @@ -152,14 +154,7 @@ pytest tests/e2e -m e2e ## Timeouts -Default timeouts are configured per test type: - -- Embeddings: 10 minutes -- Predictor training: 20 minutes -- Align (MSA): 10 minutes -- Fold: 10 minutes - -Adjust in individual test files if needed. +Each test waits for its jobs up to a base timeout times a per-test multiplier (1x to 4x). Set the base in seconds with `OPENPROTEIN_E2E_TIMEOUT_SECONDS` (default 600). ## Adding New Tests @@ -167,10 +162,13 @@ Adjust in individual test files if needed. ```python @pytest.mark.e2e -@pytest.mark.parametrize("model_id,expected_dim", [ - ("esm2_t33_650M_UR50D", 1280), - ("prot-seq", 1024), -]) +@pytest.mark.parametrize( + "model_id,expected_dim", + [ + ("esm2_t33_650M_UR50D", 1280), + ("prot-seq", 1024), + ], +) def test_new_feature(session: OpenProtein, model_id: str, expected_dim: int): model = session.embedding.get_model(model_id) # ... test logic @@ -183,15 +181,14 @@ def test_new_feature(session: OpenProtein, model_id: str, expected_dim: int): def test_with_assay(session: OpenProtein, assay_small: AssayDataset): # assay_small is automatically created and reused predictor = session.embedding.esm2.fit_gp( - assay=assay_small, - properties=[assay_small.measurement_names[0]] + assay=assay_small, properties=[assay_small.measurement_names[0]] ) ``` ## Troubleshooting ### Tests timing out -- Increase timeout values in test files +- Raise `OPENPROTEIN_E2E_TIMEOUT_SECONDS` - Check backend status - Reduce batch sizes for testing @@ -200,13 +197,9 @@ def test_with_assay(session: OpenProtein, assay_small: AssayDataset): - Use `-n 1` to run sequentially for debugging - Check for shared state between tests -### Missing fixtures -- Ensure medium/large CSV files are present -- Tests will skip if fixtures are unavailable - ### Authentication errors -- Verify OPENPROTEIN_USERNAME and OPENPROTEIN_PASSWORD are set -- Check credentials are valid +- Check the credentials in the environment or `~/.openprotein/config.toml` +- Check that `OPENPROTEIN_API_BACKEND` points at the backend those credentials belong to ## Future Improvements diff --git a/tests/e2e/config.py b/tests/e2e/config.py index b7fc31f..166118f 100644 --- a/tests/e2e/config.py +++ b/tests/e2e/config.py @@ -12,4 +12,3 @@ def scaled_timeout(multiplier: float = 1.0) -> int: if multiplier <= 0: raise ValueError(f"multiplier must be > 0, got {multiplier}") return max(1, int(BASE_TIMEOUT * multiplier)) - diff --git a/tests/e2e/conftest.py b/tests/e2e/conftest.py index 5de82c0..d82baa7 100644 --- a/tests/e2e/conftest.py +++ b/tests/e2e/conftest.py @@ -1,6 +1,5 @@ import os import pickle -from pathlib import Path from typing import Any, Callable, List, Tuple import pandas as pd @@ -31,6 +30,9 @@ # Shared sequence constants for E2E tests BASE_SEQUENCE = "MQYKLILNGKTLKGETTTEAVDAATAEKVFKQYANDNGVDGEWTYDDATKTFTVTE" +UBIQUITIN_SEQUENCE = ( + "MQIFVKTLTGKTITLEVEPSDTIENVKAKIQDKEGIPPDQQRLIFAGKQLEDGRTLSDYNIQKESTLHLVLRLRGG" +) TEST_ANTIBODY_SEQUENCE = ANTIBODY_HEAVY_SEQUENCE MSA_SEED_SEQUENCE_LENGTH = 1000 @@ -38,8 +40,7 @@ @pytest.fixture(scope="session") def session() -> OpenProtein: """ - Establishes a session for the entire E2E test run using environment variables. - Scope is 'session' to ensure connection is established only once. + Session-scoped so the connection is established once for the whole E2E run. """ try: return connect() @@ -49,13 +50,11 @@ def session() -> OpenProtein: @pytest.fixture(scope="session") def base_sequence() -> str: - """Shared base sequence for mutation-based alignment/folding tests.""" return BASE_SEQUENCE @pytest.fixture(scope="session") def test_antibody_sequence() -> str: - """Shared antibody sequence for AbNumber alignment tests.""" return TEST_ANTIBODY_SEQUENCE @@ -106,7 +105,6 @@ def _protein_complex_with_msa( """ sequences = [random_sequence_real(56) for _ in range(2)] msa_future = session.align.create_msa(seed=":".join(sequences).encode()) - # msa_future.wait_until_done(timeout=E2E_TIMEOUT) chains = {} id_gen = id_generator() @@ -123,8 +121,7 @@ def _protein_complex_with_msa( @pytest.fixture(scope="session") def protein_complex_with_msa(session, tmp_path_factory, worker_id): """ - Creates a set of protein sequences and a corresponding MSA. - This is session-scoped to avoid recreating the MSA for every test. + Session-scoped, and file-locked across xdist workers, so the MSA is created once. """ if worker_id == "master": # Not running with xdist @@ -153,13 +150,12 @@ def protein_complex_with_msa(session, tmp_path_factory, worker_id): @pytest.fixture(scope="session") def assay_small(session: OpenProtein) -> AssayDataset: """ - Upload small assay dataset (~41 sequences) for training tests. - Session-scoped to reuse across tests. + Upload the small assay dataset (~41 sequences) for training tests. """ filepath = os.path.join(TEST_ASSAY_DATA_DIR, TEST_ASSAY_SMALL_FILE) df = pd.read_csv(filepath) assay_name = f"E2E_Small_{random_string(8)}" - return session.data.create( + return session.data.Assay.create( table=df, name=assay_name, description="Small test assay for E2E tests" ) @@ -167,15 +163,14 @@ def assay_small(session: OpenProtein) -> AssayDataset: @pytest.fixture(scope="session") def assay_medium(session: OpenProtein) -> AssayDataset: """ - Upload medium assay dataset (~1000 sequences) for training tests. - Session-scoped to reuse across tests. + Upload the medium assay dataset (~1000 sequences) for training tests. """ filepath = os.path.join(TEST_ASSAY_DATA_DIR, TEST_ASSAY_MEDIUM_FILE) if not os.path.exists(filepath): pytest.skip(f"Medium assay dataset not found: {filepath}") df = pd.read_csv(filepath) assay_name = f"E2E_Medium_{random_string(8)}" - return session.data.create( + return session.data.Assay.create( table=df, name=assay_name, description="Medium test assay for E2E tests" ) @@ -183,15 +178,14 @@ def assay_medium(session: OpenProtein) -> AssayDataset: @pytest.fixture(scope="session") def assay_large(session: OpenProtein) -> AssayDataset: """ - Upload large assay dataset (~10000 sequences) for training tests. - Session-scoped to reuse across tests. + Upload the large assay dataset (~10000 sequences) for training tests. """ filepath = os.path.join(TEST_ASSAY_DATA_DIR, TEST_ASSAY_LARGE_FILE) if not os.path.exists(filepath): pytest.skip(f"Large assay dataset not found: {filepath}") df = pd.read_csv(filepath) assay_name = f"E2E_Large_{random_string(8)}" - return session.data.create( + return session.data.Assay.create( table=df, name=assay_name, description="Large test assay for E2E tests" ) @@ -199,8 +193,7 @@ def assay_large(session: OpenProtein) -> AssayDataset: @pytest.fixture(scope="session") def test_sequences_varied() -> List[bytes]: """ - Generate a variety of test sequences with different characteristics. - Returns sequences as bytes for API compatibility. + Sequences of varied length, as bytes for API compatibility. """ seqs = [random_sequence_fake(64).encode() for _ in range(150)] # remove two residues at every other sequence @@ -211,7 +204,6 @@ def test_sequences_varied() -> List[bytes]: @pytest.fixture(scope="session") def test_sequences_short() -> List[bytes]: - """Short sequences for quick tests.""" seqs = [random_sequence_fake(64).encode() for _ in range(10)] return seqs @@ -219,8 +211,7 @@ def test_sequences_short() -> List[bytes]: @pytest.fixture(scope="session") def test_sequences_same_length() -> List[bytes]: """ - Sequences of the same length for SVD/UMAP tests. - SVD and UMAP require same-length sequences when not using reduction. + SVD and UMAP require same-length sequences when not using a reduction. """ # All sequences are 64 residues long return [random_sequence_fake(64).encode() for _ in range(150)] diff --git a/tests/e2e/correctness/README.md b/tests/e2e/correctness/README.md index 8dfc137..c4304a9 100644 --- a/tests/e2e/correctness/README.md +++ b/tests/e2e/correctness/README.md @@ -4,61 +4,60 @@ These tests assert that foundational-inference outputs are *correct*, not merely well-formed. They complement the smoke suite in `tests/e2e/`. ## Layers -- **Invariants** (no prod): determinism, batch-invariance, reduction math, attention +- **Invariants**: determinism, batch-invariance, reduction math, attention trimming/normalization. -- **Biological ground-truth** (no prod): native-residue recovery, zero-shot +- **Biological ground-truth**: native-residue recovery, zero-shot variant-effect correlation vs AMIE DMS, sequence recovery on a native backbone. -- **Prod-baseline regression** (marked `differential`): outputs match prod (old - workers) within a tolerance calibrated from prod run-to-run jitter. +- **Baseline regression** (marked `differential`): outputs match a committed + baseline within a tolerance calibrated from run-to-run jitter. ## Markers - `correctness` — all tests here (also carry `e2e`). -- `differential` — the subset that compares against a committed prod baseline. +- `differential` — the subset that compares against a committed baseline. -## Cache strategy (important) +## Cache strategy -The backend caches inference **per-environment**, keyed by sequence (and for PoET by -`prompt_id`/`query_id`). Fixed sequences ⇒ cache hits, which makes *same-input* checks -(determinism, batch-invariance) vacuous unless the call genuinely recomputes. +Inference is cached by sequence (and for PoET by `prompt_id`/`query_id`). Fixed +sequences hit the cache, which makes *same-input* checks (determinism, +batch-invariance) vacuous unless the call genuinely recomputes. - **PoET / PoET-2** are the workhorse for genuine-every-run checks: each probe mints a - **fresh prompt/query from fixed content** (`support.fresh_prompt`/`fresh_query`) → - cache miss → real recompute, still reproducible against a baseline. Batch-invariance - uses *two different* fresh prompts so neither call is cache-served. -- **esm2 / esmc + attention** have no bust lever. They keep only cache-robust checks - (reduction math, attn trim/normalization, semantic similarity) + ground-truth. Their - fixed-sequence baselines are genuine **only on the first run after a deploy / cache - clear** (cold-cache caveat, noted in each such test). -- **Predictors** retrain genuinely every run (fresh assay → fresh `embeddings_id`). + fresh prompt/query from fixed content (`support.fresh_prompt`/`fresh_query`), which + forces a recompute and stays reproducible against a baseline. Batch-invariance + uses two different fresh prompts so neither call is cache-served. +- **esm2 / esmc + attention** can't be forced to recompute. They keep only + cache-robust checks (reduction math, attn trim/normalization, semantic similarity) + plus ground-truth. Their fixed-sequence baselines are genuine only on a cold cache. +- **Predictors** retrain every run (fresh assay, fresh `embeddings_id`). Tolerance: `--baseline-repeats` jitter is ~zero for cached outputs, so the floors (`RTOL_FLOOR`/`ATOL_FLOOR` in `baselines.py`) govern. Tune them from the `max abs/rel -dev` reported by the first staging assert run (the real prod-vs-staging drift). +dev` reported by an assert run. ## Running -Invariant + ground-truth only (no baseline needed), against staging: +Invariant + ground-truth only (no baseline needed): ```bash pytest tests/e2e/correctness -m "correctness and not differential" ``` -Full correctness suite against staging (differential tests skip if no baseline): +Full correctness suite (differential tests skip if no baseline): ```bash pytest tests/e2e/correctness -m correctness ``` -### Refreshing baselines (two-phase) -1. Point `~/.openprotein/config.toml` at **prod** (old workers). +### Baselines: capture, then compare +1. Point `~/.openprotein/config.toml` at the API endpoint to capture from. 2. Capture, sampling jitter for tolerance calibration (run single-process): ```bash pytest tests/e2e/correctness -m differential --update-baselines --baseline-repeats=3 -p no:xdist ``` This (re)writes `tests/e2e/correctness/baselines/.json` and `.arrays.npz`. -3. Review the JSON diffs, point config at **staging**, and run: +3. Review the JSON diffs, then compare: ```bash pytest tests/e2e/correctness -m correctness ``` -4. Commit refreshed baselines with a message noting the prod backend + date. +4. Commit the refreshed baselines. Baselines are keyed by `(model_id, model_version, input_id, output_type)` and are -intentionally produced from **fixed** well-known sequences (cache hits are fine). +produced from **fixed** well-known sequences (cache hits are fine). diff --git a/tests/e2e/correctness/__init__.py b/tests/e2e/correctness/__init__.py index d8bf770..2414623 100644 --- a/tests/e2e/correctness/__init__.py +++ b/tests/e2e/correctness/__init__.py @@ -1 +1 @@ -"""Correctness E2E tests: invariants, biological ground-truth, and calibrated prod-baseline regression.""" +"""Correctness E2E tests: invariants, biological ground-truth, and calibrated baseline regression.""" diff --git a/tests/e2e/correctness/baselines.py b/tests/e2e/correctness/baselines.py index 8e0b653..5aaa3e9 100644 --- a/tests/e2e/correctness/baselines.py +++ b/tests/e2e/correctness/baselines.py @@ -46,8 +46,8 @@ class BaselineRecord: mismatch_fraction: float = 0.0 array: np.ndarray | None = None # numpy dtype name of the array as produced over the wire (e.g. "float16"), - # captured before the float64 coercion used for value comparison. None for - # baselines recorded before dtype tracking was added (dtype assert skipped). + # captured before the float64 coercion used for value comparison. None means + # the baseline carries no dtype and the dtype assert is skipped. dtype: str | None = None provenance: dict | None = None @@ -102,7 +102,7 @@ def save_array( "provenance": provenance, } # The wire dtype (e.g. "float16") is recorded separately from the float64 - # value store so re-runs can assert dtype parity against prod. + # value store so re-runs can assert dtype parity. if dtype is not None: entry["dtype"] = dtype data[_key_str(key)] = entry @@ -111,7 +111,9 @@ def save_array( arrays[_key_str(key)] = array self._write_npz(key, arrays) - def save_scalar(self, key: Key, value: float, *, atol: float, rtol: float, provenance: dict) -> None: + def save_scalar( + self, key: Key, value: float, *, atol: float, rtol: float, provenance: dict + ) -> None: data = self._read_json(key) data[_key_str(key)] = { "kind": "scalar", @@ -122,7 +124,9 @@ def save_scalar(self, key: Key, value: float, *, atol: float, rtol: float, prove } self._write_json(key, data) - def save_tokens(self, key: Key, tokens, *, mismatch_fraction: float, provenance: dict) -> None: + def save_tokens( + self, key: Key, tokens, *, mismatch_fraction: float, provenance: dict + ) -> None: data = self._read_json(key) data[_key_str(key)] = { "kind": "tokens", @@ -169,7 +173,9 @@ def load(self, key: Key) -> BaselineRecord | None: class Comparator: """Runs a value-producing thunk in capture or assert mode against a BaselineStore.""" - def __init__(self, *, store: BaselineStore, mode: str, repeats: int, provenance: dict): + def __init__( + self, *, store: BaselineStore, mode: str, repeats: int, provenance: dict + ): if mode not in ("capture", "assert"): raise ValueError(f"mode must be 'capture' or 'assert', got {mode!r}") self.store = store @@ -177,10 +183,12 @@ def __init__(self, *, store: BaselineStore, mode: str, repeats: int, provenance: self.repeats = repeats self.provenance = provenance - def check_array(self, key: Key, produce, *, atol: float | None = None, rtol: float | None = None) -> None: + def check_array( + self, key: Key, produce, *, atol: float | None = None, rtol: float | None = None + ) -> None: """Capture or assert an array. In assert mode, `atol`/`rtol` override the baseline's stored (jitter-derived) tolerance -- use this to absorb accepted - cross-environment jitter on a genuinely-recomputed output (e.g. PoET).""" + numerical jitter on a genuinely-recomputed output (e.g. PoET).""" if self.mode == "capture": # Capture the wire dtype before coercing to float64 for averaging. # All repeats hit the same endpoint, so they share a dtype; record @@ -203,11 +211,9 @@ def check_array(self, key: Key, produce, *, atol: float | None = None, rtol: flo return rec = self.store.load(key) if rec is None: - pytest.skip(f"no baseline for {key}; run --update-baselines against prod") + pytest.skip(f"no baseline for {key}; run --update-baselines") raw = np.asarray(produce()) - # Assert wire dtype parity before the value comparison. Skipped when the - # baseline predates dtype tracking (rec.dtype is None) so existing - # baselines keep working until re-captured against prod. + # A baseline with no recorded dtype asserts values only. if rec.dtype is not None and raw.dtype.name != rec.dtype: raise AssertionError( f"dtype mismatch for {_key_str(key)}: " @@ -220,7 +226,9 @@ def check_array(self, key: Key, produce, *, atol: float | None = None, rtol: flo atol=atol if atol is not None else rec.atol, ) - def check_scalar(self, key: Key, produce, *, atol: float | None = None, rtol: float | None = None) -> None: + def check_scalar( + self, key: Key, produce, *, atol: float | None = None, rtol: float | None = None + ) -> None: """Capture or assert a scalar. `atol`/`rtol` override the stored tolerance in assert mode (see `check_array`).""" if self.mode == "capture": @@ -229,11 +237,13 @@ def check_scalar(self, key: Key, produce, *, atol: float | None = None, rtol: fl d_atol, d_rtol = metrics.derive_tolerance( samples, safety=SAFETY, atol_floor=ATOL_FLOOR, rtol_floor=RTOL_FLOOR ) - self.store.save_scalar(key, value, atol=d_atol, rtol=d_rtol, provenance=self.provenance) + self.store.save_scalar( + key, value, atol=d_atol, rtol=d_rtol, provenance=self.provenance + ) return rec = self.store.load(key) if rec is None: - pytest.skip(f"no baseline for {key}; run --update-baselines against prod") + pytest.skip(f"no baseline for {key}; run --update-baselines") actual = float(produce()) metrics.assert_close( np.asarray([actual]), @@ -244,20 +254,31 @@ def check_scalar(self, key: Key, produce, *, atol: float | None = None, rtol: fl def check_tokens(self, key: Key, produce) -> None: if self.mode == "capture": - samples = [np.asarray(produce()).astype(int).ravel() for _ in range(self.repeats)] + samples = [ + np.asarray(produce()).astype(int).ravel() for _ in range(self.repeats) + ] value = samples[0] mismatch = 0.0 for s in samples[1:]: - mismatch = max(mismatch, 1.0 - metrics.argmax_match_fraction_tokens(value, s)) - self.store.save_tokens(key, value.tolist(), mismatch_fraction=mismatch, provenance=self.provenance) + mismatch = max( + mismatch, 1.0 - metrics.argmax_match_fraction_tokens(value, s) + ) + self.store.save_tokens( + key, + value.tolist(), + mismatch_fraction=mismatch, + provenance=self.provenance, + ) return rec = self.store.load(key) if rec is None: - pytest.skip(f"no baseline for {key}; run --update-baselines against prod") + pytest.skip(f"no baseline for {key}; run --update-baselines") actual = np.asarray(produce()).astype(int).ravel() baseline = np.asarray(rec.tokens, dtype=int) if actual.shape != baseline.shape: - raise AssertionError(f"token length mismatch: {actual.shape} vs {baseline.shape}") + raise AssertionError( + f"token length mismatch: {actual.shape} vs {baseline.shape}" + ) mismatch = 1.0 - metrics.argmax_match_fraction_tokens(actual, baseline) allowed = max(rec.mismatch_fraction, 0.0) if mismatch > allowed + 1e-9: diff --git a/tests/e2e/correctness/conftest.py b/tests/e2e/correctness/conftest.py index 8d7fe55..81bea53 100644 --- a/tests/e2e/correctness/conftest.py +++ b/tests/e2e/correctness/conftest.py @@ -16,7 +16,7 @@ def pytest_addoption(parser): "--update-baselines", action="store_true", default=False, - help="Capture mode: probe the configured backend and (re)write baseline fixtures.", + help="Capture mode: probe the configured API and (re)write baseline fixtures.", ) parser.addoption( "--baseline-repeats", diff --git a/tests/e2e/correctness/metrics.py b/tests/e2e/correctness/metrics.py index 768b2f7..fe94c14 100644 --- a/tests/e2e/correctness/metrics.py +++ b/tests/e2e/correctness/metrics.py @@ -85,7 +85,9 @@ def assert_close( actual = np.asarray(actual, dtype=float) baseline = np.asarray(baseline, dtype=float) if actual.shape != baseline.shape: - raise AssertionError(f"shape mismatch: actual {actual.shape} vs baseline {baseline.shape}") + raise AssertionError( + f"shape mismatch: actual {actual.shape} vs baseline {baseline.shape}" + ) if np.allclose(actual, baseline, rtol=rtol, atol=atol, equal_nan=True): return both_finite = np.isfinite(actual) & np.isfinite(baseline) diff --git a/tests/e2e/correctness/support.py b/tests/e2e/correctness/support.py index 6c8c147..56bfbf6 100644 --- a/tests/e2e/correctness/support.py +++ b/tests/e2e/correctness/support.py @@ -1,6 +1,6 @@ """Shared helpers for correctness E2E tests. -Cache strategy: the backend caches inference per-environment, keyed by sequence +Cache strategy: inference is cached, keyed by sequence (and, for PoET, by prompt_id/query_id). Raw-sequence encoders (esm2/esmc) therefore can't be forced to recompute a fixed sequence. PoET/PoET-2 CAN: minting a fresh prompt/query from FIXED content yields a new id -> cache @@ -17,10 +17,10 @@ def require_embedding_model(session: OpenProtein, model_id: str): - """Return the embedding model or skip if the backend doesn't expose it.""" + """Return the embedding model or skip if the API doesn't expose it.""" available = {m.id for m in session.embedding.list_models()} if model_id not in available: - pytest.skip(f"{model_id} not available in this backend") + pytest.skip(f"{model_id} not available") return session.embedding.get_model(model_id) @@ -28,7 +28,7 @@ def fresh_prompt(session: OpenProtein, context, *, timeout: int): """Create a fresh prompt (new prompt_id) from FIXED explicit content. A new prompt_id guarantees a cache miss so the inference genuinely recomputes - on the current workers. Because PoET conditions on prompt *content* (not the + on every call. Because PoET conditions on prompt *content* (not the id), identical content yields a reproducible output comparable to a committed baseline. Always use this (explicit content), never ``sample_prompt`` (which draws different context sequences each call and is therefore non-reproducible). diff --git a/tests/e2e/correctness/test_attn_correctness.py b/tests/e2e/correctness/test_attn_correctness.py index 25bd3c4..7611b4f 100644 --- a/tests/e2e/correctness/test_attn_correctness.py +++ b/tests/e2e/correctness/test_attn_correctness.py @@ -2,8 +2,8 @@ Attention is an encoder-only output (esm2/esmc); PoET raises NotImplementedError. The shape/trim/non-negativity invariants feed a freshly mutated sequence each run -(cache miss -> genuine recompute on the current workers); the per-head summary -prod-baseline keeps a fixed sequence to match the committed baseline and is +(cache miss -> genuine recompute on every call); the per-head summary +baseline keeps a fixed sequence to match the committed baseline and is cache-robust (genuine on a cold cache). """ @@ -22,7 +22,7 @@ def _attn_one(model, seq: bytes) -> np.ndarray: # Callers pass a freshly mutated sequence (cache miss) for a genuine recompute; - # the prod-baseline differential keeps a fixed sequence and is cache-robust. + # the baseline differential keeps a fixed sequence and is cache-robust. ((returned, arr),) = model.attn(sequences=[seq]).wait(timeout=TIMEOUT) assert returned == seq return np.asarray(arr) @@ -35,7 +35,7 @@ def test_attn_shape_and_finite(session: OpenProtein, model_id: str): """Attention is finite and square on its two trailing (length) axes. A freshly mutated sequence each run cache-misses, so the attention genuinely - recomputes on the current workers. + recomputes on every call. """ model = require_embedding_model(session, model_id) a = _attn_one(model, mutate_sequence(well_known.UBIQUITIN).encode()) @@ -48,13 +48,11 @@ def test_attn_shape_and_finite(session: OpenProtein, model_id: str): @pytest.mark.correctness @pytest.mark.parametrize("model_id", ENCODER_MODELS) def test_attn_trimmed_on_length_axes_not_heads(session: OpenProtein, model_id: str): - """Two sequences of different lengths trim the trailing length axes, not the head axis. + """The length mask applies to the two trailing (L, L) axes only. - Directly guards the 4D-trim regression class: the length mask must apply to the - two trailing (L, L) axes; the leading (head) axes must be identical across - sequences of different length. A freshly mutated base each run (short is its - prefix) keeps the two sequences distinct -> distinct cache keys -> genuine - recompute. + The leading (head) axes must be identical across sequences of different length. + A freshly mutated base each run (short is its prefix) keeps the two sequences + distinct -> distinct cache keys -> genuine recompute. """ model = require_embedding_model(session, model_id) base = mutate_sequence(well_known.UBIQUITIN) @@ -89,7 +87,7 @@ def test_attn_weights_nonnegative(session: OpenProtein, model_id: str): normalization invariant that holds robustly across encoder models. A freshly mutated sequence each run cache-misses, so the attention genuinely - recomputes on the current workers. + recomputes on every call. """ model = require_embedding_model(session, model_id) a = _attn_one(model, mutate_sequence(well_known.UBIQUITIN).encode()) @@ -100,12 +98,12 @@ def test_attn_weights_nonnegative(session: OpenProtein, model_id: str): @pytest.mark.correctness @pytest.mark.differential @pytest.mark.parametrize("model_id", ENCODER_MODELS) -def test_attn_summary_matches_prod(session: OpenProtein, model_id: str, baseline): - """Per-head mean attention (a compact summary) matches the prod baseline. +def test_attn_summary_matches_baseline(session: OpenProtein, model_id: str, baseline): + """Per-head mean attention (a compact summary) matches the baseline. Fixed sequence (to match the committed baseline), so this is cache-robust: genuine on a cold cache, and a systematic difference (e.g. a different attention - special-token trim) still surfaces here. Relaxed tolerance absorbs cross-env + special-token trim) still surfaces here. Relaxed tolerance absorbs numerical jitter. """ model = require_embedding_model(session, model_id) diff --git a/tests/e2e/correctness/test_baselines_unit.py b/tests/e2e/correctness/test_baselines_unit.py index 3f91c81..4c78d0e 100644 --- a/tests/e2e/correctness/test_baselines_unit.py +++ b/tests/e2e/correctness/test_baselines_unit.py @@ -10,7 +10,9 @@ def test_store_array_roundtrip(tmp_path): store = bl.BaselineStore(tmp_path) key = ("esm2", None, "ubiquitin", "embed_mean") arr = np.arange(6, dtype=float).reshape(2, 3) - store.save_array(key, arr, atol=1e-3, rtol=1e-4, provenance={"backend": "prod"}) + store.save_array( + key, arr, atol=1e-3, rtol=1e-4, provenance={"backend": "reference"} + ) fresh = bl.BaselineStore(tmp_path) # reload from disk rec = fresh.load(key) @@ -24,7 +26,9 @@ def test_store_array_roundtrip(tmp_path): def test_store_scalar_roundtrip(tmp_path): store = bl.BaselineStore(tmp_path) key = ("poet", None, "amie", "variant_effect_spearman") - store.save_scalar(key, 0.42, atol=0.05, rtol=0.0, provenance={"backend": "prod"}) + store.save_scalar( + key, 0.42, atol=0.05, rtol=0.0, provenance={"backend": "reference"} + ) rec = bl.BaselineStore(tmp_path).load(key) assert rec.kind == "scalar" assert rec.value == pytest.approx(0.42) @@ -57,7 +61,9 @@ def test_two_keys_same_model_coexist(tmp_path): def _make_comparator(tmp_path, mode, repeats=1): store = bl.BaselineStore(tmp_path) - return bl.Comparator(store=store, mode=mode, repeats=repeats, provenance={"backend": "test"}) + return bl.Comparator( + store=store, mode=mode, repeats=repeats, provenance={"backend": "test"} + ) def test_comparator_capture_then_assert_array(tmp_path): @@ -110,9 +116,6 @@ def test_comparator_tokens_exact_match(tmp_path): asr.check_tokens(key, lambda: np.array([3, 1, 4, 1, 9])) # one differs -# --- dtype parity (records + asserts the wire dtype, not just values) -------- - - def test_store_array_records_and_loads_dtype(tmp_path): store = bl.BaselineStore(tmp_path) key = ("poet-2", None, "ubiquitin", "embed") @@ -157,7 +160,9 @@ def test_comparator_assert_passes_on_dtype_match(tmp_path): cap = _make_comparator(tmp_path, "capture", repeats=1) cap.check_array(key, lambda: np.array([1.0, 2.0, 3.0], dtype=np.float16)) asr = _make_comparator(tmp_path, "assert") - asr.check_array(key, lambda: np.array([1.0, 2.0, 3.0], dtype=np.float16)) # no raise + asr.check_array( + key, lambda: np.array([1.0, 2.0, 3.0], dtype=np.float16) + ) # no raise def test_comparator_assert_skips_dtype_when_baseline_legacy(tmp_path): @@ -168,4 +173,6 @@ def test_comparator_assert_skips_dtype_when_baseline_legacy(tmp_path): key, np.array([1.0, 2.0, 3.0]), atol=1e-3, rtol=1e-4, provenance={} ) asr = _make_comparator(tmp_path, "assert") - asr.check_array(key, lambda: np.array([1.0, 2.0, 3.0], dtype=np.float16)) # no raise + asr.check_array( + key, lambda: np.array([1.0, 2.0, 3.0], dtype=np.float16) + ) # no raise diff --git a/tests/e2e/correctness/test_dtype_correctness.py b/tests/e2e/correctness/test_dtype_correctness.py index 0841d63..86637f4 100644 --- a/tests/e2e/correctness/test_dtype_correctness.py +++ b/tests/e2e/correctness/test_dtype_correctness.py @@ -2,13 +2,12 @@ The wire dtype of each output is part of the API contract: clients depend on it (fp16 per-residue embeddings, fp32 reduced embeddings, fp16 logits/attention), and -a backend change that silently flips a dtype — e.g. a reduced embedding stored +an API change that silently flips a dtype — e.g. a reduced embedding stored fp16 instead of fp32 — breaks parity without moving values enough for a closeness check to notice. These tests assert the *exact* numpy dtype each array output comes back as. Values are covered by the ``@differential`` baseline tests. -The expected dtypes were captured from prod (https://api.openprotein.ai/api/) via -``scripts/probe_dtypes.py`` on 2026-06-16 — observed, not guessed: +The expected dtypes are the observed wire dtypes (see ``scripts/probe_dtypes.py``): model embed[residue] embed[MEAN] logits attn esm2 float16 float32 float16 float16 @@ -16,13 +15,13 @@ poet-2 float16 float32 float16 (not exposed) Why MEAN is fp32 (not fp16): a ``MEAN``/``SUM`` request is dispatched through the -``MEAN_SUM`` reduction path on the backend, which computes the reduction in (and +``MEAN_SUM`` reduction path, which computes the reduction in (and returns) float32 — so the reduced embedding is fp32 even though the per-residue embedding is fp16. Not asserted here: ``score`` (a scalar that arrives as float64 over the wire — an -SDK/JSON artifact, not a worker-precision contract); esmc-300m (not available on -the probed backend); PoET attention (not exposed by the SDK). +SDK/JSON artifact, not a precision contract); esmc-300m (not available); +PoET attention (not exposed by the SDK). """ import numpy as np @@ -41,7 +40,7 @@ ENCODER_MODELS = ["esm2_t33_650M_UR50D"] POET_MODELS = ["poet", "poet-2"] -# Observed prod wire dtypes (scripts/probe_dtypes.py, 2026-06-16). +# Observed wire dtypes (scripts/probe_dtypes.py). EXPECTED = { "esm2_t33_650M_UR50D": { "embed_residue": np.float16, @@ -65,12 +64,10 @@ # --------------------------------------------------------------------------- # # Encoders (esm2): embed (per-residue + MEAN), logits, attention. # --------------------------------------------------------------------------- # - - @pytest.mark.e2e @pytest.mark.correctness @pytest.mark.parametrize("model_id", ENCODER_MODELS) -def test_encoder_output_dtypes_match_prod(session: OpenProtein, model_id: str): +def test_encoder_output_dtypes_match_observed(session: OpenProtein, model_id: str): model = require_embedding_model(session, model_id) seq = mutate_sequence(well_known.UBIQUITIN).encode() expected = EXPECTED[model_id] @@ -99,7 +96,7 @@ def test_encoder_output_dtypes_match_prod(session: OpenProtein, model_id: str): @pytest.mark.e2e @pytest.mark.correctness @pytest.mark.parametrize("model_id", POET_MODELS) -def test_poet_output_dtypes_match_prod(session: OpenProtein, model_id: str): +def test_poet_output_dtypes_match_observed(session: OpenProtein, model_id: str): model = require_embedding_model(session, model_id) query = well_known.POET_QUERY.encode() expected = EXPECTED[model_id] diff --git a/tests/e2e/correctness/test_embeddings_correctness.py b/tests/e2e/correctness/test_embeddings_correctness.py index 6e7396c..6d9b196 100644 --- a/tests/e2e/correctness/test_embeddings_correctness.py +++ b/tests/e2e/correctness/test_embeddings_correctness.py @@ -3,11 +3,11 @@ Encoders (esm2/esmc) can't be forced to recompute a fixed sequence (the cache is keyed by sequence, with no prompt_id lever), so the invariant/relational checks feed a freshly mutated sequence each run -> a cache miss -> a genuine recompute. -The encoder prod-baseline differential must use a fixed sequence to match the +The encoder baseline differential must use a fixed sequence to match the committed baseline, so it is cache-robust (genuine on a cold cache). PoET (poet/poet-2) cache-busts via a fresh prompt_id, so it carries the genuine -determinism, batch-invariance, and prod-baseline differential coverage. -Differential tolerances are relaxed to absorb accepted cross-environment jitter. +determinism, batch-invariance, and baseline differential coverage. +Differential tolerances are relaxed to absorb accepted numerical jitter. """ import numpy as np @@ -24,7 +24,7 @@ from tests.utils.sequences import mutate_sequence, random_sequence_fake TIMEOUT = scaled_timeout(1.0) -# PoET ops are heavier/slower than encoder embeds on prod; give them more headroom. +# PoET ops are heavier/slower than encoder embeds; give them more headroom. POET_TIMEOUT = scaled_timeout(3.0) ENCODER_MODELS = ["esm2_t33_650M_UR50D", "esmc-300m"] POET_MODELS = ["poet", "poet-2"] @@ -32,7 +32,7 @@ def _embed_one(model, seq: bytes, reduction): # Callers pass a freshly mutated sequence (cache miss) for a genuine recompute; - # the prod-baseline differential keeps a fixed sequence and is cache-robust. + # the baseline differential keeps a fixed sequence and is cache-robust. ((returned, arr),) = model.embed(sequences=[seq], reduction=reduction).wait( timeout=TIMEOUT ) @@ -60,7 +60,7 @@ def test_mean_reduction_equals_mean_of_residues(session: OpenProtein, model_id: """MEAN reduction equals the mean over the per-residue (reduction=None) embedding. A freshly mutated sequence each run cache-misses, so both the MEAN and the - per-residue embeddings genuinely recompute on the current workers. + per-residue embeddings genuinely recompute on every call. """ model = require_embedding_model(session, model_id) seq = mutate_sequence(well_known.UBIQUITIN).encode() @@ -70,9 +70,7 @@ def test_mean_reduction_equals_mean_of_residues(session: OpenProtein, model_id: assert per_residue.ndim == 2 recomputed = per_residue.mean(axis=0) - # Looser tol: the server may exclude special tokens from the mean. If this - # fails, inspect whether per-residue includes BOS/EOS and adjust the axis-0 - # slice accordingly (documented follow-up, not a silent pass). + # Looser tol: the server may exclude special tokens from the mean. metrics.assert_close(mean_reduced, recomputed, rtol=1e-2, atol=1e-2) @@ -98,29 +96,26 @@ def test_embedding_semantic_similarity(session: OpenProtein, model_id: str): assert metrics.cosine(e_wt, e_mut) > metrics.cosine(e_wt, e_unrel) -# --------------------------------------------------------------------------- # -# Encoders (esm2/esmc): prod-baseline differential. -# +# Encoders (esm2/esmc): baseline differential. # A fixed sequence is required to match the committed baseline, so this is # cache-robust rather than a forced recompute -- genuine on a cold cache, and a -# systematic cross-worker difference still surfaces here. Genuine determinism and +# systematic difference still surfaces here. Genuine determinism and # batch-invariance are carried by PoET below (its fresh prompt_id busts the cache # on fixed content); raw-sequence encoders have no equivalent lever. -# --------------------------------------------------------------------------- # @pytest.mark.e2e @pytest.mark.correctness @pytest.mark.differential @pytest.mark.parametrize("model_id", ENCODER_MODELS) -def test_encoder_embedding_matches_prod_baseline( +def test_encoder_embedding_matches_baseline( session: OpenProtein, model_id: str, baseline ): - """MEAN embedding of ubiquitin matches the captured prod baseline. + """MEAN embedding of ubiquitin matches the captured baseline. - Fixed sequence (to match the committed baseline), so this is cache-robust: the - staging value is genuine on a cold cache, and a systematic cross-worker - difference still surfaces. Tolerance absorbs accepted cross-env jitter. + Fixed sequence (to match the committed baseline), so this is cache-robust: + genuine on a cold cache, and a systematic difference still surfaces. The + tolerance absorbs small numerical jitter. """ model = require_embedding_model(session, model_id) seq = well_known.UBIQUITIN.encode() @@ -190,13 +185,11 @@ def test_poet_embedding_batch_invariance(session: OpenProtein, model_id: str): @pytest.mark.correctness @pytest.mark.differential @pytest.mark.parametrize("model_id", POET_MODELS) -def test_poet_embedding_matches_prod_baseline( - session: OpenProtein, model_id: str, baseline -): - """PoET embedding of the fixed query matches the prod baseline -- genuine every run. +def test_poet_embedding_matches_baseline(session: OpenProtein, model_id: str, baseline): + """PoET embedding of the fixed query matches the baseline -- genuine every run. - Each call mints a fresh prompt_id (cache miss), so both the prod capture and the - staging assert truly recompute on their respective workers. + Each call mints a fresh prompt_id (cache miss), so both the capture and the + assert truly recompute. """ model = require_embedding_model(session, model_id) query = well_known.POET_QUERY.encode() @@ -205,8 +198,8 @@ def produce(): prompt = fresh_prompt(session, well_known.POET_CONTEXT, timeout=POET_TIMEOUT) return _poet_embed(model, query, prompt) - # PoET genuinely recomputes (fresh prompt) on both envs; accept small cross-env - # numerical jitter (prod vs new workers) per the accepted-jitter decision. + # PoET genuinely recomputes (fresh prompt); the tolerance accepts small + # numerical jitter between the capture and the assert. baseline.check_array( (model_id, None, "ubiquitin@poetctx", "embed"), produce, atol=0.05, rtol=0.05 ) diff --git a/tests/e2e/correctness/test_generate_correctness.py b/tests/e2e/correctness/test_generate_correctness.py index 91be26b..d797de1 100644 --- a/tests/e2e/correctness/test_generate_correctness.py +++ b/tests/e2e/correctness/test_generate_correctness.py @@ -3,8 +3,8 @@ * **PoET-2 generate**: fresh prompt_id (cache miss) + fixed seed -> genuine recompute that's still reproducible against a committed baseline. * **ESM-IF1 inverse folding**: native-sequence recovery is a *property of the output* - (holds whether fresh or cached), so it's a robust ground-truth check. Its prod - baseline is genuine only on the first call after a deploy / cache clear. + (holds whether fresh or cached), so it's a robust ground-truth check. Its + baseline is genuine only on the first call (cold cache). """ from pathlib import Path @@ -27,7 +27,7 @@ def _esmif1(session: OpenProtein): - """Return the ESM-IF1 model or skip if the backend lacks it. + """Return the ESM-IF1 model or skip if the API lacks it. `session.models` eagerly constructs every foundation model (fetching metadata), so a missing esm-if1 raises HTTPError 404 on attribute access -- catch and skip. @@ -35,14 +35,14 @@ def _esmif1(session: OpenProtein): try: return session.models.esmif1 except HTTPError: - pytest.skip("esmif1 not available in this backend") + pytest.skip("esmif1 not available") def _load_backbone() -> Protein: if not STRUCTURE.exists(): pytest.skip(f"missing {STRUCTURE}") protein = Protein.from_filepath(path=STRUCTURE, chain_id="A") - return protein[len(SDN_LINKER):] + return protein[len(SDN_LINKER) :] def _native_str(backbone: Protein) -> str: @@ -77,15 +77,12 @@ def test_poet2_generate_deterministic(session: OpenProtein): assert seqs1 == seqs2 -# NOTE: no prod-baseline on generated scores. Generation is seeded sampling whose -# RNG/impl differs across worker versions, so a generate score is not comparable -# prod-vs-staging (it diverged by ~5-50 cross-env). Within-env determinism (above) and -# native-recovery ground-truth (below) are the meaningful generate checks. +# No baseline on generated scores: generation is seeded sampling whose RNG and +# implementation differ across model versions, so a generate score is not +# comparable over time. Determinism (above) and native-recovery ground-truth +# (below) are the meaningful generate checks. - -# --------------------------------------------------------------------------- # # ESM-IF1 inverse folding: property-based ground-truth (+ cold-cache baseline). -# --------------------------------------------------------------------------- # @pytest.mark.e2e @@ -99,35 +96,45 @@ def test_esmif1_recovers_native_at_low_temperature(session: OpenProtein): backbone = _load_backbone() native = _native_str(backbone) - future = model.generate(query=backbone, num_samples=4, temperature=0.1, seed=0) + future = model.generate( + query=backbone, num_samples=4, temperature=0.1, random_seed=0 + ) assert future.wait_until_done(timeout=GENERATE_TIMEOUT) - designs = [r.sequence for r in future.get()] + designs = future.get(output="sequences") recoveries = [ metrics.sequence_recovery(d, native) for d in designs if len(d) == len(native) ] assert recoveries, "no design matched the native length" - assert max(recoveries) >= MIN_ESMIF_RECOVERY, f"best recovery {max(recoveries):.3f} too low" + assert max(recoveries) >= MIN_ESMIF_RECOVERY, ( + f"best recovery {max(recoveries):.3f} too low" + ) @pytest.mark.e2e @pytest.mark.correctness @pytest.mark.differential -def test_esmif1_recovery_matches_prod_baseline(session: OpenProtein, baseline): - """Mean native-recovery on the 8bo9 backbone tracks the prod baseline. +def test_esmif1_recovery_matches_baseline(session: OpenProtein, baseline): + """Mean native-recovery on the 8bo9 backbone tracks the baseline. COLD-CACHE CAVEAT: ESM-IF1 has no prompt lever; genuine only on the first call - after a deploy / cache clear. + after a cache clear. """ model = _esmif1(session) backbone = _load_backbone() native = _native_str(backbone) def produce(): - future = model.generate(query=backbone, num_samples=4, temperature=0.1, seed=0) + future = model.generate( + query=backbone, num_samples=4, temperature=0.1, random_seed=0 + ) assert future.wait_until_done(timeout=GENERATE_TIMEOUT) - designs = [r.sequence for r in future.get()] - recoveries = [metrics.sequence_recovery(d, native) for d in designs if len(d) == len(native)] + designs = future.get(output="sequences") + recoveries = [ + metrics.sequence_recovery(d, native) + for d in designs + if len(d) == len(native) + ] return float(np.mean(recoveries)) baseline.check_scalar(("esmif1", None, "8bo9_A", "native_recovery_mean"), produce) diff --git a/tests/e2e/correctness/test_logits_correctness.py b/tests/e2e/correctness/test_logits_correctness.py index 34eb29c..8112403 100644 --- a/tests/e2e/correctness/test_logits_correctness.py +++ b/tests/e2e/correctness/test_logits_correctness.py @@ -1,10 +1,10 @@ """Correctness tests for logits. Encoders feed a freshly mutated sequence (cache miss -> genuine recompute) for the -shape/finite invariant; the prod-baseline differentials keep a fixed sequence to +shape/finite invariant; the baseline differentials keep a fixed sequence to match the committed baseline and are cache-robust (genuine on a cold cache). PoET cache-busts via a fresh prompt_id. Encoder argmax tokens are compared exactly; raw -logit values use a relaxed tolerance for accepted cross-env jitter. +logit values use a relaxed tolerance for accepted numerical jitter. """ import numpy as np @@ -17,7 +17,7 @@ from tests.utils.sequences import mutate_sequence TIMEOUT = scaled_timeout(1.0) -# PoET logits are heavier/slower than embeddings on prod; give them more headroom. +# PoET logits are heavier/slower than embeddings; give them more headroom. POET_TIMEOUT = scaled_timeout(3.0) ENCODER_MODELS = ["esm2_t33_650M_UR50D", "esmc-300m"] POET_MODELS = ["poet", "poet-2"] @@ -25,7 +25,7 @@ def _logits_one(model, seq: bytes) -> np.ndarray: # Callers pass a freshly mutated sequence (cache miss) for a genuine recompute; - # the prod-baseline differentials keep a fixed sequence and are cache-robust. + # the baseline differentials keep a fixed sequence and are cache-robust. ((returned, arr),) = model.logits(sequences=[seq]).wait(timeout=TIMEOUT) assert returned == seq return np.asarray(arr) @@ -41,8 +41,6 @@ def _poet_logits(model, query: bytes, prompt) -> np.ndarray: # --------------------------------------------------------------------------- # # Encoders: structural checks + cold-cache baselines. # --------------------------------------------------------------------------- # - - @pytest.mark.e2e @pytest.mark.correctness @pytest.mark.parametrize("model_id", ENCODER_MODELS) @@ -50,7 +48,7 @@ def test_logits_shape_and_finite(session: OpenProtein, model_id: str): """Logits are finite and 2-D with one row per position (+ specials). A freshly mutated sequence each run cache-misses, so the logits genuinely - recompute on the current workers. + recompute on every call. """ model = require_embedding_model(session, model_id) seq = mutate_sequence(well_known.UBIQUITIN) @@ -64,13 +62,13 @@ def test_logits_shape_and_finite(session: OpenProtein, model_id: str): @pytest.mark.correctness @pytest.mark.differential @pytest.mark.parametrize("model_id", ENCODER_MODELS) -def test_encoder_logits_argmax_tokens_match_prod( +def test_encoder_logits_argmax_tokens_match_baseline( session: OpenProtein, model_id: str, baseline ): - """Per-position argmax token indices match the prod baseline exactly. + """Per-position argmax token indices match the baseline exactly. Fixed sequence (to match the committed baseline), so this is cache-robust: - genuine on a cold cache, and a systematic cross-worker difference (e.g. a + genuine on a cold cache, and a systematic difference (e.g. a different special-token trim) still surfaces here. """ model = require_embedding_model(session, model_id) @@ -86,10 +84,10 @@ def produce(): @pytest.mark.correctness @pytest.mark.differential @pytest.mark.parametrize("model_id", ENCODER_MODELS) -def test_encoder_logits_values_match_prod( +def test_encoder_logits_values_match_baseline( session: OpenProtein, model_id: str, baseline ): - """Raw logit values match the prod baseline within accepted cross-env jitter.""" + """Raw logit values match the baseline within accepted numerical jitter.""" model = require_embedding_model(session, model_id) seq = well_known.UBIQUITIN.encode() @@ -125,8 +123,8 @@ def test_poet_logits_deterministic(session: OpenProtein, model_id: str): @pytest.mark.correctness @pytest.mark.differential @pytest.mark.parametrize("model_id", POET_MODELS) -def test_poet_logits_match_prod_baseline(session: OpenProtein, model_id: str, baseline): - """PoET logits for the fixed query match the prod baseline -- genuine every run.""" +def test_poet_logits_match_baseline(session: OpenProtein, model_id: str, baseline): + """PoET logits for the fixed query match the baseline -- genuine every run.""" model = require_embedding_model(session, model_id) query = well_known.POET_QUERY.encode() @@ -134,7 +132,7 @@ def produce(): prompt = fresh_prompt(session, well_known.POET_CONTEXT, timeout=POET_TIMEOUT) return _poet_logits(model, query, prompt) - # Genuine recompute (fresh prompt); accept small cross-env jitter on logit values. + # Genuine recompute (fresh prompt); accept small numerical jitter on logit values. baseline.check_array( (model_id, None, "ubiquitin@poetctx", "logits"), produce, atol=0.1, rtol=0.05 ) diff --git a/tests/e2e/correctness/test_metrics_unit.py b/tests/e2e/correctness/test_metrics_unit.py index 36b1212..b92325b 100644 --- a/tests/e2e/correctness/test_metrics_unit.py +++ b/tests/e2e/correctness/test_metrics_unit.py @@ -104,7 +104,9 @@ def test_assert_close_nan_aware(): def test_derive_tolerance_zero_jitter_uses_floors(): samples = [np.array([1.0, 2.0, 3.0]) for _ in range(3)] - atol, rtol = metrics.derive_tolerance(samples, safety=4.0, atol_floor=1e-5, rtol_floor=1e-4) + atol, rtol = metrics.derive_tolerance( + samples, safety=4.0, atol_floor=1e-5, rtol_floor=1e-4 + ) assert atol == pytest.approx(1e-5) assert rtol == pytest.approx(1e-4) @@ -112,6 +114,8 @@ def test_derive_tolerance_zero_jitter_uses_floors(): def test_derive_tolerance_scales_with_jitter(): base = np.array([10.0, 10.0]) samples = [base, base + 0.1, base - 0.1] # max abs dev from mean = 0.1 - atol, rtol = metrics.derive_tolerance(samples, safety=4.0, atol_floor=1e-5, rtol_floor=1e-4) + atol, rtol = metrics.derive_tolerance( + samples, safety=4.0, atol_floor=1e-5, rtol_floor=1e-4 + ) assert atol == pytest.approx(0.4, rel=1e-6) assert rtol == pytest.approx(0.04, rel=1e-6) diff --git a/tests/e2e/correctness/test_predictor_correctness.py b/tests/e2e/correctness/test_predictor_correctness.py index d469b6c..544279f 100644 --- a/tests/e2e/correctness/test_predictor_correctness.py +++ b/tests/e2e/correctness/test_predictor_correctness.py @@ -7,7 +7,7 @@ Ground-truth (L2/L4): the predictor must recover real signal from the AMIE deep mutational scan -- held-out Spearman above a floor. Differential (L3): that Spearman -and the held-out prediction means also track the prod baseline. +and the held-out prediction means also track the baseline. """ from pathlib import Path @@ -45,7 +45,7 @@ def _amie_split() -> tuple[pd.DataFrame, pd.DataFrame]: @pytest.mark.correctness @pytest.mark.differential def test_predictor_recovers_amie_signal(session: OpenProtein, baseline): - """GP trained on AMIE recovers held-out fitness; Spearman + means track prod baseline.""" + """GP trained on AMIE recovers held-out fitness; Spearman + means track baseline.""" if not AMIE_PATH.exists(): pytest.skip("AMIE DMS table not present") train_df, test_df = _amie_split() @@ -55,12 +55,14 @@ def test_predictor_recovers_amie_signal(session: OpenProtein, baseline): model = require_embedding_model(session, MODEL_ID) # Fresh assay -> fresh embeddings_id -> genuinely retrained predictor every run. - assay = session.data.create( + assay = session.data.Assay.create( table=train_df, name=f"AMIE_corr_{random_string(8)}", description="AMIE train split for predictor correctness", ) - predictor = model.fit_gp(assay=assay, properties=[PROPERTY], reduction=ReductionType.MEAN) + predictor = model.fit_gp( + assay=assay, properties=[PROPERTY], reduction=ReductionType.MEAN + ) assert predictor.wait(timeout=PRED_TIMEOUT), "GP training failed" test_seqs = [s.encode() for s in test_df["sequence"].tolist()] @@ -74,12 +76,15 @@ def test_predictor_recovers_amie_signal(session: OpenProtein, baseline): # L4 ground-truth: must recover real signal. assert rho >= MIN_PREDICTOR_SPEARMAN, f"held-out Spearman {rho:.3f} below floor" - # L3 differential: Spearman and the held-out prediction means track prod, with - # generous tolerance -- the GP recompute over fresh embeddings drifts slightly - # vs prod and that's accepted (accepted-jitter decision). + # L3 differential: Spearman and the held-out prediction means track the + # baseline, with a generous tolerance -- the GP recompute over fresh + # embeddings drifts slightly. baseline.check_scalar( (MODEL_ID, None, "amie_split", "heldout_spearman"), lambda: rho, atol=0.05 ) baseline.check_array( - (MODEL_ID, None, "amie_split", "heldout_mu"), lambda: mus[:, 0], atol=0.1, rtol=0.1 + (MODEL_ID, None, "amie_split", "heldout_mu"), + lambda: mus[:, 0], + atol=0.1, + rtol=0.1, ) diff --git a/tests/e2e/correctness/test_scoring_correctness.py b/tests/e2e/correctness/test_scoring_correctness.py index 18123be..8af6470 100644 --- a/tests/e2e/correctness/test_scoring_correctness.py +++ b/tests/e2e/correctness/test_scoring_correctness.py @@ -1,7 +1,7 @@ """Correctness tests for sequence scoring / variant effects. PoET-only (poet/poet-2). Every probe mints a fresh prompt_id from FIXED content, -so it genuinely recomputes on the current workers while staying comparable to a +so it genuinely recomputes on every call while staying comparable to a committed baseline. """ @@ -98,12 +98,12 @@ def test_variant_effect_correlates_with_amie( rho = metrics.spearman(np.array(predicted), np.array(measured)) # L2 floor: zero-shot variant effect must clear a minimum quality bar. - assert ( - rho >= MIN_VARIANT_EFFECT_SPEARMAN - ), f"variant-effect Spearman {rho:.3f} too low" + assert rho >= MIN_VARIANT_EFFECT_SPEARMAN, ( + f"variant-effect Spearman {rho:.3f} too low" + ) - # L3: the correlation tracks the captured prod baseline within a generous band - # (small cross-env drift accepted; single_site is conditioned on a fresh prompt). + # L3: the correlation tracks the committed baseline within a generous band + # (small numerical jitter accepted; single_site is conditioned on a fresh prompt). baseline.check_scalar( (model_id, None, "amie", "variant_effect_spearman"), lambda: rho, atol=0.02 ) diff --git a/tests/e2e/correctness/test_token_contract_correctness.py b/tests/e2e/correctness/test_token_contract_correctness.py index fc5dcc1..ea17f66 100644 --- a/tests/e2e/correctness/test_token_contract_correctness.py +++ b/tests/e2e/correctness/test_token_contract_correctness.py @@ -1,16 +1,13 @@ """Per-model special-token (length) contract -- cache-immune. Each embedding-model family adds a fixed number of special tokens to its per-residue -output (ESM/PoET: +2 BOS/EOS; ablang2/ProtT5: +1; prot-seq/rotaprot/ESMC: 0). We +output (ESM/PoET: +2 BOS/EOS; ablang2: +1; prot-seq/rotaprot/ESMC/ProtT5: 0). We assert `output_length - residue_count == expected_delta` using a NOVEL random sequence every run, so the call is a guaranteed cache miss (genuine recompute) and needs no -committed prod baseline. +committed baseline. -This is the robust replacement for fixed-sequence logits-shape differentials: the -backend caches inference per sequence, so a fixed-sequence baseline returns the stale -cached length on a warm cache (which produced false "trim" mismatches for the ESM -family until we switched to novel inputs). The platform is moving to residue-aligned -(delta 0) in a future release; until then each model must keep its prod convention. +A novel input is required: inference is cached per sequence, so a fixed-sequence +baseline reads back the cached length on a warm cache and cannot see a trim change. """ import numpy as np @@ -25,13 +22,13 @@ TIMEOUT = scaled_timeout(1.0) POET_TIMEOUT = scaled_timeout(3.0) -# (model_id, expected special-token delta vs residue count) -- prod convention. +# (model_id, expected special-token delta vs residue count). EXPECTED_DELTA = [ ("esm2_t33_650M_UR50D", 2), ("esm1b_t33_650M_UR50S", 2), ("esm1v_t33_650M_UR90S_1", 2), ("prot-seq", 0), - ("prott5-xl", 1), + ("prott5-xl", 0), ("rotaprot-large-uniref50w", 0), ("esmc-300m", 0), ("poet", 2), @@ -47,20 +44,22 @@ def _output_length(session: OpenProtein, model, model_id: str) -> tuple[int, int heavy = mutate_sequence(well_known.ANTIBODY_HEAVY, mutation_rate=0.05) light = mutate_sequence(well_known.ANTIBODY_LIGHT, mutation_rate=0.05) residues = len(heavy) + len(light) - res = model.embed( - sequences=[f"{heavy}:{light}".encode()], reduction=None - ).wait(timeout=TIMEOUT) + res = model.embed(sequences=[f"{heavy}:{light}".encode()], reduction=None).wait( + timeout=TIMEOUT + ) elif model_id.startswith("poet"): seq = random_sequence_fake(60) residues = len(seq) prompt = fresh_prompt(session, well_known.POET_CONTEXT, timeout=POET_TIMEOUT) - res = model.embed( - sequences=[seq.encode()], reduction=None, prompt=prompt - ).wait(timeout=POET_TIMEOUT) + res = model.embed(sequences=[seq.encode()], reduction=None, prompt=prompt).wait( + timeout=POET_TIMEOUT + ) else: seq = random_sequence_fake(60) residues = len(seq) - res = model.embed(sequences=[seq.encode()], reduction=None).wait(timeout=TIMEOUT) + res = model.embed(sequences=[seq.encode()], reduction=None).wait( + timeout=TIMEOUT + ) arr = np.asarray(res[0][1]) length = arr.shape[-2] if arr.ndim >= 2 else arr.shape[0] return length, residues @@ -72,7 +71,7 @@ def _output_length(session: OpenProtein, model, model_id: str) -> tuple[int, int def test_special_token_length_contract( session: OpenProtein, model_id: str, expected_delta: int ): - """output_length - residue_count must equal the model's prod special-token delta.""" + """output_length - residue_count must equal the model's special-token delta.""" model = require_embedding_model(session, model_id) length, residues = _output_length(session, model, model_id) delta = length - residues diff --git a/tests/e2e/models/__init__.py b/tests/e2e/models/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/e2e/models/test_estimators_e2e.py b/tests/e2e/models/test_estimators_e2e.py new file mode 100644 index 0000000..459f1c3 --- /dev/null +++ b/tests/e2e/models/test_estimators_e2e.py @@ -0,0 +1,64 @@ +"""Estimators on session.models, chained end to end.""" + +from uuid import uuid4 + +import pandas as pd +import pytest + +from openprotein import OpenProtein +from openprotein.jobs import JobStatus, _dispatch +from openprotein.models import ( + GPModel, + RBFKernel, + SVDModel, +) +from tests.e2e.config import scaled_timeout + +TIMEOUT = scaled_timeout(3.0) + + +@pytest.mark.e2e +def test_an_svd_then_a_gp_on_an_embedded_assay(session: OpenProtein, mutated_sequences): + """Embedding an assay, fitting an SVD and training a GP on its projections chains.""" + sequences = mutated_sequences(num_sequences=5, mutation_rate=0.05) + table = pd.DataFrame({"sequence": sequences, "fitness": [0.1, 0.4, 0.2, 0.9, 0.5]}) + dataset = session.data.Assay.create( + table=table, + name=f"e2e-estimators-{uuid4().hex[:8]}", + description="estimators e2e", + ) + + embeddings = session.models.esm2_t6_8M_UR50D.embed(dataset) + projected = session.models.SVD(2).fit_transform(embeddings) + trained = ( + session.models.GP(kernel="rbf") + .fit(projected, property="fitness") + .wait(timeout=TIMEOUT) + ) + fitted_svd = projected.wait(timeout=TIMEOUT) + + assert isinstance(trained, GPModel) + assert isinstance(fitted_svd, SVDModel) + assert trained.spec is not None + assert trained.spec["features"]["type"] == "SVD" + assert trained.spec["features"]["model_id"] == fitted_svd.id + kernel = trained.kernel + assert isinstance(kernel, RBFKernel) + assert kernel.type == "rbf" + assert kernel.lengthscale > 0 + assert kernel.outputscale > 0 + assert trained.mean is not None + noise = trained.noise + assert noise is not None and noise > 0 + + predicted = trained.predict(sequences[:2]) + assert predicted.wait_until_done(timeout=TIMEOUT) + assert predicted.status is JobStatus.SUCCESS + if _dispatch.is_models_job(predicted.job): + assert len(predicted.get()) == 2 + else: + mus, _ = session.jobs.get(predicted.id).wait(timeout=TIMEOUT) + assert len(mus) == 2 + + trained.delete() + fitted_svd.delete() diff --git a/tests/e2e/models/test_models_svd_e2e.py b/tests/e2e/models/test_models_svd_e2e.py new file mode 100644 index 0000000..d655fab --- /dev/null +++ b/tests/e2e/models/test_models_svd_e2e.py @@ -0,0 +1,71 @@ +"""SVDs served as svd/ models.""" + +from typing import Any, cast + +import pytest + +from openprotein import OpenProtein +from openprotein.errors import APIError +from openprotein.jobs import JobStatus, _dispatch +from tests.e2e.config import scaled_timeout + +TIMEOUT = scaled_timeout(3.0) +MODEL_ID = "esm2_t6_8M_UR50D" + + +@pytest.mark.e2e +def test_svd_fits_projects_and_is_managed_as_a_model( + session: OpenProtein, mutated_sequences +): + """A 16-component fit over 8 sequences has rank 8.""" + sequences = mutated_sequences(num_sequences=8, mutation_rate=0.05) + future = session.models.SVD(n_components=16, seed=11).fit( + model=MODEL_ID, sequences=sequences, reduction="MEAN" + ) + if not _dispatch.is_models_job(future.job): + pytest.skip("the fit isn't a models API job") + svd = future.wait(timeout=TIMEOUT) + assert svd.id == f"svd/{future.id}" + assert future.outputs == ["sequences"] + assert svd.n_components == 8 + + card = session.models.get_model(svd.id).metadata + assert card.dimension == 8 + assert [method.path for method in card.methods] == ["batch/embeddings"] + assert svd.id in [listed.id for listed in session.models.SVD.list()] + + projected = svd.embed(sequences[:2]) + values = cast(list[Any], projected.wait(timeout=TIMEOUT)) + assert projected.outputs == ["embeddings"] + assert len(values) == 2 and all(value.shape == (8,) for value in values) + assert projected.status is JobStatus.SUCCESS + + svd.delete() + assert svd.id not in [listed.id for listed in session.models.SVD.list()] + + +@pytest.mark.e2e +def test_an_svd_fit_outside_the_models_api_reads_back_and_projects( + session: OpenProtein, mutated_sequences +): + """The svd reads back once its fit succeeds; projections come from their job.""" + sequences = mutated_sequences(num_sequences=8, mutation_rate=0.05) + future = session.models.SVD(n_components=4).fit( + model=MODEL_ID, sequences=sequences, reduction="MEAN" + ) + if _dispatch.is_models_job(future.job): + pytest.skip("the fit is a models API job") + svd = future.wait(timeout=TIMEOUT) + assert (svd.id, svd.n_components) == (f"svd/{future.id}", 4) + assert svd.id in [listed.id for listed in session.models.SVD.list()] + + projected = svd.embed(sequences[:2]) + projected.wait_until_done(timeout=TIMEOUT) + assert projected.status is JobStatus.SUCCESS + with pytest.raises(APIError, match="session.jobs.get"): + projected.get() + values = session.jobs.get(projected.id).wait(timeout=TIMEOUT) + assert len(values) == 2 + + svd.delete() + assert svd.id not in [listed.id for listed in session.models.SVD.list()] diff --git a/tests/e2e/models/test_structure_ensemble_e2e.py b/tests/e2e/models/test_structure_ensemble_e2e.py new file mode 100644 index 0000000..ce01a24 --- /dev/null +++ b/tests/e2e/models/test_structure_ensemble_e2e.py @@ -0,0 +1,128 @@ +"""Structure ensemble sampling through session.models.""" + +import numpy as np +import pytest + +from openprotein import OpenProtein +from openprotein.align.msa import MSAFuture +from openprotein.jobs.futures import StructurePredictionFuture +from openprotein.models import AlphaFlow, ESMFlow +from openprotein.molecules import Protein, Structure +from tests.e2e.config import scaled_timeout +from tests.e2e.conftest import BASE_SEQUENCE, UBIQUITIN_SEQUENCE + +TIMEOUT = scaled_timeout(3.0) +NUM_SAMPLES = 2 +SEED = 7 +ALPHAFLOW_IDS = ["alphaflow-md-base-v1", "alphaflow-md-distilled-v1"] +ESMFLOW_IDS = ["esmflow-md-base-v1", "esmflow-md-distilled-v1"] + + +@pytest.fixture(scope="module") +def msa(session: OpenProtein) -> MSAFuture: + msa = session.align.create_msa(seed=BASE_SEQUENCE.encode()) + msa.wait_until_done(timeout=TIMEOUT) + return msa + + +@pytest.fixture(scope="module") +def reference_fold(session: OpenProtein) -> StructurePredictionFuture: + future = session.models.esmfold.fold(BASE_SEQUENCE) + future.wait_until_done(timeout=TIMEOUT) + return future + + +@pytest.fixture(scope="module") +def reference(reference_fold: StructurePredictionFuture) -> Protein: + (structure,) = reference_fold.get() + (protein,) = structure[0].get_proteins().values() + return protein + + +def _assert_ensembles( + structures: list[Structure], sequences: list[str], num_samples: int +) -> None: + assert len(structures) == len(sequences) + for structure, sequence in zip(structures, sequences): + assert isinstance(structure, Structure) + assert len(structure) == num_samples + for conformation in structure: + (protein,) = conformation.get_proteins().values() + assert protein.sequence.decode() == sequence + assert not protein.get_structure_mask().all() + + +def _assert_flow_outputs(future: StructurePredictionFuture, sequence: str) -> None: + plddt = np.asarray(future.get_item(0, output="plddt")) + assert plddt.shape == (NUM_SAMPLES, len(sequence)) + assert len(future.get(output="confidence")) == 1 + + +def _sample_flow( + session: OpenProtein, + model_id: str, + msa: MSAFuture, + reference: Protein | None = None, +) -> StructurePredictionFuture: + model = session.models.get_model(model_id) + if isinstance(model, AlphaFlow): + entry = model.Input(BASE_SEQUENCE, msa=msa, reference_structure=reference) + return model.sample([entry], num_samples=NUM_SAMPLES, random_seed=SEED) + assert isinstance(model, ESMFlow) + entry = model.Input(BASE_SEQUENCE, reference_structure=reference) + return model.sample([entry], num_samples=NUM_SAMPLES, random_seed=SEED) + + +@pytest.mark.e2e +def test_bioemu_samples_an_aligned_protein(session: OpenProtein, msa: MSAFuture): + bioemu = session.models.bioemu_v1_1 + future = bioemu.sample( + [bioemu.Input(BASE_SEQUENCE, msa=msa)], + num_samples=NUM_SAMPLES, + filter_samples=False, + random_seed=SEED, + ) + + structures = future.wait(timeout=TIMEOUT) + + _assert_ensembles(structures, [BASE_SEQUENCE], NUM_SAMPLES) + + +@pytest.mark.e2e +def test_bioemu_samples_several_proteins_without_an_msa(session: OpenProtein): + sequences = [BASE_SEQUENCE, UBIQUITIN_SEQUENCE] + bioemu = session.models.bioemu_v1_1 + future = bioemu.sample( + [bioemu.Input(sequence, msa=None) for sequence in sequences], + num_samples=NUM_SAMPLES, + filter_samples=False, + random_seed=SEED, + ) + + structures = future.wait(timeout=TIMEOUT) + + _assert_ensembles(structures, sequences, NUM_SAMPLES) + + +@pytest.mark.e2e +@pytest.mark.parametrize("model_id", ALPHAFLOW_IDS + ESMFLOW_IDS) +def test_flow_samples_a_protein(session: OpenProtein, msa: MSAFuture, model_id: str): + future = _sample_flow(session, model_id, msa) + + structures = future.wait(timeout=TIMEOUT) + + _assert_ensembles(structures, [BASE_SEQUENCE], NUM_SAMPLES) + _assert_flow_outputs(future, BASE_SEQUENCE) + + +@pytest.mark.e2e +@pytest.mark.parametrize("model_id", ALPHAFLOW_IDS + ESMFLOW_IDS) +def test_flow_samples_from_a_reference_structure( + session: OpenProtein, msa: MSAFuture, reference: Protein, model_id: str +): + future = _sample_flow(session, model_id, msa, reference) + + structures = future.wait(timeout=TIMEOUT) + + _assert_ensembles(structures, [BASE_SEQUENCE], NUM_SAMPLES) + _assert_flow_outputs(future, BASE_SEQUENCE) diff --git a/tests/e2e/models/test_structure_prediction_e2e.py b/tests/e2e/models/test_structure_prediction_e2e.py new file mode 100644 index 0000000..2c4a182 --- /dev/null +++ b/tests/e2e/models/test_structure_prediction_e2e.py @@ -0,0 +1,456 @@ +"""Structure prediction through session.models.""" + +from typing import Any + +import numpy as np +import pandas as pd +import pytest + +from openprotein import OpenProtein +from openprotein.align.msa import MSAFuture +from openprotein.errors import HTTPError +from openprotein.jobs.futures import StructurePredictionFuture +from openprotein.models import StructurePredictionModel +from openprotein.molecules import Complex, Ligand, Protein, Structure, Template +from tests.e2e.config import scaled_timeout +from tests.e2e.conftest import BASE_SEQUENCE, UBIQUITIN_SEQUENCE + +TIMEOUT = scaled_timeout(3.0) +NUM_SAMPLES = 2 +SEED = 7 +ATP_ATOMS = 31 +FOLD_IDS = [ + "alphafold2", + "boltz-1", + "boltz-1x", + "boltz-2", + "esmfold", + "esmfold2", + "esmfold2-fast", + "minifold", + "protenix", + "protenix-v2", + "rosettafold-3", +] +MULTICHAIN_IDS = [model_id for model_id in FOLD_IDS if model_id != "minifold"] +SINGLE_SEQUENCE_IDS = ["esmfold", "esmfold2-fast", "minifold"] +PROTEIN_ONLY_IDS = {"alphafold2", "esmfold"} +PER_ATOM_PLDDT_IDS = {"protenix", "protenix-v2"} +TEMPLATE_IDS = ["boltz-2", "protenix", "protenix-v2"] +OUTPUTS = { + "structures", + "plddt", + "pae", + "pde", + "confidence", + "ipae", + "ptm", + "affinity", + "score", + "metrics", +} +POCKET = { + "pocket": {"binder": "L", "contacts": [["A", 15], ["B", 22]], "max_distance": 6.0} +} +CONTACT = {"contact": {"token1": ["A", 10], "token2": ["B", 20], "max_distance": 15.0}} +CONSTRAINTS = { + "boltz-1": {"bond": {"atom1": ["A", 10, "CA"], "atom2": ["B", 20, "CA"]}}, + "boltz-1x": POCKET, + "boltz-2": CONTACT, +} + + +@pytest.fixture(scope="module") +def msa(session: OpenProtein) -> MSAFuture: + msa = session.align.create_msa(seed=BASE_SEQUENCE.encode()) + msa.wait_until_done(timeout=TIMEOUT) + return msa + + +@pytest.fixture(scope="module") +def paired_msa(session: OpenProtein) -> MSAFuture: + msa = session.align.create_msa( + seed=f"{BASE_SEQUENCE}:{UBIQUITIN_SEQUENCE}".encode() + ) + msa.wait_until_done(timeout=TIMEOUT) + return msa + + +@pytest.fixture(scope="module") +def template() -> Protein: + protein = Protein.from_filepath("tests/data/8bo9.cif", chain_id="A", verbose=False) + return protein[len("MHHHHHHSDN") :] + + +def _model(session: OpenProtein, model_id: str) -> StructurePredictionModel: + model = session.models.get_model(model_id) + assert isinstance(model, StructurePredictionModel) + return model + + +def _protein(sequence: str, msa: MSAFuture | None, model_id: str) -> Protein: + protein = Protein(sequence=sequence) + if model_id not in SINGLE_SEQUENCE_IDS: + protein.msa = Protein.single_sequence_mode if msa is None else msa + return protein + + +def _complex(model_id: str, msa: MSAFuture) -> Complex: + return Complex( + { + "A": _protein(BASE_SEQUENCE, msa, model_id), + "B": _protein(UBIQUITIN_SEQUENCE, msa, model_id), + "L": Ligand(ccd="ATP"), + } + ) + + +def _sampling(model: StructurePredictionModel) -> tuple[dict, int]: + properties = model._params_schema("batch/structures")["properties"] + params = {"random_seed": SEED} if "random_seed" in properties else {} + for name in ("num_samples", "num_models"): + if name in properties: + return {**params, name: NUM_SAMPLES}, NUM_SAMPLES + return params, 1 + + +def _assert_structure( + structure: Structure, chains: dict[str, str | None], samples: int +) -> None: + """``chains`` maps each chain id to its protein sequence, or None for a ligand.""" + assert isinstance(structure, Structure) + assert len(structure) == samples + for conformation in structure: + found = conformation.get_chains() + assert set(found) == set(chains) + for chain_id, sequence in chains.items(): + chain = found[chain_id] + if sequence is None: + assert isinstance(chain, Ligand) + continue + assert isinstance(chain, Protein) + assert chain.sequence.decode() == sequence + assert not chain.get_structure_mask().any() + + +def _read(future: StructurePredictionFuture, output: str, position: int) -> np.ndarray: + return np.asarray(future.get_item(position, output=output), dtype=float) + + +def _assert_outputs( + future: StructurePredictionFuture, + model_id: str, + samples: int, + tokens: int, + position: int = 0, + has_ligand: bool = False, + protein_chains: int = 1, +) -> None: + outputs = set(future.outputs) + assert "structures" in outputs + assert outputs <= OUTPUTS + if "plddt" in outputs: + plddt = _read(future, "plddt", position).reshape(samples, -1) + if model_id in PER_ATOM_PLDDT_IDS: + assert plddt.shape[1] > tokens + else: + assert plddt.shape[1] == tokens + assert ((plddt >= 0) & (plddt <= 100)).all() + for name in outputs & {"pae", "pde"}: + errors = _read(future, name, position) + assert errors.shape[-2:] == (tokens, tokens) + assert errors.size == samples * tokens * tokens + assert (errors >= 0).all() + if "confidence" in outputs: + confidence = future.get_item(position, output="confidence") + assert len(confidence) == samples + assert all(0 <= sample["ptm"] <= 1 for sample in confidence) + if "ptm" in outputs: + ptm = _read(future, "ptm", position) + assert ptm.shape == (samples,) + assert ((ptm >= 0) & (ptm <= 1)).all() + # test_ipae_reads_for_a_complex_with_a_ligand covers ligand complexes; + # a single protein chain has no interface to score + if "ipae" in outputs and not has_ligand and protein_chains >= 2: + assert _read(future, "ipae", position).shape == (samples,) + if "score" in outputs: + score = future.get_item(position, output="score") + assert isinstance(score, pd.DataFrame) + assert set(score["batch_idx"]) == set(range(samples)) + if "metrics" in outputs: + metrics = future.get_item(position, output="metrics") + assert isinstance(metrics, pd.DataFrame) + assert len(metrics) == 1 + assert {f"ptm.ptm_{i}" for i in range(samples)} <= set(metrics.columns) + + +@pytest.mark.e2e +@pytest.mark.parametrize("model_id", FOLD_IDS) +def test_folds_a_protein(session: OpenProtein, msa: MSAFuture, model_id: str): + model = _model(session, model_id) + params, samples = _sampling(model) + + future = model.fold(_protein(BASE_SEQUENCE, msa, model_id), **params) + + structures = future.wait(timeout=TIMEOUT) + assert len(structures) == 1 + _assert_structure(structures[0], {"A": BASE_SEQUENCE}, samples) + _assert_outputs(future, model_id, samples, len(BASE_SEQUENCE)) + + +@pytest.mark.e2e +@pytest.mark.parametrize("model_id", MULTICHAIN_IDS) +def test_folds_the_chains_of_a_complex_its_card_takes( + session: OpenProtein, paired_msa: MSAFuture, model_id: str +): + model = _model(session, model_id) + params, samples = _sampling(model) + complex = _complex(model_id, paired_msa) + chains: dict[str, str | None] = {"A": BASE_SEQUENCE, "B": UBIQUITIN_SEQUENCE} + tokens = len(BASE_SEQUENCE) + len(UBIQUITIN_SEQUENCE) + + if model_id in PROTEIN_ONLY_IDS: + with pytest.warns(UserWarning, match="left out"): + future = model.fold(complex, **params) + else: + future = model.fold(complex, **params) + chains["L"] = None + tokens += ATP_ATOMS + + (structure,) = future.wait(timeout=TIMEOUT) + _assert_structure(structure, chains, samples) + _assert_outputs( + future, + model_id, + samples, + tokens, + has_ligand="L" in chains, + protein_chains=sum(sequence is not None for sequence in chains.values()), + ) + + +@pytest.mark.e2e +@pytest.mark.xfail( + strict=True, + raises=HTTPError, + reason="ipae is not served for complexes with a ligand", +) +def test_ipae_reads_for_a_complex_with_a_ligand( + session: OpenProtein, paired_msa: MSAFuture +): + model = _model(session, "boltz-2") + params, samples = _sampling(model) + + future = model.fold(_complex("boltz-2", paired_msa), **params) + + future.wait_until_done(timeout=TIMEOUT) + assert _read(future, "ipae", 0).shape == (samples,) + + +@pytest.mark.e2e +@pytest.mark.parametrize("model_id", ["esmfold", "boltz-2"]) +def test_a_batch_reads_back_in_input_order(session: OpenProtein, model_id: str): + model = _model(session, model_id) + params, samples = _sampling(model) + sequences = [UBIQUITIN_SEQUENCE, BASE_SEQUENCE] + + future = model.fold( + [_protein(sequence, None, model_id) for sequence in sequences], **params + ) + + structures = future.wait(timeout=TIMEOUT) + for read in ( + structures, + list(future.stream()), + [future.get_item(i) for i in range(len(sequences))], + [future.unit(i).get() for i in range(len(sequences))], + ): + assert len(read) == len(sequences) + for structure, sequence in zip(read, sequences): + _assert_structure(structure, {"A": sequence}, samples) + for position, sequence in enumerate(sequences): + _assert_outputs(future, model_id, samples, len(sequence), position=position) + + +@pytest.mark.e2e +def test_an_msa_folds_its_seed_as_one_complex( + session: OpenProtein, paired_msa: MSAFuture +): + future = session.models.alphafold2.fold(paired_msa) + + (structure,) = future.wait(timeout=TIMEOUT) + _assert_structure(structure, {"A": BASE_SEQUENCE, "B": UBIQUITIN_SEQUENCE}, 1) + + +@pytest.mark.e2e +@pytest.mark.parametrize("model_id", TEMPLATE_IDS) +def test_folds_with_a_template(session: OpenProtein, template: Protein, model_id: str): + sequence = template.sequence.decode() + target = Complex({"A": _protein(sequence, None, model_id)}) + + future = _model(session, model_id).fold( + target, + templates=[Template(template=template, mapping="A")], + random_seed=SEED, + ) + + (structure,) = future.wait(timeout=TIMEOUT) + _assert_structure(structure, {"A": sequence}, 1) + + +@pytest.mark.e2e +@pytest.mark.parametrize( + "model_id", + [ + "boltz-1", + "boltz-1x", + "boltz-2", + ], +) +def test_boltz_folds_under_a_constraint( + session: OpenProtein, paired_msa: MSAFuture, model_id: str +): + future = _model(session, model_id).fold( + _complex(model_id, paired_msa), + constraints=[CONSTRAINTS[model_id]], + random_seed=SEED, + ) + + (structure,) = future.wait(timeout=TIMEOUT) + _assert_structure( + structure, {"A": BASE_SEQUENCE, "B": UBIQUITIN_SEQUENCE, "L": None}, 1 + ) + + +@pytest.mark.e2e +@pytest.mark.parametrize("model_id", ["boltz-1", "boltz-1x"]) +def test_boltz_1_refuses_a_contact_constraint( + session: OpenProtein, paired_msa: MSAFuture, model_id: str +): + with pytest.raises(HTTPError) as caught: + _model(session, model_id).fold( + _complex(model_id, paired_msa), constraints=[CONTACT] + ) + + assert caught.value.status_code == 422 + assert "contact" in caught.value.text + + +@pytest.mark.e2e +def test_boltz_2_predicts_the_affinity_of_a_binder( + session: OpenProtein, msa: MSAFuture +): + complex = Complex( + {"A": _protein(BASE_SEQUENCE, msa, "boltz-2"), "L": Ligand(smiles="CCO")} + ) + + future = session.models.boltz_2.fold( + complex, properties=[{"affinity": {"binder": "L"}}], random_seed=SEED + ) + + future.wait_until_done(timeout=TIMEOUT) + affinity = future.get_item(0, output="affinity") + assert np.isfinite(affinity["affinity_pred_value"]) + assert 0 <= affinity["affinity_probability_binary"] <= 1 + + +@pytest.mark.e2e +def test_a_fold_reloads_from_its_job_id(session: OpenProtein): + future = session.models.esmfold.fold(BASE_SEQUENCE) + (structure,) = future.wait(timeout=TIMEOUT) + + reloaded = session.jobs.get(future.id) + + assert isinstance(reloaded, StructurePredictionFuture) + assert reloaded.outputs == future.outputs + (again,) = reloaded.get() + np.testing.assert_array_equal( + again[0].get_proteins()["A"].coordinates, + structure[0].get_proteins()["A"].coordinates, + ) + np.testing.assert_array_equal(_read(reloaded, "pae", 0), _read(future, "pae", 0)) + + +@pytest.mark.e2e +def test_minifold_refuses_a_complex(session: OpenProtein): + complex = Complex({"A": Protein(sequence=BASE_SEQUENCE), "B": Protein("MKT")}) + + with pytest.raises(ValueError, match="only supports monomers"): + session.models.minifold.fold(complex) + + +@pytest.mark.e2e +@pytest.mark.parametrize("model_id", SINGLE_SEQUENCE_IDS) +def test_a_single_sequence_model_refuses_an_msa( + session: OpenProtein, msa: MSAFuture, model_id: str +): + protein = Protein(sequence=BASE_SEQUENCE) + protein.msa = msa + + with pytest.raises(ValueError, match="single-sequence model"): + _model(session, model_id).fold(protein) + + +@pytest.mark.e2e +@pytest.mark.parametrize( + "model_id", [model_id for model_id in FOLD_IDS if model_id not in TEMPLATE_IDS] +) +def test_a_model_without_templates_refuses_them( + session: OpenProtein, template: Protein, model_id: str +): + with pytest.raises(ValueError, match="takes no templates"): + _model(session, model_id).fold(BASE_SEQUENCE, templates=[template]) + + +@pytest.mark.e2e +@pytest.mark.parametrize("model_id", ["esmfold", "minifold", "boltz-2"]) +def test_a_sequence_over_the_card_maximum_is_refused( + session: OpenProtein, model_id: str +): + model = _model(session, model_id) + max_length = model.metadata.max_sequence_length + assert max_length is not None + + with pytest.raises(HTTPError) as caught: + model.fold(_protein("A" * (max_length + 1), None, model_id)) + + assert caught.value.status_code == 400 + assert str(max_length) in caught.value.text + + +@pytest.mark.e2e +@pytest.mark.parametrize( + ("model_id", "name", "value"), + [ + ("boltz-2", "num_samples", 21), + ("rosettafold-3", "num_samples", 21), + ("alphafold2", "num_models", 6), + ], +) +def test_an_out_of_range_param_is_refused( + session: OpenProtein, model_id: str, name: str, value: int +): + params: dict[str, Any] = {name: value} + + with pytest.raises(HTTPError) as caught: + _model(session, model_id).fold( + _protein(BASE_SEQUENCE, None, model_id), **params + ) + + assert caught.value.status_code == 422 + assert name in caught.value.text + + +@pytest.mark.e2e +def test_a_template_index_past_the_batch_is_refused( + session: OpenProtein, template: Protein +): + target = Complex({"A": _protein(template.sequence.decode(), None, "boltz-2")}) + + with pytest.raises(HTTPError) as caught: + session.models.boltz_2.fold( + target, templates=[Template(template=template, mapping="A", index=[0, 5])] + ) + + assert caught.value.status_code == 400 + assert "out of range" in caught.value.text diff --git a/tests/e2e/test_align_e2e.py b/tests/e2e/test_align_e2e.py index 23013d1..cdaa534 100644 --- a/tests/e2e/test_align_e2e.py +++ b/tests/e2e/test_align_e2e.py @@ -13,6 +13,8 @@ from tests.utils.sequences import mutated_antibody_sequences, random_sequence_real E2E_TIMEOUT = scaled_timeout(1.0) +# The sample wait covers the MSA search and the sampling after it. +E2E_SAMPLE_TIMEOUT = scaled_timeout(2.0) def _strip_alignment_gaps(sequence: str) -> str: @@ -21,9 +23,6 @@ def _strip_alignment_gaps(sequence: str) -> str: @pytest.mark.e2e def test_e2e_msa_workflow(session: OpenProtein, msa_seed_sequence_length: int): - """ - Tests the full MMSeqs MSA search workflow. - """ # 1. Generate unique seed sequence for this test run seed_sequence = random_sequence_real(msa_seed_sequence_length) @@ -39,9 +38,9 @@ def test_e2e_msa_workflow(session: OpenProtein, msa_seed_sequence_length: int): msa_iterator = msa_future.get() msa_data = list(msa_iterator) # returns list of (name, sequence) tuples - assert ( - msa_data[0][1] == seed_sequence - ), "Expected seed sequence to be first returned sequence" + assert msa_data[0][1] == seed_sequence, ( + "Expected seed sequence to be first returned sequence" + ) @pytest.mark.e2e @@ -49,9 +48,8 @@ def test_e2e_msa_get_before_complete_returns_clear_error( session: OpenProtein, msa_seed_sequence_length: int ): """ - Fetching MSA results before the job has completed should return a 409 with a - message that says the job hasn't produced results yet, instead of the old - misleading 404 "Requested align not found". Regression test for #529. + Fetching a stored MSA before its job has completed raises an HTTPError with + status 409 whose text names the MSA id. """ seed_sequence = random_sequence_real(msa_seed_sequence_length) @@ -66,14 +64,11 @@ def test_e2e_msa_get_before_complete_returns_clear_error( list(msa_future.get()) assert excinfo.value.status_code == 409 - assert "has not produced results yet" in excinfo.value.text + assert msa_future.id in excinfo.value.text @pytest.mark.e2e def test_e2e_msa_caching(session: OpenProtein, msa_seed_sequence_length: int): - """ - Tests the full MMSeqs MSA search workflow. - """ # Use a static seed sequence for this test seed_sequence = random_sequence_real(msa_seed_sequence_length) @@ -92,9 +87,6 @@ def test_e2e_msa_caching(session: OpenProtein, msa_seed_sequence_length: int): @pytest.mark.e2e def test_e2e_msa_sample_workflow(session: OpenProtein, msa_seed_sequence_length: int): - """ - Tests the full MMSeqs MSA search and sample workflow. - """ # 1. Generate unique seed sequence for this test run seed_sequence = random_sequence_real(msa_seed_sequence_length) @@ -105,7 +97,7 @@ def test_e2e_msa_sample_workflow(session: OpenProtein, msa_seed_sequence_length: prompt_future = msa_future.sample_prompt(num_ensemble_prompts=3) # 4. Wait for completion - prompt_future.wait_until_done(verbose=True, timeout=E2E_TIMEOUT) + prompt_future.wait_until_done(verbose=True, timeout=E2E_SAMPLE_TIMEOUT) # 5. Assert status and get results assert prompt_future.status == "SUCCESS" @@ -123,10 +115,7 @@ def test_e2e_mafft_workflow( mutated_sequences: Callable[..., list[str]], ): """ - Tests the full MAFFT alignment workflow: - 1. Starts a MAFFT job with dynamically generated sequences to avoid caching. - 2. Waits for it to complete. - 3. Fetches and validates the resulting MSA. + Sequences are generated per run so the job is never served from cache. """ # 1. Generate unique sequences for this test run generated_sequences = mutated_sequences(num_sequences=3, mutation_rate=0.05) @@ -144,9 +133,9 @@ def test_e2e_mafft_workflow( msa_proteins = list(msa_iterator) # The number of rows should be the number of sequences - assert len(msa_proteins) == len( - generated_sequences - ), "MSA data should contain a row for each sequence" + assert len(msa_proteins) == len(generated_sequences), ( + "MSA data should contain a row for each sequence" + ) # Verify that the original sequences can be recovered by removing gaps from the data rows original_sequences_from_msa = {row[1].replace("-", "") for row in msa_proteins} @@ -156,8 +145,8 @@ def test_e2e_mafft_workflow( @pytest.mark.e2e def test_e2e_mafft_caching(session: OpenProtein, base_sequence: str): """ - Tests that submitting an identical job soon after the first one completes - returns a cached result almost instantly. + Submitting an identical job soon after the first completes returns the + cached result. """ # Use a static, non-random set of sequences for this test static_sequences = [ @@ -178,14 +167,30 @@ def test_e2e_mafft_caching(session: OpenProtein, base_sequence: str): assert list(align_future_1.get()) == list(align_future_2.get()) +@pytest.mark.e2e +def test_e2e_mafft_keeps_the_names_it_was_given( + session: OpenProtein, + mutated_sequences: Callable[..., list[str]], +): + """Supplied row labels come back on the aligned rows, in input order.""" + generated_sequences = mutated_sequences(num_sequences=3, mutation_rate=0.05) + names = [f"row{i}" for i in range(len(generated_sequences))] + + align_future = session.align.mafft(sequences=generated_sequences, names=names) + align_future.wait_until_done(verbose=True, timeout=E2E_TIMEOUT) + assert align_future.status == "SUCCESS" + + msa_data = list(align_future.get()) + assert [row[0] for row in msa_data] == names + # names are positional, so each label must still sit on its own sequence + assert [row[1].replace("-", "") for row in msa_data] == generated_sequences + + @pytest.mark.e2e def test_e2e_clustalo_workflow( session: OpenProtein, mutated_sequences: Callable[..., list[str]], ): - """ - Tests the full ClustalO alignment workflow. - """ # 1. Generate unique sequences for this test run generated_sequences = mutated_sequences(num_sequences=3, mutation_rate=0.05) @@ -202,9 +207,9 @@ def test_e2e_clustalo_workflow( msa_data = list(msa_iterator) # Verify that the original sequences can be recovered by removing gaps - assert len(msa_data) == len( - generated_sequences - ), "MSA data should contain a row for each sequence" + assert len(msa_data) == len(generated_sequences), ( + "MSA data should contain a row for each sequence" + ) original_sequences_from_msa = {row[1].replace("-", "") for row in msa_data} assert set(generated_sequences) == original_sequences_from_msa @@ -214,13 +219,8 @@ def test_e2e_abnumber_workflow( session: OpenProtein, test_antibody_sequence: str, ): - """ - Tests the full antibody numbering workflow. - """ - # 1. Generate unique antibody sequences for this test run. Use - # substitution-only mutation so the variable-domain framing stays intact and - # every sequence remains numberable by AbNumber (indels would shift the - # frame and break numbering / round-trip recovery). + # Substitution-only mutation keeps the variable-domain framing intact so every + # sequence stays numberable by AbNumber. generated_sequences = mutated_antibody_sequences( test_antibody_sequence, num_sequences=3, mutation_rate=0.02 ) @@ -240,8 +240,8 @@ def test_e2e_abnumber_workflow( msa_data = list(msa_iterator) # Verify that the original sequences can be recovered - assert len(msa_data) == len( - generated_sequences - ), "MSA data should contain a row for each sequence" + assert len(msa_data) == len(generated_sequences), ( + "MSA data should contain a row for each sequence" + ) original_sequences_from_msa = {_strip_alignment_gaps(row[1]) for row in msa_data} assert set(generated_sequences) == original_sequences_from_msa diff --git a/tests/e2e/test_assaydata_e2e.py b/tests/e2e/test_assaydata_e2e.py index 7744ccb..b960f3e 100644 --- a/tests/e2e/test_assaydata_e2e.py +++ b/tests/e2e/test_assaydata_e2e.py @@ -8,6 +8,7 @@ from openprotein import OpenProtein from openprotein.data import AssayDataset +from openprotein.errors import APIError from tests.utils.strings import random_string TEST_ASSAY_DATA_DIR = "tests/data" @@ -26,11 +27,7 @@ @pytest.mark.e2e def test_assaydata_workflow_e2e(session: OpenProtein): """ - Tests an assaydata E2E workflow: - 1. Connect to the session using fixture. - 2. Reads a CSV using pandas. - 3. Uploads it to platform. - 4. Fetch the metadata and data and validate its structure. + Upload a CSV as an assay, then read its metadata and data back. """ # 1. Session is already connected via the session fixture. @@ -40,7 +37,9 @@ def test_assaydata_workflow_e2e(session: OpenProtein): # 3. Upload to platform assay_name = f"Test {random_string(10)}" assay_description = f"This is a test description: {random_string(50)}" - data = session.data.create(table=df, name=assay_name, description=assay_description) + data = session.data.Assay.create( + table=df, name=assay_name, description=assay_description + ) assert isinstance(data, AssayDataset) # 4. Validate metadata @@ -65,13 +64,14 @@ def test_assaydata_workflow_e2e(session: OpenProtein): @pytest.mark.e2e def test_assaydata_with_nan_values(session: OpenProtein): """ - Test uploading assay data with NaN values. - Validates proper handling of missing measurements. + Missing measurements survive the upload as NaN. """ df = pd.read_csv(TEST_ASSAY_DATA_FILEPATH) assay_name = f"Test_NaN_{random_string(10)}" - data = session.data.create(table=df, name=assay_name, description="Test with NaN") + data = session.data.Assay.create( + table=df, name=assay_name, description="Test with NaN" + ) # Verify NaN values are preserved out_df = data.get_slice(0, data.metadata.num_rows) @@ -82,11 +82,8 @@ def test_assaydata_with_nan_values(session: OpenProtein): @pytest.mark.e2e def test_assaydata_retrieval_by_id(session: OpenProtein, assay_small: AssayDataset): - """ - Test retrieving an assay dataset by ID. - """ # Retrieve by ID - retrieved = session.data.get(assay_small.id) + retrieved = session.data.Assay(id=assay_small.id) assert retrieved.id == assay_small.id assert retrieved.name == assay_small.name @@ -96,9 +93,6 @@ def test_assaydata_retrieval_by_id(session: OpenProtein, assay_small: AssayDatas @pytest.mark.e2e def test_assaydata_slice_boundaries(session: OpenProtein, assay_small: AssayDataset): - """ - Test edge cases for data slicing. - """ # Get first row df_first = assay_small.get_slice(0, 1) assert len(df_first) == 1 @@ -116,9 +110,6 @@ def test_assaydata_slice_boundaries(session: OpenProtein, assay_small: AssayData @pytest.mark.e2e @pytest.mark.skip("todo: reject invalid slices") def test_assaydata_invalid_slice(session: OpenProtein, assay_small: AssayDataset): - """ - Test error handling for invalid slice parameters. - """ # Out of bounds slice with pytest.raises(Exception): assay_small.get_slice(0, assay_small.metadata.num_rows + 100) @@ -135,8 +126,7 @@ def test_assaydata_invalid_slice(session: OpenProtein, assay_small: AssayDataset ) def test_assaydata_different_sizes(session: OpenProtein, assay_fixture: str, request): """ - Test assay datasets of different sizes. - Validates scalability across small, medium, and large datasets. + Small, medium and large assay datasets all upload and read back. """ # Get the fixture dynamically try: @@ -160,10 +150,7 @@ def test_assaydata_different_sizes(session: OpenProtein, assay_fixture: str, req @pytest.mark.e2e def test_assaydata_list_datasets(session: OpenProtein): - """ - Test listing all available datasets. - """ - datasets = session.data.list() + datasets = session.data.Assay.list() assert isinstance(datasets, list) # Should have at least the fixtures we created assert len(datasets) > 0 @@ -173,11 +160,8 @@ def test_assaydata_list_datasets(session: OpenProtein): def test_assaydata_metadata_consistency( session: OpenProtein, assay_small: AssayDataset ): - """ - Test that metadata remains consistent across retrievals. - """ # Get the same dataset again - retrieved = session.data.get(assay_small.id) + retrieved = session.data.Assay(id=assay_small.id) # Metadata should match assert retrieved.metadata.num_entries == assay_small.metadata.num_entries @@ -200,7 +184,7 @@ def test_assaydata_has_name_column(session: OpenProtein, with_name_column: bool) table.insert(0, "name", ["s1", "s2", "s3"]) assay_name = f"Test_name_col_{with_name_column}_{random_string(10)}" - data = session.data.create( + data = session.data.Assay.create( table=table, name=assay_name, description="name col test" ) @@ -209,9 +193,6 @@ def test_assaydata_has_name_column(session: OpenProtein, with_name_column: bool) @pytest.mark.e2e def test_assaydata_sequence_validation(session: OpenProtein, assay_small: AssayDataset): - """ - Test that all sequences in the dataset have the expected length. - """ df = assay_small.get_slice(0, assay_small.metadata.num_rows) for seq in df.sequence: @@ -219,3 +200,92 @@ def test_assaydata_sequence_validation(session: OpenProtein, assay_small: AssayD f"Sequence length mismatch: expected {assay_small.sequence_length}, " f"got {len(seq)}" ) + + +NOTES_TABLE = pd.DataFrame( + { + "name": ["s1", "s2", "s3"], + "sequence": ["AAAA", "CCCC", "GGGG"], + "activity": [0.1, None, 0.3], + "notes": ["007", None, 'run 2, "rerun"\nsee lab book'], + "run": ["1.0", "r2", "NA"], + } +) + + +@pytest.mark.e2e +def test_assaydata_metadata_columns_e2e(session: OpenProtein): + """Metadata columns are stored verbatim per row and kept out of the measurements.""" + data = session.data.Assay.create( + table=NOTES_TABLE.copy(), + name=f"Test_metadata_{random_string(10)}", + description="metadata columns", + metadata_columns=["notes", "run"], + ) + + assert data.measurement_names == ["activity"] + assert data.metadata_names == ["notes", "run"] + assert data.metadata.num_entries == 2 + assert data.metadata.num_rows == 3 + + out = data.get_slice(0, 3, include_metadata=True) + assert list(out.columns) == ["sequence", "activity", "notes", "run"] + assert out["sequence"].tolist() == ["AAAA", "CCCC", "GGGG"] + assert out["notes"].tolist() == ["007", None, 'run 2, "rerun"\nsee lab book'] + assert out["run"].tolist() == ["1.0", "r2", "NA"] + + plain = data.get_slice(0, 3) + assert list(plain.columns) == ["sequence", "activity"] + + retrieved = session.data.Assay(id=data.id) + assert retrieved.metadata_names == ["notes", "run"] + assert retrieved.measurement_names == ["activity"] + + +@pytest.mark.e2e +def test_assaydata_metadata_columns_empty_list_e2e(session: OpenProtein): + """An empty metadata_columns list uploads like a plain assay.""" + data = session.data.Assay.create( + table=NOTES_TABLE[["sequence", "activity"]].copy(), + name=f"Test_metadata_empty_{random_string(10)}", + metadata_columns=[], + ) + + assert data.metadata_names == [] + assert data.measurement_names == ["activity"] + + +@pytest.mark.e2e +def test_assaydata_text_column_requires_metadata_columns_e2e(session: OpenProtein): + """A text column is rejected as a measurement unless declared as metadata.""" + with pytest.raises(APIError, match="cannot be converted to float"): + session.data.Assay.create( + table=NOTES_TABLE.copy(), + name=f"Test_metadata_undeclared_{random_string(10)}", + ) + + +@pytest.mark.e2e +@pytest.mark.parametrize( + ("metadata_columns", "error"), + [ + (["missing"], "not found"), + (["sequence"], "reserved"), + (["name"], "reserved"), + (["Sequence"], "reserved"), + (["NAME"], "reserved"), + ], +) +def test_assaydata_invalid_metadata_columns_e2e( + session: OpenProtein, metadata_columns: list[str], error: str +): + """Missing or reserved metadata columns are rejected.""" + table = NOTES_TABLE.rename( + columns={c.lower(): c for c in metadata_columns if c.lower() in NOTES_TABLE} + ) + with pytest.raises(APIError, match=error): + session.data.Assay.create( + table=table, + name=f"Test_metadata_invalid_{random_string(10)}", + metadata_columns=metadata_columns, + ) diff --git a/tests/e2e/test_clustering_e2e.py b/tests/e2e/test_clustering_e2e.py index 9852374..ec153ef 100644 --- a/tests/e2e/test_clustering_e2e.py +++ b/tests/e2e/test_clustering_e2e.py @@ -2,11 +2,13 @@ import time -import numpy as np import pytest from openprotein import OpenProtein -from openprotein.clustering import HierarchicalClusteringFuture, HierarchicalClusteringResult, LinkageMethod, Metric +from openprotein.clustering import ( + HierarchicalClusteringFuture, + HierarchicalClusteringResult, +) from openprotein.common.reduction import ReductionType from openprotein.data import AssayDataset from openprotein.errors import HTTPError, InvalidParameterError @@ -267,4 +269,6 @@ def test_clustering_delete( break time.sleep(0.5) else: - pytest.fail(f"Expected deleted clustering job {clustering_id!r} to become unavailable") + pytest.fail( + f"Expected deleted clustering job {clustering_id!r} to become unavailable" + ) diff --git a/tests/e2e/test_data_resources_e2e.py b/tests/e2e/test_data_resources_e2e.py new file mode 100644 index 0000000..2e439d2 --- /dev/null +++ b/tests/e2e/test_data_resources_e2e.py @@ -0,0 +1,86 @@ +"""Stored assays, MSAs and prompts through ``session.data``.""" + +import pandas as pd +import pytest + +from openprotein import OpenProtein +from openprotein.data import MSA, Assay, Prompt +from openprotein.errors import HTTPError +from openprotein.jobs import JobStatus +from tests.e2e.config import scaled_timeout + +TIMEOUT = scaled_timeout(3.0) + +QUERY = "MKTAYIAKQRQISFVKSHFSRQLEERLGLIEVQAPILSRVGDGTQDNLSGAEK" +A3M = ( + f">query\n{QUERY}\n" + f">h1\n{QUERY[:10]}aa{QUERY[10:]}\n" + f">h2\n{QUERY[:20]}-{QUERY[21:]}\n" + f">h3\n{QUERY[:5]}gg{QUERY[5:30]}--{QUERY[32:]}\n" + f">h4\n{QUERY}\n" + f">h5\n{QUERY[:-1]}A\n" +) + + +def _raises_not_found(load) -> None: + with pytest.raises(HTTPError) as error: + load() + assert error.value.status_code == 404 + + +@pytest.mark.e2e +def test_an_msa_is_created_read_sampled_and_deleted(session: OpenProtein): + msa = session.data.MSA.create(A3M, format="a3m", name="e2e-resource") + try: + assert isinstance(msa, MSA) and msa.status is JobStatus.SUCCESS + assert (len(msa), msa.has_insertions) == (6, True) + + rows = list(msa) + assert [name for name, _ in rows] == ["query", "h1", "h2", "h3", "h4", "h5"] + assert {len(sequence) for _, sequence in rows} == {len(QUERY)} + assert msa[0] == ("query", QUERY) + assert "aa" in msa.to_string() and "aa" not in msa.to_string("fasta") + + loaded = session.data.MSA(id=msa.id) + assert loaded.update(description="read back").description == "read back" + assert msa.id in [listed.id for listed in session.data.MSA.list(limit=20)] + + prompt = msa.sample_prompt(replicates=2, seed=7, max_msa_sequences=3) + assert isinstance(prompt, Prompt) + assert prompt.wait(timeout=TIMEOUT) is prompt + assert len(prompt) == 2 and all(len(replicate) == 3 for replicate in prompt) + assert session.data.Prompt(id=prompt.id).status is JobStatus.SUCCESS + + embeddings = session.embedding.poet.embed([QUERY.encode()], prompt=prompt) + assert len(embeddings.wait(timeout=TIMEOUT)) == 1 + finally: + msa.delete() + _raises_not_found(lambda: session.data.MSA(id=msa.id)) + + +@pytest.mark.e2e +def test_a_prompt_is_created_read_used_and_deleted(session: OpenProtein): + replicate = f">a\n{QUERY}\n>b\n{QUERY[:-1]}A\n" + prompt = session.data.Prompt.create([replicate, replicate], name="e2e-resource") + try: + assert (prompt.status, prompt.job_id) == (JobStatus.SUCCESS, None) + assert list(prompt) == [[QUERY, QUERY[:-1] + "A"]] * 2 + assert prompt.update(name="e2e-renamed").name == "e2e-renamed" + assert prompt.id in [listed.id for listed in session.data.Prompt.list(limit=20)] + + embeddings = session.embedding.poet.embed([QUERY.encode()], prompt=prompt) + assert len(embeddings.wait(timeout=TIMEOUT)) == 1 + finally: + prompt.delete() + _raises_not_found(lambda: session.data.Prompt(id=prompt.id)) + + +@pytest.mark.e2e +def test_an_assay_is_created_read_and_deleted(session: OpenProtein): + table = pd.DataFrame({"sequence": [QUERY, QUERY[:-1] + "A"], "y": [1.0, 2.0]}) + assay = session.data.Assay.create(table, "e2e-resource") + assert isinstance(assay, Assay) and len(assay) == 2 + assert assay.update(description="read back").description == "read back" + assert session.data.Assay(id=assay.id).name == "e2e-resource" + assay.delete() + _raises_not_found(lambda: session.data.Assay(id=assay.id)) diff --git a/tests/e2e/test_design_e2e.py b/tests/e2e/test_design_e2e.py index 37a50ce..c755574 100644 --- a/tests/e2e/test_design_e2e.py +++ b/tests/e2e/test_design_e2e.py @@ -33,11 +33,8 @@ def test_design_workflow_e2e(session: OpenProtein, assay_small: AssayDataset): predictor = predictor_future assert predictor.id is not None - # The SDK's ModelCriterion requires direction and target to be set - # before serialization (otherwise the inner `criterion` field is dropped - # by Pydantic's union resolution and the backend rejects the request - # with KeyError 'criterion'). `> 0` is a generic maximize-toward-positive - # constraint suitable for a smoke test against any numeric assay. + # ModelCriterion needs a direction and target before it serializes; `> 0` is a + # generic maximize constraint that suits any numeric assay. criterion = ( ModelCriterion(model_id=predictor.id, measurement_name=property_name) > 0 ) diff --git a/tests/e2e/test_embeddings_e2e.py b/tests/e2e/test_embeddings_e2e.py index 9b85481..266de60 100644 --- a/tests/e2e/test_embeddings_e2e.py +++ b/tests/e2e/test_embeddings_e2e.py @@ -4,7 +4,6 @@ import pytest from openprotein import OpenProtein from openprotein.common.reduction import ReductionType -from openprotein.data import AssayDataset from openprotein.errors import HTTPError from tests.e2e.config import scaled_timeout @@ -41,9 +40,6 @@ def _build_paired_chain_sequence(seq_len: int) -> bytes: # Model configurations: (model_id, expected_dimension, sequence_builder). -# Once the upcoming dev rollout lets every model accept ':' separators, every -# model can use _build_paired_chain_sequence and the per-model entry can -# collapse back to (model_id, expected_dimension). EMBEDDING_MODELS = [ ("esm2_t33_650M_UR50D", 1280, _build_single_chain_sequence), ("esmc-300m", None, _build_single_chain_sequence), @@ -82,8 +78,7 @@ def test_embedding_single_model( build_sequence, ): """ - Test embedding workflow for a single model. - Validates model metadata and embedding output shape. + A single model reports metadata and returns embeddings of the expected shape. """ if model_id not in {m.id for m in session.embedding.list_models()}: pytest.skip(f"{model_id} is not available in this backend") @@ -120,7 +115,6 @@ def test_embedding_single_model( def test_embedding_reduction_types( session: OpenProtein, reduction: ReductionType, model_id: str ): - """Test different reduction types for embeddings.""" if not _supports_model(session, model_id): pytest.skip(f"{model_id} model is not available in this backend") model = session.embedding.get_model(model_id) @@ -139,8 +133,7 @@ def test_embedding_reduction_types( @pytest.mark.e2e def test_embedding_parallel_models(session: OpenProtein): """ - Test submitting embedding jobs to multiple models in parallel. - Validates that the backend can handle concurrent jobs. + Concurrent embedding jobs across models all complete. Uses a per-model sequence builder so each model gets sequences in its accepted format (e.g. ablang2 needs paired heavy:light). @@ -177,8 +170,7 @@ def test_embedding_parallel_models(session: OpenProtein): @pytest.mark.parametrize("num_seqs", [1, 10, 100]) def test_embedding_batch_sizes(session: OpenProtein, num_seqs: int, model_id: str): """ - Test embedding with different batch sizes. - Validates scalability and batch processing. + Embedding works across a range of batch sizes. """ if not _supports_model(session, model_id): pytest.skip(f"{model_id} model is not available in this backend") @@ -201,8 +193,7 @@ def test_embedding_varied_sequence_lengths( session: OpenProtein, test_sequences_varied, model_id: str ): """ - Test embedding sequences of varying lengths. - Validates handling of short, medium, long, and very long sequences. + Embedding works for short, medium, long, and very long sequences. """ if not _supports_model(session, model_id): pytest.skip(f"{model_id} model is not available in this backend") @@ -221,7 +212,6 @@ def test_embedding_varied_sequence_lengths( @pytest.mark.e2e @pytest.mark.parametrize("model_id", PER_MODEL_TEST_IDS) def test_embedding_empty_sequence_handling(session: OpenProtein, model_id: str): - """Test error handling for edge cases like empty sequences.""" if not _supports_model(session, model_id): pytest.skip(f"{model_id} model is not available in this backend") model = session.embedding.get_model(model_id) @@ -234,7 +224,6 @@ def test_embedding_empty_sequence_handling(session: OpenProtein, model_id: str): @pytest.mark.e2e @pytest.mark.parametrize("model_id", PER_MODEL_TEST_IDS) def test_embedding_invalid_amino_acids(session: OpenProtein, model_id: str): - """Test error handling for sequences with invalid amino acids.""" if not _supports_model(session, model_id): pytest.skip(f"{model_id} model is not available in this backend") model = session.embedding.get_model(model_id) @@ -329,6 +318,166 @@ def test_e2e_poet2_score_single_site_and_indel(session: OpenProtein): assert np.isfinite(row.score).all() +def _single_site_scores(model, sequence: str) -> tuple[list[float], dict[str, float]]: + """Return the wild-type scores and the substitution scores by mut_code.""" + wild_type: list[float] = [] + substitutions: dict[str, float] = {} + for row in model.single_site(sequence=sequence).wait(timeout=TIMEOUT): + score = float(np.asarray(row.score).item()) + if row.mut_code == "WT": + wild_type.append(score) + else: + substitutions[row.mut_code] = score + return wild_type, substitutions + + +@pytest.mark.e2e +def test_e2e_ablang2_single_site(session: OpenProtein): + """AbLang2 scans both chains of a paired base, skipping ':' and gap columns, + and a gapped base scores each substitution like its ungapped form.""" + if not _supports_model(session, "ablang2"): + pytest.skip("ablang2 model is not available in this backend") + + model = session.embedding.ablang2 + heavy = mutate_sequence(ANTIBODY_HEAVY_SEQUENCE, mutation_rate=0.02) + light = mutate_sequence(ANTIBODY_LIGHT_SEQUENCE, mutation_rate=0.02) + plain = f"{heavy}:{light}" + gapped = f"{heavy[:20]}-{heavy[20:]}:{light[:40]}-{light[40:]}" + + plain_wild_type, plain_scores = _single_site_scores(model, plain) + gapped_wild_type, gapped_scores = _single_site_scores(model, gapped) + + residues = len(heavy) + len(light) + for base, wild_type, scores in [ + (plain, plain_wild_type, plain_scores), + (gapped, gapped_wild_type, gapped_scores), + ]: + assert len(wild_type) == residues + assert all(score == 0.0 for score in wild_type) + assert len(scores) == 19 * residues + assert np.isfinite(list(scores.values())).all() + for code in scores: + ref, position, alt = code[0], int(code[1:-1]), code[-1] + assert base[position - 1] == ref and ref not in ":-" and alt != ref + + # Dropping the gaps maps each gapped column onto the plain base, so the + # codes shift but the scores must not. + gapped_to_plain = [i for i, c in enumerate(gapped) if c != "-"] + for code, score in gapped_scores.items(): + position = int(code[1:-1]) - 1 + plain_code = f"{code[0]}{gapped_to_plain.index(position) + 1}{code[-1]}" + assert score == pytest.approx(plain_scores[plain_code], abs=1e-4), code + assert any(int(code[1:-1]) > len(heavy) + 1 for code in plain_scores) + + +@pytest.mark.e2e +def test_e2e_esmc_score_single_site(session: OpenProtein): + """ESM-C scores every substitution at every position against the wild type.""" + if not _supports_model(session, "esmc-300m"): + pytest.skip("esmc-300m model is not available in this backend") + + base_sequence = b"ACDEFGHIKLMNPQRSTVWY" + rows = session.embedding.esmc_300m.single_site(sequence=base_sequence).wait( + timeout=TIMEOUT + ) + + assert len(rows) == 20 * len(base_sequence) + wild_type = [row for row in rows if row.mut_code == "WT"] + assert len(wild_type) == len(base_sequence) + for row in rows: + assert isinstance(row.score, np.ndarray) + assert row.score.size == 1 + assert np.isfinite(row.score).all() + assert all(row.score[0] == 0.0 for row in wild_type) + + +ESM2_SCORE_MODEL = "esm2_t6_8M_UR50D" +SUBSTITUTIONS = "ARNDCQEGHILKMFPSTWYV" + + +def _scores_by_code(rows) -> dict[str, float]: + return {row.mut_code: float(row.score[0]) for row in rows if row.mut_code != "WT"} + + +@pytest.mark.e2e +def test_e2e_esm2_score_single_site(session: OpenProtein): + """ESM2 scores every substitution at every position against the wild type.""" + if not _supports_model(session, ESM2_SCORE_MODEL): + pytest.skip(f"{ESM2_SCORE_MODEL} model is not available in this backend") + + base_sequence = random_sequence_fake(30) + model = session.embedding.get_model(ESM2_SCORE_MODEL) + rows = model.single_site(sequence=base_sequence).wait(timeout=TIMEOUT) + + assert len(rows) == 20 * len(base_sequence) + wild_type = [row for row in rows if row.mut_code == "WT"] + assert len(wild_type) == len(base_sequence) + for row in rows: + assert row.score.size == 1 + assert np.isfinite(row.score).all() + assert all(row.score[0] == 0.0 for row in wild_type) + expected = { + f"{wt}{position}{mutant}" + for position, wt in enumerate(base_sequence, start=1) + for mutant in SUBSTITUTIONS + if mutant != wt + } + assert set(_scores_by_code(rows)) == expected + + +@pytest.mark.e2e +def test_e2e_esm2_score_single_site_on_a_gapped_base(session: OpenProtein): + """Gap positions are not scanned, and the rest score as they do without the gaps.""" + if not _supports_model(session, ESM2_SCORE_MODEL): + pytest.skip(f"{ESM2_SCORE_MODEL} model is not available in this backend") + + left, right = random_sequence_fake(10), random_sequence_fake(10) + model = session.embedding.get_model(ESM2_SCORE_MODEL) + gapped = model.single_site(sequence=f"{left}--{right}").wait(timeout=TIMEOUT) + plain = model.single_site(sequence=left + right).wait(timeout=TIMEOUT) + + assert len(gapped) == len(plain) == 20 * 20 + gapped_scores = _scores_by_code(gapped) + assert not any(code[1:-1] in ("11", "12") for code in gapped_scores) + shifted = {} + for code, score in gapped_scores.items(): + position = int(code[1:-1]) + if position > 12: + position -= 2 + shifted[f"{code[0]}{position}{code[-1]}"] = score + plain_scores = _scores_by_code(plain) + assert shifted.keys() == plain_scores.keys() + for code, score in plain_scores.items(): + assert shifted[code] == pytest.approx(score, abs=1e-2) + + +@pytest.mark.e2e +def test_e2e_esm2_score_single_site_through_models(session: OpenProtein): + """The models API returns the embeddings API's scan, by site then substitution.""" + if not _supports_model(session, ESM2_SCORE_MODEL): + pytest.skip(f"{ESM2_SCORE_MODEL} model is not available in this backend") + + base_sequence = random_sequence_fake(20) + scores = ( + session.models.get_model(ESM2_SCORE_MODEL) + .single_site(base_sequence=base_sequence) + .wait(timeout=TIMEOUT) + ) + rows = ( + session.embedding.get_model(ESM2_SCORE_MODEL) + .single_site(sequence=base_sequence) + .wait(timeout=TIMEOUT) + ) + + by_code = _scores_by_code(rows) + expected = [ + 0.0 if mutant == wt else by_code[f"{wt}{position}{mutant}"] + for position, wt in enumerate(base_sequence, start=1) + for mutant in SUBSTITUTIONS + ] + assert list(scores) == pytest.approx(expected, abs=1e-6) + + @pytest.mark.e2e def test_e2e_poet2_generate_with_query_fanout(session: OpenProtein): """Validate list-valued `query` fan-out behavior for PoET2 generation.""" diff --git a/tests/e2e/test_fold_e2e.py b/tests/e2e/test_fold_e2e.py index 8e2f7d9..4398d7f 100644 --- a/tests/e2e/test_fold_e2e.py +++ b/tests/e2e/test_fold_e2e.py @@ -1,18 +1,19 @@ """End-to-end tests for the fold domain.""" +from collections.abc import Callable from copy import deepcopy from pathlib import Path -from typing import Callable, List, Tuple import numpy as np import pytest +from pydantic import ValidationError + from openprotein import OpenProtein from openprotein.align.msa import MSAFuture from openprotein.errors import APIError, HTTPError from openprotein.fold.future import FoldResultFuture from openprotein.molecules import Complex, Ligand, Protein, Structure from openprotein.molecules.template import Template - from tests.e2e.config import scaled_timeout E2E_TIMEOUT = scaled_timeout(1.5) @@ -62,7 +63,6 @@ def fold_complex(protein_complex_with_msa: tuple[Complex, MSAFuture]) -> Complex @pytest.mark.e2e def test_e2e_list_models(session: OpenProtein): - """Test listing all available fold models.""" models = session.fold.list_models() assert models assert len(models) > 0 @@ -89,7 +89,6 @@ def test_e2e_fold_rejects_total_sequence_length_above_model_max( model_id: str, uses_multichain_entity: bool, ): - """Test fold API rejects sequence/entity lengths above the model metadata max.""" available_model_ids = {model.id for model in session.fold.list_models()} if model_id not in available_model_ids: pytest.skip(f"{model_id} is not available in this backend") @@ -134,18 +133,19 @@ def test_e2e_fold_rejects_total_sequence_length_above_model_max( @pytest.mark.e2e @pytest.mark.parametrize( - "invalid_chain_id", + "invalid_chain_id,error,match", [ - "a", # chain IDs should be uppercase - "A B", # spaces are invalid - "A*", # symbols are invalid + ("a", HTTPError, "Status code"), # chain IDs should be uppercase + ("A B", ValidationError, "invalid chain id"), # spaces are invalid + ("A*", ValidationError, "invalid chain id"), # symbols are invalid ], ) def test_e2e_fold_rejects_invalid_chain_ids( session: OpenProtein, invalid_chain_id: str, + error: type[Exception], + match: str, ): - """Test fold API rejects entities containing invalid chain IDs.""" model = session.fold.boltz1 invalid_chain = Protein("A" * 16) @@ -154,15 +154,12 @@ def test_e2e_fold_rejects_invalid_chain_ids( valid_chain.msa = Protein.single_sequence_mode complex_input = Complex(chains={invalid_chain_id: invalid_chain, "B": valid_chain}) - with pytest.raises(HTTPError, match="Status code"): + with pytest.raises(error, match=match): model.fold(sequences=[complex_input]) -# Oseltamivir phosphate as a user actually submitted it. The phosphate carries -# one oxygen too many, leaving P with valence 6, so RDKit refuses to parse it. -# It reached a protenix worker, where RDKit returned None and the resulting -# Boost.Python error could not be pickled, taking the LitServe worker process -# down with it. Validation has to reject this at submission. +# Oseltamivir phosphate whose phosphate carries one oxygen too many, leaving P +# with valence 6, so RDKit refuses to parse it. UNPARSEABLE_LIGAND_SMILES = "CCOC(=O)C1=CC(C(CC1NC(=O)C)OC(CC)CC)N.OP(=O)(O)(O)O" MALFORMED_LIGAND_SMILES = [ @@ -175,7 +172,7 @@ def test_e2e_fold_rejects_invalid_chain_ids( # The same molecule written correctly: a two-fragment salt. OSELTAMIVIR_PHOSPHATE = "CCOC(=O)C1=CC(C(CC1NC(=O)C)OC(CC)CC)N.OP(=O)(O)O" -# Models whose workers accept ligand chains, and which therefore validate them. +# Models that accept ligand chains, and which therefore validate them. LIGAND_MODEL_IDS = [ "boltz-1", "boltz-1x", @@ -224,8 +221,7 @@ def test_e2e_fold_rejects_unparseable_ligand_smiles( with pytest.raises(HTTPError, match="Status code") as exc_info: model.fold(sequences=[fold_complex]) - # Pin the reason: a fold rejected for some unrelated reason would otherwise - # satisfy this test and hide the fact that ligands went unchecked. + # Pin the reason so a rejection for an unrelated cause cannot satisfy the test. assert "ligand" in exc_info.value.text.lower() @@ -236,7 +232,7 @@ def test_e2e_fold_rejects_malformed_ligand_smiles( fold_complex: Complex, smiles: str, ): - """Malformed SMILES are rejected in several shapes, not just the prod one.""" + """Malformed SMILES are rejected in every shape they can take.""" model = _require_model(session, "boltz-2") fold_complex.set_chain("D", Ligand(smiles=smiles)) @@ -299,7 +295,6 @@ def test_e2e_fold_with_esmfold( session: OpenProtein, mutated_sequences: Callable[..., list[str]], ): - """Test folding a single chain with ESMFold.""" sequence = mutated_sequences(num_sequences=2)[1] future = session.fold.esmfold.fold(sequences=[sequence]) assert isinstance(future, FoldResultFuture) @@ -317,7 +312,6 @@ def test_e2e_fold_with_esmfold2( session: OpenProtein, fold_complex: Complex, ): - """Test folding a multi-chain complex with ESMFold2.""" available_model_ids = {model.id for model in session.fold.list_models()} if "esmfold2" not in available_model_ids: pytest.skip("esmfold2 is not available in this backend") @@ -338,7 +332,6 @@ def test_e2e_fold_with_esmfold2_custom_params( session: OpenProtein, fold_complex: Complex, ): - """Test folding with ESMFold2 using custom runtime parameters.""" available_model_ids = {model.id for model in session.fold.list_models()} if "esmfold2" not in available_model_ids: pytest.skip("esmfold2 is not available in this backend") @@ -365,7 +358,6 @@ def test_e2e_fold_with_esmfold2_with_ligand( session: OpenProtein, fold_complex: Complex, ): - """Test folding a complex with a ligand chain using ESMFold2.""" available_model_ids = {model.id for model in session.fold.list_models()} if "esmfold2" not in available_model_ids: pytest.skip("esmfold2 is not available in this backend") @@ -405,7 +397,6 @@ def test_e2e_fold_with_esmfold2_with_msa( session: OpenProtein, fold_complex: Complex, ): - """Test ESMFold2 conditioned on a real MSA from the fixture.""" available_model_ids = {model.id for model in session.fold.list_models()} if "esmfold2" not in available_model_ids: pytest.skip("esmfold2 is not available in this backend") @@ -524,7 +515,6 @@ def test_e2e_fold_with_esmfold2_fast( session: OpenProtein, mutated_sequences: Callable[..., list[str]], ): - """Test folding a single chain with ESMFold2-Fast.""" available_model_ids = {model.id for model in session.fold.list_models()} if "esmfold2-fast" not in available_model_ids: pytest.skip("esmfold2-fast is not available in this backend") @@ -546,7 +536,6 @@ def test_e2e_fold_with_alphafold2_complex( session: OpenProtein, fold_complex: Complex, ): - """Test folding a multi-chain complex with AlphaFold2.""" future = session.fold.alphafold2.fold(sequences=[fold_complex]) assert isinstance(future, FoldResultFuture) # The MSA is already waited on in the fixture, so we just wait for the fold @@ -564,7 +553,6 @@ def test_e2e_fold_with_alphafold2_complex_with_num_models( session: OpenProtein, fold_complex: Complex, ): - """Test folding a multi-chain complex with num_models > 1 with AlphaFold2.""" future = session.fold.alphafold2.fold(sequences=[fold_complex], num_models=2) assert isinstance(future, FoldResultFuture) # The MSA is already waited on in the fixture, so we just wait for the fold @@ -621,7 +609,6 @@ def test_e2e_fold_with_boltz_cyclic_protein( session: OpenProtein, fold_complex: Complex, ): - """Test folding with a Boltz model and a cyclic protein.""" fold_complex.get_protein("A").cyclic = True # set first to cyclic future = session.fold.boltz1.fold(sequences=[fold_complex]) @@ -640,7 +627,6 @@ def test_e2e_fold_with_boltz_bond_constraint( session: OpenProtein, fold_complex: Complex, ): - """Test folding with a Boltz model using a 'bond' constraint.""" constraints = [{"bond": {"atom1": ["A", 10, "CA"], "atom2": ["B", 20, "CA"]}}] future = session.fold.boltz1.fold(sequences=[fold_complex], constraints=constraints) assert isinstance(future, FoldResultFuture) @@ -658,7 +644,6 @@ def test_e2e_fold_with_boltz_pocket_constraint( session: OpenProtein, fold_complex: Complex, ): - """Test folding with a Boltz model using a 'pocket' constraint.""" ligand = Ligand(smiles="CCO") constraints = [ { @@ -686,7 +671,6 @@ def test_e2e_fold_with_boltz_contact_constraint( session: OpenProtein, fold_complex: Complex, ): - """Test folding with a Boltz-1 model using a 'contact' constraint.""" constraints = [ {"contact": {"token1": ["A", 10], "token2": ["B", 20], "max_distance": 15.0}} ] @@ -728,7 +712,6 @@ def test_e2e_fold_with_boltz2_with_affinity( session: OpenProtein, fold_complex: Complex, ): - """Test folding with Boltz-2 and requesting the affinity property.""" ligand = Ligand(smiles="CCO") # Use a different chain ID properties = [{"affinity": {"binder": "D"}}] constraints = [ @@ -760,7 +743,6 @@ def test_e2e_fold_with_protenix( session: OpenProtein, fold_complex: Complex, ): - """Test folding a multi-chain complex with Protenix.""" future = session.fold.protenix.fold(sequences=[fold_complex]) assert isinstance(future, FoldResultFuture) assert future.wait_until_done(timeout=E2E_TIMEOUT) @@ -856,7 +838,6 @@ def test_e2e_fold_with_protenix_custom_params( session: OpenProtein, fold_complex: Complex, ): - """Test folding with Protenix using custom diffusion/recycle/step parameters.""" future = session.fold.protenix.fold( sequences=[fold_complex], diffusion_samples=2, @@ -1118,9 +1099,6 @@ def test_e2e_fold_with_templates( sdn_linker = b"MHHHHHHSDN" template_protein = template_protein[len(sdn_linker) :] - # Wrap as Complex so the Template mapping="A" form is valid. - # A standalone Protein target rejects any explicit mapping per - # Template.validate_for_target. fold_chain = Protein(sequence=template_protein.sequence) fold_chain.msa = Protein.single_sequence_mode fold_input = Complex(chains={"A": fold_chain}) @@ -1133,3 +1111,22 @@ def test_e2e_fold_with_templates( structure = results[0] assert structure assert isinstance(structure, Structure) + + +@pytest.mark.e2e +def test_e2e_protenix_folds_each_unseeded_call_afresh( + session: OpenProtein, + fold_complex: Complex, +): + first = session.fold.protenix_v2.fold(sequences=[fold_complex]) + second = session.fold.protenix_v2.fold(sequences=[deepcopy(fold_complex)]) + assert first.wait_until_done(timeout=E2E_TIMEOUT) + assert second.wait_until_done(timeout=E2E_TIMEOUT) + (a,) = first.get() + (b,) = second.get() + for chain_id, protein in a[0].get_proteins().items(): + assert not np.allclose( + protein.coordinates, + b[0].get_proteins()[chain_id].coordinates, + equal_nan=True, + ) diff --git a/tests/e2e/test_msa_prompt_poet_e2e.py b/tests/e2e/test_msa_prompt_poet_e2e.py new file mode 100644 index 0000000..594304a --- /dev/null +++ b/tests/e2e/test_msa_prompt_poet_e2e.py @@ -0,0 +1,44 @@ +"""Strict public v1 MSA → prompt → PoET chain.""" + +from typing import Any, cast + +import numpy as np +import pytest + +from openprotein import OpenProtein +from openprotein.jobs import JobStatus +from tests.e2e.config import scaled_timeout + +TIMEOUT = scaled_timeout(3.0) + + +@pytest.mark.e2e +def test_msa_prompt_poet_embed( + session: OpenProtein, + base_sequence: str, + mutated_sequences, +): + """All three public stages run as jobs.""" + sequences = mutated_sequences( + sequence=base_sequence, + num_sequences=8, + mutation_rate=0.05, + ) + + msa = session.align.create_msa(seed=base_sequence) + prompt = msa.sample_prompt(num_sequences=20, random_seed=7) + poet_embeddings = session.embedding.poet.embed( + sequences, prompt=prompt, reduction=None + ) + + jobs = [msa, prompt, poet_embeddings] + assert len({future.id for future in jobs}) == 3 + + assert msa.wait(timeout=TIMEOUT) + prompt_values = cast(list[list[str]], prompt.wait(timeout=TIMEOUT)) + poet_values = cast(list[Any], poet_embeddings.wait(timeout=TIMEOUT)) + + assert len(prompt_values) == 1 and prompt_values[0] + assert len(poet_values) == len(sequences) + assert all(np.isfinite(embedding).all() for _, embedding in poet_values) + assert all(future.status is JobStatus.SUCCESS for future in jobs) diff --git a/tests/e2e/test_multichain_e2e.py b/tests/e2e/test_multichain_e2e.py index bd8c226..9a1f02a 100644 --- a/tests/e2e/test_multichain_e2e.py +++ b/tests/e2e/test_multichain_e2e.py @@ -17,6 +17,9 @@ * genetic-algorithm design driven by a multi-chain GP (on-SVD and with-reduction): every designed sequence preserves the ":" layout (same length, ":" frozen at its column, never introduced elsewhere). + * genetic-algorithm design constrained by a ``DesignConstraint`` built from a + multi-chain parent: the constraint submits, and designed sequences mutate + only at the allowed positions of each chain. * alignment jobs (mafft / clustalo / abnumber) on multi-chain inputs: each chain is aligned independently and rejoined with a single ":" column, and gap-stripping each chain recovers the input chains. Chain order is @@ -27,8 +30,9 @@ type fail the job. * prompt sampling from a multi-chain MSA: sampling scores residue columns, so the ":" break is dropped from the encoded MSA and restored in the sampled - rows. Every context entry comes back as a Complex with the seed's chain - layout, across the sequence and residue budgets, ensemble replicates, + rows. Every context entry carries the seed's chain layout (a Complex from + an MSAFuture; its chains joined by ":" when read through + ``session.data.Prompt``), across the sequence and residue budgets, ensemble replicates, similarity bounds, and seed inclusion. Covers both a search-built MSA and one a user uploads directly (the non-a3m reader), including that reader's validation of a misaligned chain break. @@ -44,8 +48,6 @@ from __future__ import annotations -import io - import numpy as np import pandas as pd import pytest @@ -57,8 +59,10 @@ UnnumberedPolicy, ) from openprotein.common.reduction import ReductionType -from openprotein.design import ModelCriterion +from openprotein.data.msa import MSA +from openprotein.design import DesignConstraint, ModelCriterion from openprotein.errors import HTTPError, InvalidParameterError +from openprotein.jobs import JobStatus from openprotein.molecules import Complex from tests.e2e.config import scaled_timeout @@ -86,8 +90,6 @@ # --------------------------------------------------------------------------- # # Helpers # --------------------------------------------------------------------------- # - - def _generic_chains() -> tuple[str, str]: """Two unrelated real-ish chains for general-purpose models.""" return random_sequence_real(64), random_sequence_real(48) @@ -140,7 +142,7 @@ def _make_assay(session: OpenProtein, sequences: list[str]): "property": [float(s.count("A")) for s in sequences], } ) - return session.data.create( + return session.data.Assay.create( table=df, name=f"E2E_MultiChain_{random_string(8)}", description="Multi-chain E2E assay", @@ -171,10 +173,9 @@ def _assert_single_site_preserves_delimiter(predictor, base: str) -> None: # --------------------------------------------------------------------------- # # Embeddings: multi-chain per-residue output length # --------------------------------------------------------------------------- # - -# Linker-mean models: the backend replaces ":" with a linker and mean-pools it -# into one column, so the multi-chain per-residue length is the single-chain -# (same residues) length + one column per delimiter. The model's BOS/EOS offset +# Linker-mean models represent each ":" as one mean-pooled linker column, so +# the multi-chain per-residue length is the single-chain (same residues) length +# + one column per delimiter. The model's BOS/EOS offset # cancels in this differential. (model_id, needs_prompt) _DIFFERENTIAL_LENGTH_MODELS = [ ("esm2_t33_650M_UR50D", False), @@ -234,8 +235,6 @@ def test_multichain_embedding_length_ablang2(session: OpenProtein): # --------------------------------------------------------------------------- # # Scoring: score + single-site on multi-chain sequences (PoET / PoET-2) # --------------------------------------------------------------------------- # - - @pytest.mark.parametrize("model_id", SCORE_MODELS) def test_multichain_score(session: OpenProtein, model_id: str): """score() accepts a multi-chain sequence and returns a finite score.""" @@ -280,8 +279,6 @@ def test_multichain_single_site_score(session: OpenProtein, model_id: str): # --------------------------------------------------------------------------- # # SVD on multi-chain sequences # --------------------------------------------------------------------------- # - - @pytest.mark.parametrize("model_id", SVD_GP_MODELS) def test_multichain_svd_fit_and_embed(session: OpenProtein, model_id: str): """Fit an SVD on same-length multi-chain sequences, then embed multi-chain @@ -397,13 +394,23 @@ def _assert_design_preserves_delimiter(results, base: str) -> None: ) -def _run_multichain_design(session: OpenProtein, assay, property_name: str, predictor): +def _run_multichain_design( + session: OpenProtein, + assay, + property_name: str, + predictor, + allowed_tokens: DesignConstraint | None = None, +): """Build a maximize criterion against ``predictor`` and run a tiny GA design.""" criterion = ( ModelCriterion(model_id=predictor.id, measurement_name=property_name) > 0 ) design = session.design.create_genetic_algorithm_design( - assay=assay, criteria=criterion, num_steps=2, pop_size=4 + assay=assay, + criteria=criterion, + num_steps=2, + pop_size=4, + allowed_tokens=allowed_tokens or {}, ) assert design.wait_until_done(timeout=DESIGN_TIMEOUT), "multi-chain design failed" return design.get() @@ -446,10 +453,47 @@ def test_multichain_ga_design_gp_with_reduction(session: OpenProtein): _assert_design_preserves_delimiter(results, seqs[0]) -# --------------------------------------------------------------------------- # -# Alignment jobs on multi-chain sequences (mafft / clustalo / abnumber) -# --------------------------------------------------------------------------- # -# +def test_multichain_ga_design_with_constraint(session: OpenProtein): + """GA design constrained by a ``DesignConstraint`` over a multi-chain parent + mutates only the allowed positions of each chain.""" + model = require_embedding_model(session, DESIGN_MODEL) + heavy0, light0 = _generic_chains() + parent = f"{heavy0}:{light0}" + # 1-indexed over the full sequence, three positions in each chain + allowed = [26, 27, 28, len(heavy0) + 2, len(heavy0) + 3, len(heavy0) + 4] + + constraint = DesignConstraint(parent) + constraint.allow(positions=allowed) + allowed_tokens = constraint.as_dict() + + rng = np.random.default_rng() + seqs = [parent] + for _ in range(39): + seq = list(parent) + for p in rng.choice(allowed, size=2, replace=False): + seq[p - 1] = str(rng.choice(allowed_tokens[p])) + seqs.append("".join(seq)) + assay = _make_assay(session, seqs) + property_name = assay.measurement_names[0] + + predictor = model.fit_gp( + assay=assay, properties=[property_name], reduction=ReductionType.MEAN + ) + assert predictor.wait(timeout=PRED_TIMEOUT), "GP-with-reduction training failed" + + results = _run_multichain_design( + session, assay, property_name, predictor, allowed_tokens=constraint + ) + _assert_design_preserves_delimiter(results, parent) + for r in results: + for i, aa in enumerate(r.sequence, start=1): + if aa != ":": + assert aa in allowed_tokens[i], ( + f"design placed {aa!r} at constrained position {i}: {r.sequence!r}" + ) + + +# Alignment jobs (mafft / clustalo / abnumber) on multi-chain sequences. # Submitting ":"-delimited sequences to the alignment endpoints exercises the # split / align-each-chain / rejoin path: every chain position is aligned # independently, then rejoined with a single ":" column. @@ -710,7 +754,8 @@ def test_multichain_abnumber_mixed_chain_types_rejected(session: OpenProtein): # # Sampling scores residue columns, so the ":" break is dropped from the encoded # MSA and restored in the sampled rows. Every sampled context entry therefore -# carries the seed's chain layout and comes back as a Complex. +# carries the seed's chain layout. An entry read through ``session.data.Prompt`` +# comes back as its chains joined by ":". PROMPT_TIMEOUT = scaled_timeout(4.0) PROMPT_CONTEXT_SIZE = 8 @@ -721,16 +766,14 @@ def _multichain_msa(session: OpenProtein, chain_a: str, chain_b: str) -> MSAFutu return session.align.create_msa(seed=f"{chain_a}:{chain_b}".encode()) -def _uploaded_multichain_msa( - session: OpenProtein, query: str, rows: list[str] -) -> MSAFuture: - """A ready-made multi-chain MSA a user uploads directly, bypassing homology +def _uploaded_multichain_msa(session: OpenProtein, query: str, rows: list[str]) -> MSA: + """A ready-made multi-chain MSA a user stores directly, bypassing homology search. This is the non-a3m path: a plain FASTA block, no insertions.""" records = [f">query\n{query}"] + [ f">homolog_{i}\n{row}" for i, row in enumerate(rows) ] fasta = ("\n".join(records) + "\n").encode() - return session.align.upload_msa(io.BytesIO(fasta)) + return session.data.MSA.create(fasta, format="fasta") def _assert_multichain_prompt(replicates, n_chains: int = 2) -> None: @@ -754,6 +797,18 @@ def _assert_multichain_prompt(replicates, n_chains: int = 2) -> None: assert b":" not in chain.sequence, f"chain retains a break: {chain!r}" +def _assert_two_chain_complexes(replicates: list[list[str]]) -> None: + """Every replicate is non-empty and every entry is two non-empty chains + joined by a single ":".""" + assert replicates, "prompt returned no replicates" + for entries in replicates: + assert entries, "prompt replicate has no context entries" + for entry in entries: + chains = entry.split(":") + assert len(chains) == 2, f"expected 2 chains, got {len(chains)}: {entry!r}" + assert all(chains), f"empty chain in entry: {entry!r}" + + def _sample(msa: MSAFuture, **kwargs): """Sample a prompt and return its replicates, asserting the job succeeded.""" prompt = msa.sample_prompt(**kwargs) @@ -843,32 +898,30 @@ def test_multichain_prompt_sampling_includes_seed(session: OpenProtein): def test_multichain_prompt_sampling_from_uploaded_msa(session: OpenProtein): - """A user-uploaded MSA has no homology-search a3m behind it -- it hits the - worker's plain-FASTA/CSV reader, which has to drop the chain break itself - just like the a3m reader does.""" + """Prompt sampling drops the chain break from a user-stored MSA, as it + does for a homology-search MSA.""" chain_a, chain_b = _generic_chains() query = f"{chain_a}:{chain_b}" homologs = _multichain_same_length_dataset(10, chain_a, chain_b) msa = _uploaded_multichain_msa(session, query, homologs) - _assert_multichain_prompt(_sample(msa, num_sequences=PROMPT_CONTEXT_SIZE)) + prompt = msa.sample_prompt(max_msa_sequences=PROMPT_CONTEXT_SIZE) + prompt.wait(verbose=True, timeout=PROMPT_TIMEOUT) + assert prompt.status == JobStatus.SUCCESS + _assert_two_chain_complexes(list(prompt)) def test_multichain_prompt_uploaded_msa_misaligned_break_fails(session: OpenProtein): - """Every row of an uploaded MSA has to place its break at the query's column. - A homolog whose break lands one column early (same total width, wrong chain - boundary) fails the prompt job instead of sampling on a silently misaligned - complex.""" + """A homolog whose break lands one column early (same width, wrong chain + boundary) is refused when the MSA is stored, instead of sampling on a + silently misaligned complex.""" chain_a, chain_b = _generic_chains() query = f"{chain_a}:{chain_b}" good = _multichain_same_length_dataset(5, chain_a, chain_b) misaligned = f"{chain_a[:-1]}:{chain_a[-1]}{chain_b}" - msa = _uploaded_multichain_msa(session, query, good + [misaligned]) - - prompt = msa.sample_prompt(num_sequences=PROMPT_CONTEXT_SIZE) - prompt.wait_until_done(verbose=True, timeout=PROMPT_TIMEOUT) - assert prompt.status == "FAILURE" + with pytest.raises(HTTPError, match="Status code 400"): + _uploaded_multichain_msa(session, query, good + [misaligned]) def test_multichain_prompt_empty_chain_round_trips(session: OpenProtein): diff --git a/tests/e2e/test_predictor_e2e.py b/tests/e2e/test_predictor_e2e.py index ebd052a..615a28b 100644 --- a/tests/e2e/test_predictor_e2e.py +++ b/tests/e2e/test_predictor_e2e.py @@ -4,7 +4,6 @@ import pytest from openprotein import OpenProtein -from openprotein.common import FeatureType from openprotein.common.reduction import ReductionType from openprotein.data import AssayDataset from openprotein.errors import HTTPError, InvalidParameterError @@ -51,8 +50,7 @@ def test_predictor_training_single_model( reduction: ReductionType, ): """ - Test training a GP predictor with different embedding models. - Validates training workflow and prediction output. + A GP predictor trains on each embedding model and predicts. """ # Get the embedding model embedding_model = session.embedding.get_model(model_id) @@ -66,9 +64,9 @@ def test_predictor_training_single_model( ) # Wait for training to complete - assert predictor_future.wait( - timeout=TIMEOUT - ), f"Predictor training failed for {model_id}" + assert predictor_future.wait(timeout=TIMEOUT), ( + f"Predictor training failed for {model_id}" + ) predictor_model = predictor_future # Validate predictor metadata @@ -87,8 +85,7 @@ def test_predictor_training_single_model( @pytest.mark.e2e def test_predictor_parallel_training(session: OpenProtein, assay_small: AssayDataset): """ - Test training multiple predictors in parallel. - Validates that the backend can handle concurrent training jobs. + Concurrent training jobs all complete and predict. """ property_name = assay_small.measurement_names[0] @@ -119,9 +116,6 @@ def test_predictor_parallel_training(session: OpenProtein, assay_small: AssayDat def test_predictor_multitask( session: OpenProtein, assay_small: AssayDataset, num_properties: int ): - """ - Test training a multitask predictor with multiple properties. - """ # Get the first N measurement names properties = assay_small.measurement_names[:num_properties] @@ -148,9 +142,6 @@ def test_predictor_multitask( def test_predictor_batch_prediction( session: OpenProtein, assay_small: AssayDataset, num_sequences: int ): - """ - Test making predictions on batches of sequences. - """ # Train a predictor embedding_model = session.embedding.esm2 property_name = assay_small.measurement_names[0] @@ -182,8 +173,7 @@ def test_predictor_different_dataset_sizes( session: OpenProtein, assay_fixture: str, request ): """ - Test training predictors on datasets of different sizes. - Validates scalability and training time. + Predictors train on small, medium and large assay datasets. """ # Get the fixture dynamically try: @@ -201,9 +191,9 @@ def test_predictor_different_dataset_sizes( # Larger datasets may take longer timeout = TIMEOUT * (2 if "large" in assay_fixture else 1) - assert predictor_future.wait( - timeout=timeout - ), f"Training failed for {assay_fixture}" + assert predictor_future.wait(timeout=timeout), ( + f"Training failed for {assay_fixture}" + ) # Validate prediction works test_sequence = b"MSKGEELFTGVVPILVELDGDVNGHKFSVSGEGEGDATYGKLTLKFICTTGKLPVPWPTLV" @@ -214,9 +204,6 @@ def test_predictor_different_dataset_sizes( @pytest.mark.e2e def test_predictor_retrieval_by_id(session: OpenProtein, assay_small: AssayDataset): - """ - Test retrieving a trained predictor by ID. - """ # Train a predictor embedding_model = session.embedding.esm2 property_name = assay_small.measurement_names[0] @@ -244,9 +231,6 @@ def test_predictor_retrieval_by_id(session: OpenProtein, assay_small: AssayDatas def test_predictor_error_handling_invalid_sequence( session: OpenProtein, assay_small: AssayDataset ): - """ - Test error handling for invalid sequences in prediction. - """ # Train a predictor embedding_model = session.embedding.esm2 property_name = assay_small.measurement_names[0] @@ -265,7 +249,8 @@ def test_predictor_error_handling_invalid_sequence( ] with pytest.raises( - HTTPError, match="Status code 400" # TODO: surface the HTTP error + HTTPError, + match="Status code 400", # TODO: surface the HTTP error ): # Adjust exception type based on actual API behavior prediction_future = predictor_model.predict(sequences=[invalid_sequence]) prediction_future.wait(timeout=TIMEOUT) @@ -275,9 +260,6 @@ def test_predictor_error_handling_invalid_sequence( def test_predictor_error_handling_empty_sequence( session: OpenProtein, assay_small: AssayDataset ): - """ - Test error handling for empty sequences in prediction. - """ # Train a predictor embedding_model = session.embedding.esm2 property_name = assay_small.measurement_names[0] @@ -305,9 +287,6 @@ def test_predictor_error_handling_empty_sequence( @pytest.mark.e2e def test_predictor_list_and_pagination(session: OpenProtein): - """ - Test listing predictors and basic offset pagination behavior. - """ page_0 = session.predictor.list_predictors(limit=2, offset=0) page_1 = session.predictor.list_predictors(limit=2, offset=2) @@ -326,8 +305,7 @@ def test_predictor_train_on_svd_embeddings( n_components: int, ): """ - Test training a GP predictor on SVD-reduced embeddings. - This tests the full workflow: fit SVD -> train predictor on SVD embeddings. + Full workflow: fit SVD, then train a GP predictor on the SVD embeddings. """ # Get the embedding model embedding_model = session.embedding.get_model(model_id) @@ -342,9 +320,9 @@ def test_predictor_train_on_svd_embeddings( predictor_future = svd_model.fit_gp(assay=assay_small, properties=[property_name]) # Wait for training to complete - assert predictor_future.wait( - timeout=TIMEOUT - ), f"Predictor training on SVD embeddings failed for {model_id}" + assert predictor_future.wait(timeout=TIMEOUT), ( + f"Predictor training on SVD embeddings failed for {model_id}" + ) predictor_model = predictor_future # Validate predictor metadata @@ -368,9 +346,6 @@ def test_predictor_train_on_svd_embeddings( def test_predictor_parallel_svd_training( session: OpenProtein, assay_small: AssayDataset ): - """ - Test training multiple predictors on different SVD models in parallel. - """ property_name = assay_small.measurement_names[0] # First, fit SVD models in parallel @@ -399,9 +374,9 @@ def test_predictor_parallel_svd_training( # Wait for all training jobs to complete for model_id, future in predictor_futures: - assert future.wait( - timeout=TIMEOUT - ), f"Training on SVD embeddings failed for {model_id}" + assert future.wait(timeout=TIMEOUT), ( + f"Training on SVD embeddings failed for {model_id}" + ) # Validate all predictors can make predictions seq_len = assay_small.sequence_length or 346 @@ -421,8 +396,7 @@ def test_predictor_svd_different_n_components( session: OpenProtein, assay_small: AssayDataset, n_components: int ): """ - Test training predictors on SVD embeddings with different n_components. - Validates that predictor performance is consistent across different SVD dimensions. + Predictors train on SVD embeddings across a range of n_components. """ embedding_model = session.embedding.esm2 property_name = assay_small.measurement_names[0] @@ -451,9 +425,6 @@ def test_predictor_svd_different_n_components( def test_predictor_svd_batch_prediction( session: OpenProtein, assay_small: AssayDataset ): - """ - Test batch predictions using a predictor trained on SVD embeddings. - """ embedding_model = session.embedding.esm2 property_name = assay_small.measurement_names[0] @@ -513,9 +484,9 @@ def test_predictor_training_kernels( **kernel_kwargs, ) - assert predictor_future.wait( - timeout=TIMEOUT - ), f"Predictor training failed for kernel {kernel!r}" + assert predictor_future.wait(timeout=TIMEOUT), ( + f"Predictor training failed for kernel {kernel!r}" + ) predictor_model = predictor_future assert predictor_model.id is not None @@ -528,6 +499,18 @@ def test_predictor_training_kernels( _assert_prediction_arrays(mus=mus, vs=vs, rows=1, cols=1) + trained = predictor_model.kernel + assert trained.type == kernel + assert predictor_model.mean is not None + assert predictor_model.noise > 0 + assert trained.outputscale > 0 + if kernel == "linear": + assert not hasattr(trained, "lengthscale") + else: + assert trained.lengthscale > 0 + assert hasattr(trained, "period") == (kernel == "periodic") + assert hasattr(trained, "alpha") == (kernel == "rational_quadratic") + @pytest.mark.e2e def test_predictor_training_kernel_enum( @@ -546,9 +529,9 @@ def test_predictor_training_kernel_enum( kernel=KernelType.MATERN52, ) - assert predictor_future.wait( - timeout=TIMEOUT - ), "Predictor training failed for KernelType.MATERN52" + assert predictor_future.wait(timeout=TIMEOUT), ( + "Predictor training failed for KernelType.MATERN52" + ) seq_len = assay_small.sequence_length or 346 test_sequence = random_sequence_fake(seq_len) @@ -556,6 +539,53 @@ def test_predictor_training_kernel_enum( _assert_prediction_arrays(mus=mus, vs=vs, rows=1, cols=1) +# one linear and one GP kernel; every kernel's training is covered by +# test_predictor_training_kernels. +CROSSVALIDATE_KERNEL_CONFIGS = [ + ("linear", {}), + ("rbf", {}), +] + + +@pytest.mark.e2e +@pytest.mark.parametrize("kernel,kernel_kwargs", CROSSVALIDATE_KERNEL_CONFIGS) +def test_predictor_crossvalidate_kernels( + session: OpenProtein, + assay_small: AssayDataset, + kernel: str, + kernel_kwargs: dict, +): + """ + Crossvalidate a GP predictor trained with each kernel family and confirm + the service returns a finite mean and non-negative variance for every + held-out row of the training assay. + """ + embedding_model = session.embedding.esm2 + property_name = assay_small.measurement_names[0] + + predictor_future = embedding_model.fit_gp( + assay=assay_small, + properties=[property_name], + reduction=ReductionType.MEAN, + kernel=kernel, + **kernel_kwargs, + ) + assert predictor_future.wait(timeout=TIMEOUT), ( + f"Predictor training failed for kernel {kernel!r}" + ) + predictor_model = predictor_future + + cv_future = predictor_model.crossvalidate() + y, mus, variances = cv_future.wait(timeout=TIMEOUT) + + assert len(y) > 0, f"Crossvalidate for kernel {kernel!r} returned no rows" + assert len(mus) == len(y) + assert len(variances) == len(y) + assert np.isfinite(mus.astype(float)).all() + assert np.isfinite(variances.astype(float)).all() + assert np.all(variances.astype(float) >= 0.0) + + @pytest.mark.e2e @pytest.mark.parametrize( "kernel_kwargs,match", diff --git a/tests/e2e/test_predictor_trained_e2e.py b/tests/e2e/test_predictor_trained_e2e.py new file mode 100644 index 0000000..5434ca7 --- /dev/null +++ b/tests/e2e/test_predictor_trained_e2e.py @@ -0,0 +1,327 @@ +"""E2E tests on a few predictors trained once per module: crossvalidation, ensembles, +single-site predictions and deletion.""" + +import io +import os + +import numpy as np +import pandas as pd +import pytest + +from openprotein import OpenProtein +from openprotein.common.reduction import ReductionType +from openprotein.data import AssayDataset +from openprotein.errors import HTTPError, InvalidParameterError, JobFailedException +from openprotein.jobs import CrossvalidateResults +from openprotein.models import GPModel +from openprotein.predictor import api +from openprotein.predictor.models import PredictorModel +from tests.e2e.config import scaled_timeout +from tests.e2e.conftest import TEST_ASSAY_DATA_DIR, TEST_ASSAY_SMALL_FILE + +pytestmark = [pytest.mark.e2e, pytest.mark.xdist_group("predictor_trained")] + +TIMEOUT = scaled_timeout(2.0) + +# one null measurement, at row 3, so crossvalidation scores 14 of the 15 rows +PROPERTY = "isobutyramide_normalized_fitness" + +# three folds over the 15 assay rows, with rows 0 and 5 excluded +FOLDS = [-1 if i in (0, 5) else i % 3 for i in range(15)] + + +@pytest.fixture(scope="module") +def assay_table() -> pd.DataFrame: + return pd.read_csv(os.path.join(TEST_ASSAY_DATA_DIR, TEST_ASSAY_SMALL_FILE)) + + +@pytest.fixture(scope="module") +def scored_rows(assay_table: pd.DataFrame) -> list[int]: + return assay_table.index[assay_table[PROPERTY].notna()].tolist() + + +@pytest.fixture(scope="module") +def predictors( + session: OpenProtein, assay_small: AssayDataset +) -> dict[str, PredictorModel]: + """rbf and linear GPs on ESM2, which crossvalidate through the GP v1 and + BayesReg paths, and an rbf GP on prot-seq to ensemble with the first.""" + esm2, prot_seq = session.embedding.esm2, session.embedding.get_model("prot-seq") + futures = { + "rbf": esm2.fit_gp( + assay=assay_small, + properties=[PROPERTY], + reduction=ReductionType.MEAN, + kernel="rbf", + ), + "linear": esm2.fit_gp( + assay=assay_small, + properties=[PROPERTY], + reduction=ReductionType.MEAN, + kernel="linear", + ), + "rbf_prot_seq": prot_seq.fit_gp( + assay=assay_small, + properties=[PROPERTY], + reduction=ReductionType.MEAN, + kernel="rbf", + ), + } + for name, future in futures.items(): + assert future.wait(timeout=TIMEOUT), f"training the {name} predictor failed" + return futures + + +@pytest.fixture(scope="module") +def ensemble( + session: OpenProtein, predictors: dict[str, PredictorModel] +) -> PredictorModel: + return session.predictor.ensemble([predictors["rbf"], predictors["rbf_prot_seq"]]) + + +def _results(session: OpenProtein, future) -> CrossvalidateResults: + """The run's rows from its raw result, after checking the returned tuple + against them.""" + y, y_mu, y_var = future.wait(timeout=TIMEOUT) + raw = pd.read_csv(io.BytesIO(api.predictor_crossvalidate_get(session, future.id))) + # an ensemble result has a y_mu/y_var pair per member after its own pair + result = CrossvalidateResults( + row_index=raw["row_index"].to_numpy(), + sequence=raw["sequence"].to_numpy(), + measurement_name=raw["measurement_name"].to_numpy(), + fold=raw["fold"].to_numpy() if "fold" in raw else None, + y=raw["y"].to_numpy(dtype=float), + y_mu=raw.iloc[:, 4].to_numpy(dtype=float), + y_var=raw.iloc[:, 5].to_numpy(dtype=float), + ) + np.testing.assert_array_equal(y, result.y) + np.testing.assert_array_equal(y_mu, result.y_mu) + np.testing.assert_array_equal(y_var, result.y_var) + return result + + +def _crossvalidate( + session: OpenProtein, predictor: PredictorModel, **kwargs +) -> CrossvalidateResults: + return _results(session, predictor.crossvalidate(**kwargs)) + + +def _assert_scored(result: CrossvalidateResults, rows: np.ndarray) -> None: + assert np.isfinite(result.y_mu[rows]).all() + assert (result.y_var[rows] >= 0).all() + + +def _assert_rows_match_assay( + result: CrossvalidateResults, assay_table: pd.DataFrame, scored_rows: list[int] +) -> None: + """Each result row carries the sequence and measurement of its assay row.""" + assert sorted(result.row_index.tolist()) == scored_rows + assert (result.measurement_name == PROPERTY).all() + np.testing.assert_array_equal( + result.sequence, assay_table["sequence"].to_numpy()[result.row_index] + ) + np.testing.assert_allclose( + result.y, assay_table[PROPERTY].to_numpy()[result.row_index], rtol=1e-6 + ) + + +def _raw_crossvalidation(session: OpenProtein, job_id: str) -> pd.DataFrame: + raw = api.predictor_crossvalidate_get(session, job_id) + return pd.read_csv(io.BytesIO(raw)).set_index("row_index").sort_index() + + +@pytest.mark.parametrize("kernel", ["rbf", "linear"]) +def test_crossvalidate_default_split( + session, predictors, assay_table, scored_rows, kernel: str +): + """The default split puts every scored row in one of 5 folds.""" + result = _crossvalidate(session, predictors[kernel]) + + _assert_rows_match_assay(result, assay_table, scored_rows) + assert result.fold is not None + assert sorted(set(result.fold.tolist())) == [0, 1, 2, 3, 4] + _assert_scored(result, np.ones(len(result.y), dtype=bool)) + + +def test_crossvalidate_n_splits(session, predictors, scored_rows): + result = _crossvalidate(session, predictors["rbf"], n_splits=3) + + assert sorted(result.row_index.tolist()) == scored_rows + assert result.fold is not None + assert sorted(set(result.fold.tolist())) == [0, 1, 2] + _assert_scored(result, np.ones(len(result.y), dtype=bool)) + + +def _gp(session: OpenProtein, predictor: PredictorModel) -> GPModel: + gp = session.models.get_model(f"gp/{predictor.id}") + assert isinstance(gp, GPModel) + return gp + + +@pytest.mark.parametrize("kernel", ["rbf", "linear"]) +def test_crossvalidate_custom_folds( + session, predictors, assay_table, scored_rows, kernel: str +): + """Each row is held out in the fold it was given, and excluded rows are unscored.""" + result = ( + _gp(session, predictors[kernel]) + .crossvalidate(folds=FOLDS) + .wait(timeout=TIMEOUT) + ) + + assert isinstance(result, CrossvalidateResults) + _assert_rows_match_assay(result, assay_table, scored_rows) + assert result.fold is not None + expected = np.array([FOLDS[i] for i in result.row_index]) + np.testing.assert_array_equal(result.fold, expected) + excluded = expected == -1 + assert excluded.sum() == 2 + assert np.isnan(result.y_mu[excluded]).all() + assert np.isnan(result.y_var[excluded]).all() + _assert_scored(result, ~excluded) + + +@pytest.mark.parametrize( + "kwargs,match", + [ + ({"n_splits": 3, "folds": FOLDS}, "mutually exclusive"), + ({"folds": FOLDS[:4]}, r"one fold per row of the training assay \(15\), got 4"), + ({"folds": [-2] + FOLDS[1:]}, "fold must be -1 to exclude a row or >= 0"), + ( + {"folds": [0 if f == -1 else f * 2 for f in FOLDS]}, + "labelled 0..2 with none empty", + ), + ({"folds": [0] * 15}, "between 2 and 10 folds, got 1"), + ], +) +def test_crossvalidate_rejects_invalid_folds_client_side( + session, predictors, kwargs, match +): + with pytest.raises(InvalidParameterError, match=match): + _gp(session, predictors["rbf"]).crossvalidate(**kwargs) + + +@pytest.mark.parametrize("n_splits", [1, 11]) +def test_crossvalidate_rejects_n_splits_out_of_range(predictors, n_splits: int): + with pytest.raises(HTTPError) as error: + predictors["rbf"].crossvalidate(n_splits=n_splits) + + assert error.value.status_code == 400 + assert ( + f"invalid n_splits: expected between 2 and 10, got {n_splits}" + in error.value.text + ) + + +def test_crossvalidate_failure_reports_its_cause(session, predictors): + """A fold made only of rows without a measurement is emptied when the trainer drops + them, and the job fails with the trainer's reason.""" + folds = [i % 2 for i in range(15)] + folds[3] = 2 + future = _gp(session, predictors["rbf"]).crossvalidate(folds=folds) + + with pytest.raises( + JobFailedException, match=r"folds \[2\] have no training rows" + ) as error: + future.wait(timeout=TIMEOUT) + assert "null measurement" in (error.value.failure_message or "") + + +def test_ensemble_crossvalidate_matches_its_members(session, predictors, ensemble): + """An ensemble splits rows like its members and carries each member's predictions.""" + members = {name: predictors[name] for name in ("rbf", "rbf_prot_seq")} + futures = {name: p.crossvalidate() for name, p in members.items()} + ensemble_future = ensemble.crossvalidate() + member_results = {name: _results(session, f) for name, f in futures.items()} + result = _results(session, ensemble_future) + + order = np.argsort(result.row_index) + assert result.fold is not None + for name, member in member_results.items(): + member_order = np.argsort(member.row_index) + assert member.fold is not None + np.testing.assert_array_equal( + result.fold[order], + member.fold[member_order], + err_msg=f"{name} folds differ", + ) + _assert_scored(result, np.ones(len(result.y), dtype=bool)) + + raw = _raw_crossvalidation(session, ensemble_future.id) + for name, member in member_results.items(): + column = next( + c + for c in raw.columns + if c.startswith(f"{members[name].id}:") and c.endswith(":y_mu") + ) + member_mu = pd.Series(member.y_mu, index=member.row_index).sort_index() + np.testing.assert_allclose( + raw[column].to_numpy(), + member_mu.to_numpy(), + rtol=1e-6, + err_msg=f"{name} y_mu differs", + ) + + +def test_ensemble_predict(session, predictors, ensemble, assay_table): + """An ensemble prediction carries each member's own prediction, and its mean is the + members' mean.""" + sequence = assay_table["sequence"][0] + members = [predictors[name] for name in ("rbf", "rbf_prot_seq")] + member_futures = {m.id: m.predict(sequences=[sequence]) for m in members} + future = ensemble.predict(sequences=[sequence]) + mus, variances = future.wait(timeout=TIMEOUT) + + assert mus.shape == (1, 1 + len(members)) + assert variances.shape == mus.shape + assert np.isfinite(mus).all() + assert (variances >= 0).all() + + raw = pd.read_csv( + io.BytesIO(api.predictor_predict_get_batched_result(session, future.id)) + ) + member_mus = [] + for member_id, member_future in member_futures.items(): + member_mu, member_var = member_future.wait(timeout=TIMEOUT) + columns = [c for c in raw.columns if c.startswith(f"{member_id}:")] + mu_column = next(c for c in columns if c.endswith(":y_mu")) + var_column = next(c for c in columns if c.endswith(":y_var")) + np.testing.assert_allclose(raw[mu_column], member_mu[:, 0], rtol=1e-6) + np.testing.assert_allclose(raw[var_column], member_var[:, 0], rtol=1e-6) + member_mus.append(member_mu[:, 0]) + ensemble_mu = next( + c + for c in raw.columns + if c.startswith(f"{ensemble.id}:") and c.endswith(":y_mu") + ) + np.testing.assert_allclose(raw[ensemble_mu], np.mean(member_mus, axis=0), rtol=1e-6) + + +def test_ensemble_has_no_hyperparameters(ensemble): + with pytest.raises(HTTPError) as error: + _ = ensemble.kernel + + assert error.value.status_code == 404 + + +@pytest.mark.parametrize("kernel", ["rbf", "linear"]) +def test_single_site(predictors, assay_table, kernel: str): + """A single-site scan predicts every substitution of the base sequence and the wildtype.""" + sequence = assay_table["sequence"][0] + mus, variances = predictors[kernel].single_site(sequence).wait(timeout=TIMEOUT) + + assert mus.shape == variances.shape + assert mus.shape[1] == 1 + assert mus.shape[0] >= 19 * len(sequence) + assert np.isfinite(mus).all() + assert (variances >= 0).all() + + +def test_delete_predictor(session, predictors): + """A deleted predictor can't be fetched.""" + disposable = session.predictor.ensemble([predictors["rbf"], predictors["linear"]]) + + assert disposable.delete() + with pytest.raises(HTTPError) as error: + session.predictor.get_predictor(disposable.id) + assert error.value.status_code == 404 diff --git a/tests/e2e/test_prompt_e2e.py b/tests/e2e/test_prompt_e2e.py index 2f2ddf1..d38852b 100644 --- a/tests/e2e/test_prompt_e2e.py +++ b/tests/e2e/test_prompt_e2e.py @@ -9,7 +9,6 @@ @pytest.mark.e2e def test_prompt_e2e(session: OpenProtein) -> None: - """End-to-end test for the prompt feature.""" # 1. Create a prompt prompt_name = f"test-prompt-{random_string()}" context = ["ACDEFGHIKLMNPQRSTVWY"] @@ -42,7 +41,6 @@ def test_prompt_e2e(session: OpenProtein) -> None: @pytest.mark.e2e def test_prompt_editing_e2e(session: OpenProtein) -> None: - """End-to-end test for editing prompts and queries.""" # 1. Create an initial prompt (context) prompt_name_1 = f"test-prompt-edit-1-{random_string()}" context_1 = ["ACDEFGHIKLMNPQRSTVWY"] diff --git a/tests/e2e/test_structgen_e2e.py b/tests/e2e/test_structgen_e2e.py index 412fde1..e4a28d2 100644 --- a/tests/e2e/test_structgen_e2e.py +++ b/tests/e2e/test_structgen_e2e.py @@ -4,21 +4,21 @@ import numpy as np import pytest + from openprotein import OpenProtein from openprotein.molecules import Complex, Protein, Template - from tests.e2e.config import scaled_timeout GENERATE_TIMEOUT = scaled_timeout(2.0) -def _assert_generated_sequences(results: list, expected_count: int) -> None: - assert isinstance(results, list) - assert len(results) == expected_count - for entry in results: - assert isinstance(entry.sequence, str) - assert len(entry.sequence) > 0 - assert isinstance(entry.score, np.ndarray) +def _assert_generated_sequences(future, expected_count: int) -> None: + sequences = future.get(output="sequences") + loglikelihoods = future.get(output="loglikelihood") + assert len(sequences) == len(loglikelihoods) == expected_count + for sequence in sequences: + assert isinstance(sequence, str) + assert len(sequence) > 0 @pytest.mark.e2e @@ -33,11 +33,14 @@ def test_e2e_structure_generate_then_sequence_generate_with_design( """ n_designs = 1 n_sequences = 2 - design_future = session.models.rfdiffusion.generate(contigs=60, N=n_designs) + design_future = session.models.rfdiffusion.generate( + query=Protein.from_expr(60), num_samples=n_designs + ) assert design_future.wait_until_done(timeout=GENERATE_TIMEOUT) designs = design_future.get() assert len(designs) == n_designs + assert isinstance(designs[0], Complex) seq_future = session.models.proteinmpnn.generate( design=design_future, @@ -45,8 +48,7 @@ def test_e2e_structure_generate_then_sequence_generate_with_design( temperature=0.1, ) assert seq_future.wait_until_done(timeout=GENERATE_TIMEOUT) - results = seq_future.get() - _assert_generated_sequences(results=results, expected_count=n_designs * n_sequences) + _assert_generated_sequences(seq_future, expected_count=n_designs * n_sequences) @pytest.mark.e2e @@ -92,41 +94,85 @@ def test_e2e_proteinmpnn_generate_with_query_fanout(session: OpenProtein): temperature=0.1, ) assert future.wait_until_done(timeout=GENERATE_TIMEOUT) - results = future.get() - _assert_generated_sequences( - results=results, - expected_count=num_queries * n_sequences, + _assert_generated_sequences(future, expected_count=num_queries * n_sequences) + + +@pytest.mark.e2e +@pytest.mark.parametrize("model_id", ["proteinmpnn", "solublempnn"]) +def test_e2e_proteinmpnn_embed_multichain(session: OpenProtein, model_id: str): + """Per-residue rows line up with the sequence: NaN at each `:`, zero where + the structure has no residue.""" + structure_filepath = Path("tests/data/8bo9.cif") + if not structure_filepath.exists(): + pytest.skip(f"Missing test structure file: {structure_filepath}") + + structure = Complex(chains=Complex.from_filepath(structure_filepath).get_proteins()) + proteins = list(structure.get_proteins().values()) + query = session.prompt.create_query(query=structure) + sequence = ":".join(protein.sequence.decode() for protein in proteins) + is_break = np.array([residue == ":" for residue in sequence]) + unresolved = np.zeros(len(sequence), dtype=bool) + unresolved[~is_break] = np.concatenate( + [protein.get_structure_mask() for protein in proteins] + ) + model = getattr(session.models, model_id) + dimension = model.metadata.dimension + + [per_residue] = model.embed(sequences=[sequence], query=query, reduction=None).wait( + timeout=GENERATE_TIMEOUT ) + assert per_residue.shape == (len(sequence), dimension) + assert np.isnan(per_residue[is_break]).all() + assert np.isfinite(per_residue[~is_break]).all() + assert (per_residue[unresolved] == 0).all() + @pytest.mark.e2e -def test_e2e_proteinmpnn_score_not_implemented(session: OpenProtein): - with pytest.raises(NotImplementedError, match="Score not yet implemented"): - session.models.proteinmpnn.score( - sequences=[b"ACDEFGHIKLMNPQRSTVWY"], - query=b"ACDEFGHIKLMNPQRSTVWY", - ) +def test_e2e_proteinmpnn_score_native_against_structure(session: OpenProtein): + """ProteinMPNN scores the native sequence against its backbone, the same + way every time.""" + structure_filepath = Path("tests/data/8bo9.cif") + if not structure_filepath.exists(): + pytest.skip(f"Missing test structure file: {structure_filepath}") + + query_protein = Protein.from_filepath(path=structure_filepath, chain_id="A") + + future = session.models.proteinmpnn.score( + sequences=[query_protein.sequence, query_protein.sequence], + query=query_protein, + ) + assert future.wait_until_done(timeout=GENERATE_TIMEOUT) + first, second = future.get() + + assert first == second + per_residue_ll = first / len(query_protein.sequence) + assert -4.0 <= per_residue_ll <= 0.0 @pytest.mark.e2e -def test_e2e_proteinmpnn_indel_not_implemented(session: OpenProtein): - with pytest.raises(NotImplementedError, match="Score indel not yet implemented"): - session.models.proteinmpnn.indel( - sequence=b"ACDEFGHIKLMNPQRSTVWY", - query=b"ACDEFGHIKLMNPQRSTVWY", - insert="A", - ) +def test_e2e_proteinmpnn_has_no_indel(session: OpenProtein): + with pytest.raises(ValueError, match="has no indel"): + session.models.proteinmpnn.indel(b"ACDEFGHIKLMNPQRSTVWY", insert="A") @pytest.mark.e2e -def test_e2e_proteinmpnn_single_site_not_implemented(session: OpenProtein): - with pytest.raises( - NotImplementedError, match="Score single site not yet implemented" - ): - session.models.proteinmpnn.single_site( - sequence=b"ACDEFGHIKLMNPQRSTVWY", - query=b"ACDEFGHIKLMNPQRSTVWY", - ) +def test_e2e_proteinmpnn_single_site_against_structure(session: OpenProtein): + """ProteinMPNN scores every substitution of a resolved window, and every + unmutated row scores the same.""" + structure_filepath = Path("tests/data/8bo9.cif") + if not structure_filepath.exists(): + pytest.skip(f"Missing test structure file: {structure_filepath}") + + window = Protein.from_filepath(path=structure_filepath, chain_id="A")[10:40] + assert not window.get_structure_mask().any() + + future = session.models.proteinmpnn.single_site(window.sequence, query=window) + assert future.wait_until_done(timeout=GENERATE_TIMEOUT) + scores = np.array(future.get(), dtype=float) + + assert len(scores) == 20 * len(window.sequence) + assert np.isfinite(scores).all() @pytest.mark.e2e @@ -143,11 +189,10 @@ def test_e2e_esmif1_generate_basic(session: OpenProtein): query=query_protein, num_samples=n_sequences, temperature=1.0, - seed=42, + random_seed=42, ) assert future.wait_until_done(timeout=GENERATE_TIMEOUT) - results = future.get() - _assert_generated_sequences(results=results, expected_count=n_sequences) + _assert_generated_sequences(future, expected_count=n_sequences) # Note: samples are not asserted to be distinct. With a fixed seed (and on a # well-determined backbone) ESM-IF1 can legitimately return identical samples, # so sequence diversity is not a reliable invariant here. @@ -167,34 +212,35 @@ def test_e2e_esmif1_score_native_against_structure(session: OpenProtein): query=query_protein, ) assert future.wait_until_done(timeout=GENERATE_TIMEOUT) - results = future.get() + [score] = future.get() - assert len(results) == 1 - [row] = results - assert isinstance(row.sequence, str) - assert isinstance(row.score, np.ndarray) - assert row.score.shape == (1,) # ESM-IF1 returns ll_fullseq: the summed log-likelihood over the sequence, # which scales with length. Normalize to a per-residue average before # bounding. Natural proteins score ~[-2.5, -1.0] per residue; allow [-4, 0]. - per_residue_ll = float(row.score[0]) / len(row.sequence) + per_residue_ll = float(score) / len(query_protein.sequence) assert -4.0 <= per_residue_ll <= 0.0 @pytest.mark.e2e def test_e2e_rfdiffusion_generate_basic(session: OpenProtein): - """Standalone smoke test: rfdiffusion generates a structure from `contigs` only.""" + """Standalone smoke test: rfdiffusion designs a structure de novo from a fully masked query.""" n_designs = 1 - future = session.models.rfdiffusion.generate(contigs=60, N=n_designs) + future = session.models.rfdiffusion.generate( + query=Protein.from_expr(60), num_samples=n_designs + ) assert future.wait_until_done(timeout=GENERATE_TIMEOUT) designs = future.get() assert len(designs) == n_designs + assert isinstance(designs[0], Complex) @pytest.mark.e2e def test_e2e_rfdiffusion_query_with_mask_structure(session: OpenProtein): - """rfdiffusion fills in a partially-masked structure passed via `query`.""" + """rfdiffusion fills in a partially-masked structure passed via `query`. + + RFdiffusion ignores sequence, so a position without structure has no sequence. + """ structure_filepath = Path("tests/data/8bo9.cif") if not structure_filepath.exists(): pytest.skip(f"Missing test structure file: {structure_filepath}") @@ -208,12 +254,17 @@ def test_e2e_rfdiffusion_query_with_mask_structure(session: OpenProtein): rng = np.random.default_rng(1) kept_positions = np.sort(rng.choice(structured_positions, size=16, replace=False)) - masked = base.copy().mask_structure_except_at(kept_positions) + masked = ( + base.copy() + .mask_structure_except_at(kept_positions) + .mask_sequence_except_at(kept_positions) + ) - future = session.models.rfdiffusion.generate(query=masked, N=1) + future = session.models.rfdiffusion.generate(query=masked, num_samples=1) assert future.wait_until_done(timeout=GENERATE_TIMEOUT) designs = future.get() assert len(designs) == 1 + assert isinstance(designs[0], Complex) @pytest.mark.e2e @@ -234,24 +285,11 @@ def test_e2e_boltzgen_query_with_mask_structure(session: OpenProtein): kept_positions = np.sort(rng.choice(structured_positions, size=16, replace=False)) masked = base.copy().mask_structure_except_at(kept_positions) - future = session.models.boltzgen.generate(query=masked, N=1) - assert future.wait_until_done(timeout=GENERATE_TIMEOUT) - designs = future.get() - assert len(designs) == 1 - - -@pytest.mark.e2e -def test_e2e_boltzgen_generate_basic(session: OpenProtein): - """Standalone smoke test: boltzgen accepts a minimal design_spec.""" - design_spec = { - "entities": [ - {"protein": {"id": "A", "sequence": "ACDEFGHIKLMNPQRSTVWY"}}, - ], - } - future = session.models.boltzgen.generate(design_spec=design_spec, N=1) + future = session.models.boltzgen.generate(query=masked, num_samples=1) assert future.wait_until_done(timeout=GENERATE_TIMEOUT) designs = future.get() assert len(designs) == 1 + assert isinstance(designs[0], Complex) @pytest.mark.e2e @@ -285,9 +323,11 @@ def test_e2e_binder_design_full_flow_with_template( # structure). RFdiffusion designs the unstructured chain conditioned on # the structured one. query_complex = Complex(chains={"A": target, "B": Protein.from_expr(binder_len)}) - rfdiff_future = session.models.rfdiffusion.generate(query=query_complex, N=1) + rfdiff_future = session.models.rfdiffusion.generate( + query=query_complex, num_samples=1 + ) assert rfdiff_future.wait_until_done(timeout=GENERATE_TIMEOUT) - rfdiff_designs = rfdiff_future.get() + rfdiff_designs = rfdiff_future.get(output="structures") assert len(rfdiff_designs) == 1 rfdiff_complex = rfdiff_designs[0] assert isinstance(rfdiff_complex, Complex) @@ -298,9 +338,9 @@ def test_e2e_binder_design_full_flow_with_template( temperature=0.1, ) assert seq_future.wait_until_done(timeout=GENERATE_TIMEOUT) - seq_results = seq_future.get() + seq_results = seq_future.get(output="sequences") assert len(seq_results) == 1 - binder_sequence = seq_results[0].sequence.split(":")[1].encode() + binder_sequence = seq_results[0].split(":")[1].encode() binder_protein = Protein(sequence=binder_sequence) # The fold call requires every input Protein to have an msa attached or diff --git a/tests/e2e/test_svd_e2e.py b/tests/e2e/test_svd_e2e.py index ef85233..b9a928b 100644 --- a/tests/e2e/test_svd_e2e.py +++ b/tests/e2e/test_svd_e2e.py @@ -5,7 +5,6 @@ from openprotein import OpenProtein from openprotein.common.reduction import ReductionType -from openprotein.data import AssayDataset from openprotein.errors import HTTPError from openprotein.svd.models import SVDModel from tests.e2e.config import scaled_timeout @@ -31,10 +30,6 @@ def test_svd_single_model( expected_base_dim: int, n_components: int, ): - """ - Test fitting SVD models with different embedding models and n_components. - Validates SVD workflow and reduced embedding output. - """ # Get the embedding model embedding_model = session.embedding.get_model(model_id) @@ -45,15 +40,17 @@ def test_svd_single_model( # Wait for the model to be ready svd_model = svd_future.wait(timeout=TIMEOUT) - assert isinstance( - svd_model, SVDModel - ), f"SVD model fitting failed for {model_id} with {n_components} components" + assert isinstance(svd_model, SVDModel), ( + f"SVD model fitting failed for {model_id} with {n_components} components" + ) assert svd_model.n_components == n_components assert svd_model.n_components <= expected_base_dim # Use the SVD model to embed a sequence embedding_future = svd_model.embed(sequences=[test_sequences_same_length[0]]) - assert embedding_future.wait_until_done(timeout=TIMEOUT), f"SVD embed failed for {model_id}" + assert embedding_future.wait_until_done(timeout=TIMEOUT), ( + f"SVD embed failed for {model_id}" + ) results = embedding_future.get() # Validate the output @@ -62,9 +59,9 @@ def test_svd_single_model( seq, embedding = results[0] assert seq == test_sequences_same_length[0] assert isinstance(embedding, np.ndarray) - assert embedding.shape == ( - n_components, - ), f"Expected SVD embedding shape of ({n_components},), but got {embedding.shape} for {model_id}" + assert embedding.shape == (n_components,), ( + f"Expected SVD embedding shape of ({n_components},), but got {embedding.shape} for {model_id}" + ) assert np.isfinite(embedding).all() @@ -72,10 +69,6 @@ def test_svd_single_model( def test_svd_parallel_models( session: OpenProtein, test_sequences_same_length: list[bytes] ): - """ - Test fitting multiple SVD models in parallel. - Validates that the backend can handle concurrent SVD fitting jobs. - """ n_components = 32 # Submit SVD fitting jobs for multiple models in parallel @@ -112,9 +105,6 @@ def test_svd_parallel_models( def test_svd_reduction_types( session: OpenProtein, test_sequences_varied: list[bytes], reduction: ReductionType ): - """ - Test SVD with different reduction types for variable-length sequences. - """ embedding_model = session.embedding.esm2 n_components = 32 @@ -143,9 +133,6 @@ def test_svd_batch_embedding_same_length( test_sequences_same_length: list[bytes], num_sequences: int, ): - """ - Test SVD embedding with different batch sizes (same-length sequences). - """ embedding_model = session.embedding.esm2 n_components = 32 @@ -178,9 +165,6 @@ def test_svd_batch_embedding_same_length( ["assay_small", "assay_medium"], ) def test_svd_from_assay(session: OpenProtein, assay_fixture: str, request): - """ - Test fitting SVD from assay datasets of different sizes. - """ # Get the fixture dynamically try: assay = request.getfixturevalue(assay_fixture) @@ -215,9 +199,6 @@ def test_svd_from_assay(session: OpenProtein, assay_fixture: str, request): def test_svd_retrieval_by_id( session: OpenProtein, test_sequences_same_length: list[bytes] ): - """ - Test retrieving an SVD model by ID. - """ embedding_model = session.embedding.esm2 n_components = 32 @@ -249,9 +230,7 @@ def test_svd_edge_case_n_components_large( test_sequences_same_length: list[bytes], ): """ - Test SVD with n_components exceeding the number of sequences. - The backend should reduce n_components to min(M, N) where M is the number - of sequences and N is the embedding dimension. + n_components is reduced to min(num_sequences, embedding_dim). """ embedding_model = session.embedding.esm2 # Use n_components larger than number of sequences @@ -271,7 +250,7 @@ def test_svd_edge_case_n_components_large( f"Expected n_components to be reduced to {num_sequences}, " f"but got {svd_model.n_components}" ) - + # Verify embedding works with the reduced components embedding_future = svd_model.embed(sequences=[test_sequences_same_length[0]]) results = embedding_future.wait(timeout=TIMEOUT) @@ -287,9 +266,6 @@ def test_svd_edge_case_small_n_components( session: OpenProtein, test_sequences_same_length: list[bytes], ): - """ - Test SVD with very small n_components (e.g., 2). - """ embedding_model = session.embedding.esm2 n_components = 2 @@ -312,16 +288,13 @@ def test_svd_edge_case_small_n_components( assert np.isfinite(embedding).all() - @pytest.mark.e2e def test_svd_edge_case_n_components_exceeds_embedding_dim( session: OpenProtein, test_sequences_same_length: list[bytes], ): """ - Test SVD with n_components exceeding the embedding dimension. - The backend should reduce n_components to min(M, N) where M is the number - of sequences and N is the embedding dimension. + n_components is reduced to min(num_sequences, embedding_dim). """ embedding_model = session.embedding.esm2 # ESM2 has 1280 dimensions, use more than that @@ -342,7 +315,7 @@ def test_svd_edge_case_n_components_exceeds_embedding_dim( f"Expected n_components to be reduced to {expected_components}, " f"but got {svd_model.n_components}" ) - + # Verify embedding works with the reduced components embedding_future = svd_model.embed(sequences=[test_sequences_same_length[0]]) results = embedding_future.wait(timeout=TIMEOUT) @@ -352,14 +325,14 @@ def test_svd_edge_case_n_components_exceeds_embedding_dim( assert embedding.shape == (expected_components,) assert np.isfinite(embedding).all() + @pytest.mark.e2e def test_svd_error_different_length_sequences_no_reduction( session: OpenProtein, test_sequences_varied: list[bytes] ): """ - Test that SVD raises an error when fitting on different-length sequences - without reduction. SVD requires same-length embeddings, which means - same-length sequences when no reduction is applied. + SVD requires same-length embeddings, so without a reduction the sequences + must all be the same length. """ embedding_model = session.embedding.esm2 n_components = 32 @@ -377,8 +350,7 @@ def test_svd_different_length_sequences_with_reduction( session: OpenProtein, test_sequences_varied: list[bytes] ): """ - Test that SVD works with different-length sequences when reduction is used. - Reduction (MEAN/SUM) produces fixed-size embeddings regardless of sequence length. + A MEAN/SUM reduction produces fixed-size embeddings, so sequence lengths may vary. """ embedding_model = session.embedding.esm2 n_components = 32 diff --git a/tests/e2e/test_umap_e2e.py b/tests/e2e/test_umap_e2e.py index 52bd2ba..5057d27 100644 --- a/tests/e2e/test_umap_e2e.py +++ b/tests/e2e/test_umap_e2e.py @@ -33,10 +33,6 @@ def test_umap_single_model( expected_base_dim: int, n_components: int, ): - """ - Test fitting UMAP models with different embedding models and n_components. - Validates UMAP workflow and projected embedding output. - """ # Get the embedding model embedding_model = session.embedding.get_model(model_id) @@ -46,14 +42,18 @@ def test_umap_single_model( ) # Wait for the model to be ready - assert umap_future.wait_until_done(timeout=E2E_TIMEOUT), f"UMAP model fitting failed for {model_id}" + assert umap_future.wait_until_done(timeout=E2E_TIMEOUT), ( + f"UMAP model fitting failed for {model_id}" + ) umap_model = umap_future assert isinstance(umap_model, UMAPModel) assert umap_model.n_components == n_components # Use the UMAP model to embed a sequence embedding_future = umap_model.embed(sequences=[test_sequences_same_length[0]]) - assert embedding_future.wait_until_done(timeout=E2E_TIMEOUT), f"UMAP embed failed for {model_id}" + assert embedding_future.wait_until_done(timeout=E2E_TIMEOUT), ( + f"UMAP embed failed for {model_id}" + ) results = embedding_future.get() # Validate the output @@ -61,19 +61,15 @@ def test_umap_single_model( assert len(results) == 1 seq, embedding = results[0] assert isinstance(embedding, np.ndarray) - assert embedding.shape == ( - n_components, - ), f"Expected UMAP embedding shape of ({n_components},), but got {embedding.shape} for {model_id}" + assert embedding.shape == (n_components,), ( + f"Expected UMAP embedding shape of ({n_components},), but got {embedding.shape} for {model_id}" + ) @pytest.mark.e2e def test_umap_parallel_models( session: OpenProtein, test_sequences_same_length: list[bytes] ): - """ - Test fitting multiple UMAP models in parallel. - Validates that the backend can handle concurrent UMAP fitting jobs. - """ n_components = 3 # Submit UMAP fitting jobs for multiple models in parallel @@ -88,7 +84,9 @@ def test_umap_parallel_models( # Wait for all UMAP fitting jobs to complete umap_models = [] for model_id, future in futures: - assert future.wait_until_done(timeout=E2E_TIMEOUT), f"UMAP fitting failed for {model_id}" + assert future.wait_until_done(timeout=E2E_TIMEOUT), ( + f"UMAP fitting failed for {model_id}" + ) umap_model = future assert isinstance(umap_model, UMAPModel) assert umap_model.n_components == n_components @@ -101,9 +99,9 @@ def test_umap_parallel_models( results = embedding_future.wait(timeout=E2E_TIMEOUT) assert len(results) == 1 seq, embedding = results[0] - assert embedding.shape == ( - n_components, - ), f"Model {model_id}: unexpected UMAP embedding shape" + assert embedding.shape == (n_components,), ( + f"Model {model_id}: unexpected UMAP embedding shape" + ) @pytest.mark.e2e @@ -111,9 +109,6 @@ def test_umap_parallel_models( def test_umap_reduction_types( session: OpenProtein, test_sequences_varied: list[bytes], reduction: ReductionType ): - """ - Test UMAP with different reduction types for variable-length sequences. - """ embedding_model = session.embedding.esm2 n_components = 3 @@ -150,9 +145,6 @@ def test_umap_hyperparameters( n_neighbors: int, min_dist: float, ): - """ - Test UMAP with different hyperparameter combinations. - """ embedding_model = session.embedding.esm2 n_components = 2 @@ -186,9 +178,6 @@ def test_umap_batch_embedding( test_sequences_same_length: list[bytes], num_sequences: int, ): - """ - Test UMAP embedding with different batch sizes. - """ embedding_model = session.embedding.esm2 n_components = 3 @@ -224,9 +213,6 @@ def test_umap_from_assay( assay_fixture: str, fixture_lookup, ): - """ - Test fitting UMAP from assay datasets of different sizes. - """ # Get the fixture dynamically assay: AssayDataset = fixture_lookup(assay_fixture) @@ -257,9 +243,6 @@ def test_umap_from_assay( def test_umap_retrieval_by_id( session: OpenProtein, test_sequences_same_length: list[bytes] ): - """ - Test retrieving a UMAP model by ID. - """ embedding_model = session.embedding.esm2 n_components = 3 @@ -287,8 +270,7 @@ def test_umap_retrieval_by_id( @pytest.mark.e2e def test_umap_edge_case_small_dataset(session: OpenProtein): """ - Test UMAP with a very small dataset (minimum viable, same-length sequences). - UMAP typically requires at least n_neighbors + 1 sequences. + UMAP requires at least n_neighbors + 1 sequences. """ embedding_model = session.embedding.esm2 n_components = 2 @@ -327,9 +309,6 @@ def test_umap_edge_case_high_dimensions( session: OpenProtein, test_sequences_same_length: list[bytes], ): - """ - Test UMAP with higher dimensional output (e.g., 50 components). - """ embedding_model = session.embedding.esm2 n_components = 50 @@ -356,9 +335,8 @@ def test_umap_error_different_length_sequences_no_reduction( session: OpenProtein, test_sequences_varied: list[bytes] ): """ - Test that UMAP raises an error when fitting on different-length sequences - without reduction. UMAP requires same-length embeddings, which means - same-length sequences when no reduction is applied. + UMAP requires same-length embeddings, so without a reduction the sequences + must all be the same length. """ embedding_model = session.embedding.esm2 n_components = 3 @@ -381,8 +359,7 @@ def test_umap_different_length_sequences_with_reduction( session: OpenProtein, test_sequences_varied: list[bytes] ): """ - Test that UMAP works with different-length sequences when reduction is used. - Reduction (MEAN/SUM) produces fixed-size embeddings regardless of sequence length. + A MEAN/SUM reduction produces fixed-size embeddings, so sequence lengths may vary. """ embedding_model = session.embedding.esm2 n_components = 3 @@ -413,8 +390,7 @@ def test_umap_with_svd_features( session: OpenProtein, test_sequences_same_length: list[bytes] ): """ - Test UMAP using SVD-reduced embeddings as features. - When using SVD features, reduction must be None. + SVD features are already reduced, so reduction must be None. """ embedding_model = session.embedding.esm2 svd_n_components = 32 @@ -452,8 +428,7 @@ def test_umap_error_svd_with_reduction( session: OpenProtein, test_sequences_same_length: list[bytes] ): """ - Test that UMAP raises an error when trying to use reduction with SVD features. - SVD features are already reduced, so reduction should not be specified. + SVD features are already reduced, so specifying a reduction is an error. """ embedding_model = session.embedding.esm2 svd_n_components = 32 @@ -483,8 +458,7 @@ def test_umap_edge_case_n_neighbors_large( session: OpenProtein, test_sequences_same_length: list[bytes] ): """ - Test UMAP with n_neighbors close to the dataset size. - UMAP should handle this gracefully or adjust n_neighbors. + n_neighbors close to the dataset size is handled or adjusted by UMAP. """ embedding_model = session.embedding.esm2 n_components = 2 @@ -518,9 +492,6 @@ def test_umap_extreme_min_dist( test_sequences_same_length: list[bytes], min_dist: float, ): - """ - Test UMAP with extreme min_dist values (0.0 to 1.0). - """ embedding_model = session.embedding.esm2 n_components = 2 @@ -548,17 +519,14 @@ def test_umap_extreme_min_dist( def test_umap_sequence_length_property( session: OpenProtein, test_sequences_same_length: list[bytes] ): - """ - Test that the sequence_length property is set correctly for same-length sequences. - """ embedding_model = session.embedding.esm2 n_components = 2 # All sequences should be the same length expected_length = len(test_sequences_same_length[0]) - assert all( - len(seq) == expected_length for seq in test_sequences_same_length - ), "Test sequences should all be the same length" + assert all(len(seq) == expected_length for seq in test_sequences_same_length), ( + "Test sequences should all be the same length" + ) # Fit UMAP with same-length sequences (no reduction needed) umap_future = embedding_model.fit_umap( @@ -577,9 +545,6 @@ def test_umap_sequence_length_property( def test_umap_get_embeddings( session: OpenProtein, test_sequences_same_length: list[bytes] ): - """ - Test retrieving the projected embeddings from a fitted UMAP model. - """ embedding_model = session.embedding.esm2 n_components = 2 num_sequences = 10 @@ -606,9 +571,6 @@ def test_umap_get_embeddings( @pytest.mark.e2e def test_umap_get_model(session: OpenProtein, test_sequences_same_length: list[bytes]): - """ - Test retrieving the base embedding model from a UMAP model. - """ embedding_model = session.embedding.esm2 n_components = 2 @@ -628,9 +590,6 @@ def test_umap_get_model(session: OpenProtein, test_sequences_same_length: list[b @pytest.mark.e2e def test_umap_delete(session: OpenProtein, test_sequences_same_length: list[bytes]): - """ - Test deleting a UMAP model. - """ embedding_model = session.embedding.esm2 n_components = 2 diff --git a/tests/embeddings/test_embeddings.py b/tests/embeddings/test_embeddings.py index d978800..53fd69a 100644 --- a/tests/embeddings/test_embeddings.py +++ b/tests/embeddings/test_embeddings.py @@ -1,68 +1,143 @@ """L2 integration tests for the embeddings domain.""" -from unittest.mock import MagicMock, call, patch +from unittest.mock import MagicMock, patch import pytest -from openprotein.common import ModelMetadata from openprotein.embeddings import api as embeddings_api_module from openprotein.embeddings.embeddings import EmbeddingsAPI -from openprotein.embeddings.poet import PoETModel +from openprotein.embeddings.models import EmbeddingModel +from openprotein.models import ModelsAPI -def test_embeddings_api_init(mock_session: MagicMock): - """Test that the EmbeddingsAPI initializes models correctly.""" - # Create mock model instances with 'id' attributes - mock_model1 = MagicMock() - mock_model1.id = "prot-seq" - mock_model2 = MagicMock() - mock_model2.id = "poet-2" +def test_embeddings_api_init_is_lazy(mock_session: MagicMock): + """Constructing the API makes no requests; models resolve on access.""" + session = MagicMock() + session.models = ModelsAPI(session) - mock_models_list = [mock_model1, mock_model2] + EmbeddingsAPI(session) - # Patch list_models to return our list of configured mocks - with patch.object(EmbeddingsAPI, "list_models", return_value=mock_models_list): - api = EmbeddingsAPI(mock_session) + assert session.mock_calls == [] - # Check that the models were set as attributes with the correct names - assert hasattr(api, "prot_seq") - assert hasattr(api, "poet2") - assert api.prot_seq == mock_model1 - assert api.poet2 == mock_model2 + +def test_embeddings_api_resolves_legacy_handles(mock_session: MagicMock): + """Embedding handles retain their legacy types.""" + from contextlib import ExitStack + + from openprotein.embeddings import ( + ESMModel, + OpenProteinModel, + ) + from openprotein.embeddings.poet2 import PoET2Model + from openprotein.models import ModelsAPI + + session = MagicMock() + session.models = ModelsAPI(mock_session) + api = EmbeddingsAPI(session) + + with ExitStack() as stack: + for cls in (PoET2Model, OpenProteinModel, ESMModel): + stack.enter_context( + patch.object(cls, "get_metadata", return_value=MagicMock()) + ) + assert isinstance(api.poet2, PoET2Model) + assert api.poet2.id == "poet-2" + assert api.prot_seq.id == "prot-seq" + assert api.esm2.id == "esm2_t33_650M_UR50D" + assert api.esm2 is api.esm2_t33_650M_UR50D + assert api.esm2 is not session.models.esm2 + assert type(api.esm1b) is ESMModel + assert type(api.esm2_t6_8M_UR50D) is ESMModel + assert type(api.esmc_300m) is ESMModel + assert api.esmc_300m.id == "esmc-300m" def test_embeddings_api_get_model(mock_session: MagicMock): - """Test the get_model method of the EmbeddingsAPI.""" - mock_prot_seq = MagicMock() - mock_prot_seq.id = "prot-seq" + """get_model resolves hyphenated and aliased Gen1 names.""" + from contextlib import ExitStack + + from openprotein.embeddings import ESMModel, OpenProteinModel + from openprotein.models import ModelsAPI + + session = MagicMock() + session.models = ModelsAPI(mock_session) + api = EmbeddingsAPI(session) + + with ExitStack() as stack: + for cls in (OpenProteinModel, ESMModel): + stack.enter_context( + patch.object(cls, "get_metadata", return_value=MagicMock()) + ) + assert api.get_model("prot-seq").id == "prot-seq" + assert api.get_model("esm2").id == "esm2_t33_650M_UR50D" + with ( + patch.object(embeddings_api_module, "list_models", return_value=[]), + pytest.raises(AttributeError), + ): + api.get_model("not-a-model") + + +def test_embeddings_api_resolves_listed_models_without_a_typed_handle( + mock_session: MagicMock, +): + """A listed model without a typed handle resolves by attribute and by name.""" + metadata = MagicMock() + metadata.id = "prott5-xl" + api = EmbeddingsAPI(mock_session) + + with patch.object( + embeddings_api_module, "list_models", return_value=[metadata] + ) as listing: + model = api.prott5_xl + assert type(model) is EmbeddingModel + assert model.id == "prott5-xl" + assert api.get_model("prott5-xl") is model + listing.assert_called_once() + + +def test_embeddings_api_private_names_raise_without_a_request( + mock_session: MagicMock, +): + """Private and dunder names raise AttributeError without reading the listing.""" + api = EmbeddingsAPI(mock_session) - with patch.object(EmbeddingsAPI, "list_models", return_value=[mock_prot_seq]): - api = EmbeddingsAPI(mock_session) + with patch.object(embeddings_api_module, "list_models") as listing: + assert not hasattr(api, "_repr_html_") + assert not hasattr(api, "__deepcopy__") + listing.assert_not_called() - # Test getting the model by its name - model = api.get_model("prot-seq") - assert model is mock_prot_seq - # Test getting the model with a hyphenated name - model_by_hyphen = api.get_model("prot-seq") - assert model_by_hyphen is mock_prot_seq +def test_embeddings_api_without_a_session_raises_without_a_request(): + """An instance with no session resolves no model names.""" + api = EmbeddingsAPI.__new__(EmbeddingsAPI) + + with patch.object(embeddings_api_module, "list_models") as listing: + assert not hasattr(api, "prott5_xl") + assert not hasattr(api, "session") + listing.assert_not_called() def test_embeddings_api_model_call(mock_session: MagicMock): - """Test calling a method on a model through the EmbeddingsAPI.""" - mock_poet_instance = MagicMock(spec=PoETModel) - mock_poet_instance.id = "poet" + """Legacy embeddings post to the embeddings endpoint.""" + session = MagicMock() + session.models = ModelsAPI(session) + api = EmbeddingsAPI(session) + session.post.return_value.json.return_value = { + "job_id": "job-1", + "job_type": "/embeddings/embed", + "status": "PENDING", + "created_date": "2026-09-05T08:00:00Z", + } - with patch.object(EmbeddingsAPI, "list_models", return_value=[mock_poet_instance]): - api = EmbeddingsAPI(mock_session) + from openprotein.embeddings import ESMModel - # Access the dynamically set attribute and call a method - api.poet.embed(sequences=[b"ACGT"], prompt="p1") + with patch.object(ESMModel, "get_metadata", return_value=MagicMock()): + api.esm2.embed(sequences=["ACGT"]) - # Verify that the embed method on our mock instance was called - mock_poet_instance.embed.assert_called_once_with( - sequences=[b"ACGT"], prompt="p1" - ) + assert session.post.call_args.args == ( + "v1/embeddings/models/esm2_t33_650M_UR50D/embed", + ) + assert session.models.esm2.id == "esm2_t33_650M_UR50D" def test_embeddings_list_models_uses_verbose(mock_session: MagicMock): @@ -78,8 +153,6 @@ def test_embeddings_list_models_uses_verbose(mock_session: MagicMock): return_value=[mock_metadata1, mock_metadata2], ) as mock_list: emb_api = EmbeddingsAPI(mock_session) + result = emb_api.list_models() mock_list.assert_called_once_with(mock_session, verbose=True) - - # Models should be created with the metadata objects - assert hasattr(emb_api, "prot_seq") - assert hasattr(emb_api, "poet") + assert [m.id for m in result] == ["prot-seq", "poet"] diff --git a/tests/embeddings/test_embeddings_api.py b/tests/embeddings/test_embeddings_api.py index 2c813f7..471743e 100644 --- a/tests/embeddings/test_embeddings_api.py +++ b/tests/embeddings/test_embeddings_api.py @@ -1,6 +1,6 @@ """Test the api for the embeddings domain.""" -from unittest.mock import MagicMock, call +from unittest.mock import MagicMock import numpy as np import pytest @@ -10,7 +10,6 @@ def test_list_models(mock_session: MagicMock): - """Test the list_models API function.""" mock_session.get.return_value.json.return_value = ["model1", "model2"] result = api.list_models(mock_session) mock_session.get.assert_called_once_with("v1/embeddings/models", params={}) @@ -18,7 +17,6 @@ def test_list_models(mock_session: MagicMock): def test_list_models_verbose(mock_session: MagicMock): - """Test the list_models API function with verbose=True returns ModelMetadata.""" mock_session.get.return_value.json.return_value = [ { "model_id": "model1", @@ -48,7 +46,6 @@ def test_list_models_verbose(mock_session: MagicMock): def test_get_model(mock_session: MagicMock): - """Test the get_model API function.""" mock_session.get.return_value.json.return_value = { "model_id": "model1", "description": {"summary": "A test model"}, @@ -62,7 +59,6 @@ def test_get_model(mock_session: MagicMock): def test_get_request_sequences(mock_session: MagicMock): - """Test get_request_sequences.""" job_id = "job_123" job_type = JobType.embeddings_embed expected_sequences = [b"seq1", b"seq2"] @@ -77,7 +73,6 @@ def test_get_request_sequences(mock_session: MagicMock): def test_request_get_sequence_result(mock_session: MagicMock): - """Test request_get_sequence_result.""" job_id = "job_123" sequence = b"seq1" job_type = JobType.embeddings_embed @@ -93,7 +88,6 @@ def test_request_get_sequence_result(mock_session: MagicMock): def test_result_decode(): - """Test result_decode.""" arr = np.array([1.0, 2.0, 3.0]) encoded = arr.tobytes() with pytest.raises(ValueError): @@ -112,7 +106,6 @@ def test_result_decode(): def test_embedding_request_posts( mock_session: MagicMock, api_func, schema_class, job_type ): - """Test POST requests for various embedding-related jobs.""" model_id = "test_model" sequences = ["ACGT"] job_id = "job-123" @@ -135,7 +128,6 @@ def test_embedding_request_posts( def test_request_generate_post_with_query_id_list(mock_session: MagicMock): - """Test generation POST body when query_id is provided as a list.""" mock_session.post.return_value.json.return_value = { "job_id": "job-123", "status": JobStatus.SUCCESS, diff --git a/tests/embeddings/test_embeddings_future.py b/tests/embeddings/test_embeddings_future.py index 22224c6..3b6a4e5 100644 --- a/tests/embeddings/test_embeddings_future.py +++ b/tests/embeddings/test_embeddings_future.py @@ -9,9 +9,6 @@ ) -# --- Generate --- - - def test_embeddings_generate_future_stream_without_query_id_column(mock_session): job = MagicMock() job.job_id = "job-123" @@ -84,9 +81,6 @@ def test_embeddings_generate_future_stream_with_empty_query_id(mock_session): assert results[0].query_id is None -# --- Score --- - - def test_embeddings_score_future_stream_without_query_id(mock_session): job = MagicMock() job.job_id = "job-123" @@ -159,9 +153,6 @@ def test_embeddings_score_future_stream_with_empty_query_id(mock_session): assert results[0].query_id is None -# --- SingleSite --- - - def test_embeddings_single_site_future_stream_without_query_id(mock_session): job = MagicMock() job.job_id = "job-123" diff --git a/tests/embeddings/test_embeddings_models.py b/tests/embeddings/test_embeddings_models.py index b9a8b76..61d5875 100644 --- a/tests/embeddings/test_embeddings_models.py +++ b/tests/embeddings/test_embeddings_models.py @@ -4,6 +4,7 @@ import pytest +from openprotein.embeddings.ablang import AbLang2Model from openprotein.embeddings.esm import ESMModel from openprotein.embeddings.models import EmbeddingModel from openprotein.embeddings.openprotein import OpenProteinModel @@ -16,10 +17,12 @@ "model_id, expected_class", [ ("esm1b_t33_650M_UR50S", ESMModel), + ("esm1v_t33_650M_UR90S_1", ESMModel), ("esm2_t33_650M_UR50D", ESMModel), ("esmc-300m", ESMModel), ("esmc-600m", ESMModel), ("esmc-6b", ESMModel), + ("ablang2", AbLang2Model), ("prot-seq", OpenProteinModel), ("poet", PoETModel), ("poet-2", PoET2Model), @@ -27,7 +30,6 @@ ], ) def test_embedding_model_create(model_id, expected_class): - """Test the EmbeddingModel.create factory method.""" mock_session = MagicMock() # The factory calls get_metadata, which we can ignore for this test with patch.object( @@ -43,7 +45,6 @@ def test_embedding_model_create(model_id, expected_class): def test_embedding_model_create_with_metadata(): - """Test that pre-provided metadata skips the get_metadata API call.""" mock_session = MagicMock() mock_metadata = MagicMock() mock_metadata.id = "prot-seq" @@ -63,7 +64,6 @@ def test_embedding_model_create_with_metadata(): def test_embedding_model_create_unsupported_error(): - """Test that creating an unsupported model without a default raises an error.""" mock_session = MagicMock() with pytest.raises( ValueError, match="Unsupported model_id type: unsupported-model" @@ -72,7 +72,6 @@ def test_embedding_model_create_unsupported_error(): def test_embedding_model_embed(mock_session: MagicMock): - """Test the base EmbeddingModel.embed method.""" with patch("openprotein.embeddings.api.get_model", return_value=MagicMock()): model = EmbeddingModel(session=mock_session, model_id="test-model") @@ -95,7 +94,6 @@ def test_embedding_model_embed(mock_session: MagicMock): def test_poet_model_embed(mock_session: MagicMock): - """Test that PoETModel.embed correctly passes the prompt_id.""" with patch("openprotein.embeddings.api.get_model", return_value=MagicMock()): model = PoETModel(session=mock_session, model_id="poet") @@ -119,7 +117,6 @@ def test_poet_model_embed(mock_session: MagicMock): def test_poet2_model_embed(): - """Test that PoET2Model.embed correctly passes prompt and query IDs.""" from openprotein.prompt import PromptAPI mock_session = MagicMock() @@ -152,7 +149,6 @@ def test_poet2_model_embed(): def test_poet2_model_generate_with_query_list(): - """Test that PoET2Model.generate forwards list-valued query via query_id.""" from openprotein.prompt import PromptAPI mock_session = MagicMock() @@ -179,3 +175,93 @@ def test_poet2_model_generate_with_query_list(): ) _, kwargs = mock_request_post.call_args assert kwargs["query_id"] == ["query-1", "query-2"] + + +@pytest.mark.parametrize( + "model_class, model_id", + [ + (ESMModel, "esm1b_t33_650M_UR50S"), + (ESMModel, "esm2_t33_650M_UR50D"), + (ESMModel, "esmc-300m"), + ], +) +def test_single_site_forwards_base_sequence(model_class, model_id): + """single_site() posts the base sequence and returns the single-site future.""" + mock_session = MagicMock() + + with patch("openprotein.embeddings.api.get_model", return_value=MagicMock()): + model = model_class(session=mock_session, model_id=model_id) + + with ( + patch( + "openprotein.embeddings.esm.api.request_score_single_site_post", + return_value=MagicMock(), + ) as mock_request_post, + patch( + "openprotein.embeddings.esm.EmbeddingsScoreSingleSiteFuture.create", + return_value=MagicMock(), + ) as mock_future_create, + ): + model.single_site(sequence="MKTLL") + + _, kwargs = mock_request_post.call_args + assert kwargs["model_id"] == model_id + assert kwargs["base_sequence"] == "MKTLL" + mock_future_create.assert_called_once() + + +def test_ablang2_single_site_forwards_base_sequence(): + """single_site() posts the base sequence and returns the single-site future.""" + mock_session = MagicMock() + + with patch("openprotein.embeddings.api.get_model", return_value=MagicMock()): + model = AbLang2Model(session=mock_session, model_id="ablang2") + + with ( + patch( + "openprotein.embeddings.ablang.api.request_score_single_site_post", + return_value=MagicMock(), + ) as mock_request_post, + patch( + "openprotein.embeddings.ablang.EmbeddingsScoreSingleSiteFuture.create", + return_value=MagicMock(), + ) as mock_future_create, + ): + model.single_site(sequence="EVQL:DIQM") + + _, kwargs = mock_request_post.call_args + assert kwargs["model_id"] == "ablang2" + assert kwargs["base_sequence"] == "EVQL:DIQM" + mock_future_create.assert_called_once() + + +@pytest.mark.parametrize( + ("model_class", "model_id"), [(PoETModel, "poet"), (PoET2Model, "poet-2")] +) +def test_a_poet_model_sends_the_id_of_a_stored_prompt_that_is_not_ready( + model_class, model_id +): + from openprotein.data.prompts import Prompt, PromptSummary + from openprotein.jobs import JobStatus + from openprotein.prompt import PromptAPI + + session = MagicMock() + session.prompt = MagicMock(spec=PromptAPI) + session.prompt._resolve_query.return_value = None + prompt = Prompt( + session, + PromptSummary(id="prompt-9", status=JobStatus.PENDING, job_id="prompt-9"), + ) + job = { + "job_id": "job-123", + "status": "PENDING", + "job_type": JobType.embeddings_embed.value, + "created_date": "2023-01-01T00:00:00", + } + with patch("openprotein.embeddings.api.get_model", return_value=MagicMock()): + model = model_class(session=session, model_id=model_id) + + with patch("openprotein.embeddings.api.request_post", return_value=job) as post: + model.embed(sequences=[b"ACGT"], prompt=prompt) + + assert post.call_args.kwargs["prompt_id"] == "prompt-9" diff --git a/tests/embeddings/test_embeddings_poet2.py b/tests/embeddings/test_embeddings_poet2.py new file mode 100644 index 0000000..7b2792e --- /dev/null +++ b/tests/embeddings/test_embeddings_poet2.py @@ -0,0 +1,29 @@ +"""PoET-2 scoring runs the CLM decoder, so `mlm` is refused before any request.""" + +from unittest.mock import MagicMock + +import pytest + +from openprotein.embeddings.poet2 import PoET2Model +from openprotein.errors import InvalidParameterError + + +@pytest.fixture +def poet2(mock_session: MagicMock) -> PoET2Model: + return PoET2Model(session=mock_session, model_id="poet-2", metadata=MagicMock()) + + +@pytest.mark.parametrize( + "method,kwargs", + [ + ("score", {"sequences": [b"MQIF"]}), + ("indel", {"sequence": b"MQIF"}), + ("single_site", {"sequence": b"MQIF"}), + ], +) +def test_score_family_rejects_mlm_decoder( + poet2: PoET2Model, mock_session: MagicMock, method: str, kwargs: dict +): + with pytest.raises(InvalidParameterError, match="cannot be `mlm` for scoring"): + getattr(poet2, method)(decoder_type="mlm", **kwargs) + mock_session.post.assert_not_called() diff --git a/tests/embeddings/test_embeddings_schemas.py b/tests/embeddings/test_embeddings_schemas.py index fc02760..a75c1d9 100644 --- a/tests/embeddings/test_embeddings_schemas.py +++ b/tests/embeddings/test_embeddings_schemas.py @@ -18,7 +18,6 @@ def test_embedded_sequence_behavior(): - """Test the tuple-like behavior of EmbeddedSequence.""" sequence = b"ACGT" embedding = np.array([1.0, 2.0, 3.0]) embedded_sequence = EmbeddedSequence(sequence=sequence, embedding=embedding) @@ -37,7 +36,6 @@ def test_embedded_sequence_behavior(): def test_embedded_sequence_with_invalid_index(): - """Test that IndexError is raised for out-of-bounds access.""" embedded_sequence = EmbeddedSequence( sequence=b"ACGT", embedding=np.array([1.0, 2.0]) ) @@ -58,7 +56,6 @@ def test_embedded_sequence_with_invalid_index(): ], ) def test_job_schemas_job_type(job_class, expected_job_type): - """Test that each job schema has the correct default job_type.""" job_data = { "job_id": "job-123", "status": JobStatus.SUCCESS, @@ -69,7 +66,6 @@ def test_job_schemas_job_type(job_class, expected_job_type): def test_embeddings_job_with_reduced_type(): - """Test that EmbeddingsJob can handle the reduced embedding job type.""" job_data = { "job_id": "job-123", "status": JobStatus.SUCCESS, @@ -81,7 +77,6 @@ def test_embeddings_job_with_reduced_type(): def test_job_schemas_invalid_job_type(): - """Test that validation fails for an incorrect job_type.""" job_data = { "job_id": "job-123", "status": JobStatus.SUCCESS, diff --git a/tests/embeddings/typecheck_stored_prompt.py b/tests/embeddings/typecheck_stored_prompt.py new file mode 100644 index 0000000..c7dd91e --- /dev/null +++ b/tests/embeddings/typecheck_stored_prompt.py @@ -0,0 +1,14 @@ +"""A stored prompt is a prompt to the PoET models, statically.""" + +from openprotein.data.prompts import Prompt +from openprotein.embeddings.poet import PoETModel +from openprotein.embeddings.poet2 import PoET2Model + + +def stored_prompt_inputs(poet: PoETModel, poet2: PoET2Model, prompt: Prompt) -> None: + poet.embed([b"MKT"], prompt=prompt) + poet.score([b"MKT"], prompt=prompt) + poet.generate(prompt=prompt) + poet2.embed([b"MKT"], prompt=prompt) + poet2.score([b"MKT"], prompt=prompt) + poet2.generate(prompt=prompt) diff --git a/tests/fold/test_common.py b/tests/fold/test_common.py index 78e6481..01f4029 100644 --- a/tests/fold/test_common.py +++ b/tests/fold/test_common.py @@ -1,7 +1,54 @@ +import inspect from unittest.mock import MagicMock -from openprotein.fold.common import normalize_inputs, serialize_input +import numpy as np +import pytest + +import openprotein.common.residue_constants as RC +from openprotein.align import AlignAPI +from openprotein.base import APISession +from openprotein.codecs import MSA as DecodedMSA +from openprotein.embeddings import api as embeddings_api +from openprotein.fold.common import ( + _msa_id_of, + normalize_inputs, + normalize_templates, + serialize_input, +) from openprotein.molecules import Complex, Ligand, Protein +from openprotein.molecules.template import Template + + +def test_an_unknown_msa_type_names_the_accepted_and_the_given_types(): + with pytest.raises( + TypeError, + match=r"openprotein\.data\.MSA.*not openprotein\.codecs\.msa\.MSA", + ): + _msa_id_of(object.__new__(DecodedMSA)) + + +def test_serializing_an_msa_id_reads_no_seed(): + session = MagicMock(spec=APISession) + session.align = MagicMock(spec=AlignAPI) + protein = Protein(sequence="MKT") + protein.msa = "e0b1c3d4-0000-4000-8000-000000000001" + + serialize_input(session, [Complex({"A": protein})], needs_msa=True) + + session.align.get_seed.assert_not_called() + + +def test_the_embeddings_stream_documents_the_sdk_error(): + stream = embeddings_api.request_get_embeddings_stream + assert "openprotein.errors.HTTPError" in (stream.__doc__ or "") + assert "raise_for_status" not in inspect.getsource(stream) + + +def _protein_with_structure() -> Protein: + """Build a Protein carrying coordinates so Template's validation accepts it.""" + amino_acids = list(RC.restype_1to3.keys()) + ["X"] + p = Protein(sequence="".join(amino_acids[i] for i in range(6))) + return p._set_coordinates(np.random.random(p.coordinates.shape).astype(np.float32)) def test_normalize_inputs_splits_colon_delimited_into_one_complex(): @@ -32,7 +79,104 @@ def test_normalize_inputs_single_sequence_is_single_chain_complex(): def test_normalize_inputs_preserves_order_and_resets_ids_per_complex(): complexes = normalize_inputs(["AAAA", "BBBB:CCCC", Protein(b"DDDD")]) - assert [list(c.get_chains().keys()) for c in complexes] == [["A"], ["A", "B"], ["A"]] + assert [list(c.get_chains().keys()) for c in complexes] == [ + ["A"], + ["A", "B"], + ["A"], + ] + + +def test_normalize_inputs_lone_string_is_one_complex(): + [complex] = normalize_inputs("AAAA:BBBB") + assert [chain.sequence.decode() for chain in complex.get_chains().values()] == [ + "AAAA", + "BBBB", + ] + + +def test_normalize_inputs_lone_bytes_is_one_complex(): + [complex] = normalize_inputs(b"AAAA") + assert [chain.sequence.decode() for chain in complex.get_chains().values()] == [ + "AAAA" + ] + + +def test_normalize_inputs_lone_protein_is_single_chain_complex(): + [complex] = normalize_inputs(Protein(b"DDDD")) + assert list(complex.get_chains().keys()) == ["A"] + + +def test_normalize_inputs_lone_complex_passes_through(): + complex = Complex({"A": Protein(b"AAAA"), "B": Protein(b"BBBB")}) + assert normalize_inputs(complex) == [complex] + + +@pytest.mark.parametrize("chain_id", ["A", "B"]) +def test_a_chain_with_different_templates_across_a_batch_is_refused(chain_id): + first = Complex({"A": Protein("MKT")}) + later_chains = {"A": Protein("MKT")} + later_chains[chain_id] = Protein("MKT").set_templates([_protein_with_structure()]) + later = Complex(later_chains) + + with pytest.raises(ValueError, match="same chain.*same templates"): + normalize_templates(MagicMock(), [first, later]) + + +@pytest.mark.parametrize( + ("first_ids", "later_ids", "templated_id"), + [("A", "B", "A"), ("AB", "A", "B")], +) +def test_a_shared_template_requires_its_chain_in_every_complex( + first_ids, later_ids, templated_id +): + first = Complex({chain: Protein("MKT") for chain in first_ids}) + first.get_protein(templated_id).templates = [_protein_with_structure()] + later = Complex({chain: Protein("MKT") for chain in later_ids}) + + with pytest.raises(ValueError, match="Template maps.*does not exist"): + normalize_templates(MagicMock(), [first, later]) + + +def test_shared_templates_allow_additional_untemplated_chains(): + template = _protein_with_structure() + first = Complex({"A": Protein("MKT").set_templates([template])}) + later = Complex({"A": Protein("MKT").set_templates([template]), "B": Protein("AC")}) + + [normalized] = normalize_templates(MagicMock(), [first, later]) + + assert normalized.template is template + assert normalized.mapping == "A" + + +def test_automatic_template_mapping_allows_different_chain_ids(): + template = Template(template=_protein_with_structure()) + first = Complex({"A": Protein("MKT").set_templates([template])}) + later = Complex({"B": Protein("AC")}) + + assert normalize_templates(MagicMock(), [first, later]) == [template] + + +def test_normalize_templates_validates_lone_complex_against_its_own_chains(): + """A lone Complex is one target, so a chain mapping resolves against its chains.""" + session = MagicMock() + target = Complex({"A": Protein(b"AAAA"), "B": Protein(b"BBBB")}) + template = Template(template=_protein_with_structure(), mapping="B") + assert normalize_templates(session, target, [template]) == [template] + + +def test_normalize_templates_maps_a_template_to_chain_a_of_a_lone_protein(): + """A lone protein is chain A, so a template mapped to ``A`` is valid.""" + session = MagicMock() + template = Template(template=_protein_with_structure(), mapping="A") + assert normalize_templates(session, Protein(b"AAAA"), [template]) == [template] + + +def test_normalize_templates_refuses_another_chain_of_a_lone_protein(): + """A lone protein has no chain but ``A``.""" + session = MagicMock() + template = Template(template=_protein_with_structure(), mapping="B") + with pytest.raises(ValueError, match="does not exist in the target"): + normalize_templates(session, Protein(b"AAAA"), [template]) def test_serialize_input_emits_scalar_id_per_chain(): diff --git a/tests/fold/test_fold.py b/tests/fold/test_fold.py index aae3690..e1f8a74 100644 --- a/tests/fold/test_fold.py +++ b/tests/fold/test_fold.py @@ -12,7 +12,6 @@ def test_fold_api_init(mock_session: MagicMock): - """Test FoldAPI initialization by mocking the underlying session call.""" # Configure the mock to return a list of models first, then model metadata mock_session.get.return_value.json.side_effect = [ ["esmfold", "alphafold2", "boltz-1", "protenix"], # First call for list_models @@ -35,9 +34,6 @@ def test_fold_api_init(mock_session: MagicMock): def test_get_results(mock_session: MagicMock): - """ - Test FoldAPI.get_results integration. - """ # Configure mock responses for the sequence of API calls try: mock_session.get.return_value.json.side_effect = [ diff --git a/tests/fold/test_fold_api.py b/tests/fold/test_fold_api.py index 49edb0f..c6b9241 100644 --- a/tests/fold/test_fold_api.py +++ b/tests/fold/test_fold_api.py @@ -1,22 +1,18 @@ """Test the api for the fold domain.""" import io -from unittest.mock import MagicMock, Mock +from unittest.mock import MagicMock import numpy as np import pytest -from requests import Response -from openprotein.base import APISession from openprotein.common.model_metadata import ModelMetadata -from openprotein.errors import HTTPError from openprotein.fold import api from openprotein.fold.schemas import FoldJob, FoldMetadata from openprotein.jobs.schemas import JobType def test_fold_models_list_get(mock_session: MagicMock): - """Test fold_models_list_get.""" mock_session.get.return_value.json.return_value = ["model1", "model2"] result = api.fold_models_list_get(mock_session) mock_session.get.assert_called_once_with("v1/fold/models") @@ -24,7 +20,6 @@ def test_fold_models_list_get(mock_session: MagicMock): def test_fold_model_get(mock_session: MagicMock): - """Test fold_model_get.""" mock_session.get.return_value.json.return_value = { "model_id": "model1", "description": {"summary": "A test model"}, @@ -40,7 +35,6 @@ def test_fold_model_get(mock_session: MagicMock): def test_fold_get(mock_session: MagicMock): - """Test fold_get.""" mock_session.get.return_value.json.return_value = { "job_id": "job1", "model_id": "model1", @@ -52,7 +46,6 @@ def test_fold_get(mock_session: MagicMock): def test_fold_get_sequences(mock_session: MagicMock): - """Test fold_get_sequences.""" mock_session.get.return_value.json.return_value = ["seq1".encode(), "seq2".encode()] result = api.fold_get_sequences(mock_session, "job1") mock_session.get.assert_called_once_with("v1/fold/job1/sequences") @@ -60,7 +53,6 @@ def test_fold_get_sequences(mock_session: MagicMock): def test_fold_get_sequence_result(mock_session: MagicMock): - """Test fold_get_sequence_result.""" mock_session.get.return_value.content = b"pdb_content" result = api.fold_get_sequence_result(mock_session, "job1", "seq1") mock_session.get.assert_called_once_with( @@ -118,14 +110,11 @@ def test_fold_get_batch_extra_result_json(mock_session: MagicMock): def test_fold_get_batch_extra_result_rejects_unknown_key(mock_session: MagicMock): """Unknown keys are rejected before the HTTP call.""" with pytest.raises(ValueError, match="Unexpected key"): - api.fold_get_batch_extra_result( - mock_session, "job1", "unknown" - ) # ty: ignore[no-matching-overload] + api.fold_get_batch_extra_result(mock_session, "job1", "unknown") # ty: ignore[no-matching-overload] mock_session.get.assert_not_called() def test_fold_models_post(mock_session: MagicMock): - """Test fold_models_post.""" mock_session.post.return_value.json.return_value = { "job_id": "job1", "status": "PENDING", diff --git a/tests/fold/test_fold_common.py b/tests/fold/test_fold_common.py index 010beea..16a3fa6 100644 --- a/tests/fold/test_fold_common.py +++ b/tests/fold/test_fold_common.py @@ -4,7 +4,7 @@ import numpy as np -import openprotein.common.residue_contants as RC +import openprotein.common.residue_constants as RC from openprotein.fold.common import resolve_templates from openprotein.molecules.protein import Protein from openprotein.molecules.template import Template diff --git a/tests/fold/test_fold_confidence.py b/tests/fold/test_fold_confidence.py new file mode 100644 index 0000000..4f73439 --- /dev/null +++ b/tests/fold/test_fold_confidence.py @@ -0,0 +1,230 @@ +import json + +import pytest +from pydantic import TypeAdapter, ValidationError + +from openprotein.codecs import json_utf8_v1 +from openprotein.fold import FoldConfidence + +NULL_SCORES = { + "complex_iplddt": None, + "complex_pde": None, + "complex_ipde": None, + "protein_iptm": None, + "ligand_iptm": None, + "chain_iptm": None, + "has_clash": None, +} + + +def two_chain(**overrides): + payload = { + "chain_ids": ["A", "B"], + "ranking_score": 0.81, + "ptm": 0.72, + "iptm": 0.64, + "complex_plddt": 83.5, + "chain_plddt": [85.0, 80.25], + "chain_ptm": [0.8, None], + "chain_pair_iptm": [[0.8, 0.6], [0.6, None]], + "ipae": 7.5, + **NULL_SCORES, + } + payload.update(overrides) + return payload + + +def one_chain(**overrides): + payload = { + "chain_ids": ["A"], + "ranking_score": None, + "ptm": None, + "iptm": None, + "complex_plddt": 91.0, + "chain_plddt": [91.0], + "chain_ptm": [None], + "chain_pair_iptm": [[None]], + "ipae": None, + **NULL_SCORES, + } + payload.update(overrides) + return payload + + +def test_null_scores_validate(): + confidence = FoldConfidence.model_validate(two_chain()) + assert confidence.chain_ids == ["A", "B"] + assert confidence.chain_pair_iptm == [[0.8, 0.6], [0.6, None]] + assert confidence.complex_pde is None + + +def test_single_chain_with_null_scores_validates(): + assert FoldConfidence.model_validate(one_chain()).ipae is None + + +def test_every_score_validates(): + confidence = FoldConfidence.model_validate( + two_chain( + complex_iplddt=70.0, + complex_pde=1.5, + complex_ipde=4.0, + protein_iptm=0.6, + ligand_iptm=0.3, + chain_iptm=[0.6, 0.6], + has_clash=False, + ) + ) + assert confidence.has_clash is False + assert confidence.chain_iptm == [0.6, 0.6] + + +def test_list_from_json_utf8_v1_validates(): + data = json_utf8_v1.encode([two_chain(), two_chain(ranking_score=-99.2)]) + samples = [FoldConfidence.model_validate(s) for s in json_utf8_v1.decode(data)] + assert [s.ranking_score for s in samples] == [0.81, -99.2] + + +SCORES = { + "complex_iplddt": 70.0, + "complex_pde": 1.5, + "complex_ipde": 4.0, + "protein_iptm": 0.6, + "ligand_iptm": 0.3, + "chain_iptm": [0.6, 0.6], + "has_clash": False, +} + + +@pytest.mark.parametrize( + "payload", + [ + two_chain(), + two_chain(complex_pde=1.5, has_clash=True), + two_chain(**SCORES), + one_chain(), + ], + ids=["null-scores", "some-scores", "every-score", "one-chain"], +) +def test_dump_re_validates_and_keeps_every_key(payload): + confidence = FoldConfidence.model_validate(payload) + assert confidence.model_dump() == payload + assert json.loads(confidence.model_dump_json()) == payload + assert FoldConfidence.model_validate(confidence.model_dump()) == confidence + assert ( + FoldConfidence.model_validate_json(confidence.model_dump_json()) == confidence + ) + + +def test_dump_keeps_null_keys(): + dumped = FoldConfidence.model_validate(one_chain()).model_dump() + for key in ("ranking_score", "ptm", "iptm", "ipae", *NULL_SCORES): + assert dumped[key] is None + + +def test_list_dump_re_validates(): + samples = [ + FoldConfidence.model_validate(two_chain()), + FoldConfidence.model_validate(two_chain(complex_pde=1.5)), + ] + adapter = TypeAdapter(list[FoldConfidence]) + for dumped in ( + adapter.dump_python(samples), + json.loads(adapter.dump_json(samples)), + ): + assert dumped == [two_chain(), two_chain(complex_pde=1.5)] + assert adapter.validate_python(dumped) == samples + + +@pytest.mark.parametrize("key", list(FoldConfidence.model_fields)) +def test_every_key_is_required(key): + payload = two_chain() + del payload[key] + with pytest.raises(ValidationError, match=key): + FoldConfidence.model_validate(payload) + + +def test_unknown_keys_are_rejected(): + with pytest.raises(ValidationError, match="chains_ptm"): + FoldConfidence.model_validate(two_chain(chains_ptm={"0": 0.8})) + + +@pytest.mark.parametrize( + "overrides", + [ + {"ptm": float("nan")}, + {"ranking_score": float("inf")}, + {"chain_plddt": [85.0, float("nan")]}, + {"chain_pair_iptm": [[0.8, float("nan")], [0.6, None]]}, + {"ipae": float("nan")}, + ], +) +def test_non_finite_numbers_are_rejected(overrides): + with pytest.raises(ValidationError): + FoldConfidence.model_validate(two_chain(**overrides)) + + +def test_nan_in_json_is_rejected(): + with pytest.raises(ValidationError): + FoldConfidence.model_validate_json(json.dumps(two_chain(ptm=float("nan")))) + + +@pytest.mark.parametrize( + "overrides", + [ + {"ptm": 1.2}, + {"iptm": -0.1}, + {"complex_plddt": -0.5}, + {"complex_plddt": 100.5}, + {"chain_plddt": [85.0, 101.0]}, + {"chain_ptm": [1.5, None]}, + {"chain_pair_iptm": [[0.8, 1.1], [0.6, None]]}, + {"ipae": -1.0}, + {"complex_iplddt": 120.0}, + {"complex_pde": -0.5}, + {"ligand_iptm": 2.0}, + {"chain_iptm": [0.5, -0.5]}, + ], +) +def test_out_of_scale_values_are_rejected(overrides): + with pytest.raises(ValidationError): + FoldConfidence.model_validate(two_chain(**overrides)) + + +@pytest.mark.parametrize( + "overrides", + [ + {"chain_plddt": [85.0]}, + {"chain_ptm": [0.8, None, 0.7]}, + {"chain_iptm": [0.6]}, + {"chain_pair_iptm": [[0.8, 0.6]]}, + {"chain_pair_iptm": [[0.8, 0.6], [0.6]]}, + ], +) +def test_chain_lists_must_match_chain_ids(overrides): + with pytest.raises(ValidationError, match="chain_ids"): + FoldConfidence.model_validate(two_chain(**overrides)) + + +@pytest.mark.parametrize("chain_ids", [[], ["A", "A"]], ids=["empty", "duplicate"]) +def test_chain_ids_are_non_empty_and_unique(chain_ids): + with pytest.raises(ValidationError, match="chain_ids"): + FoldConfidence.model_validate(two_chain(chain_ids=chain_ids)) + + +@pytest.mark.parametrize("key, value", [("iptm", 0.5), ("ipae", 3.0)]) +def test_interface_scores_are_null_for_one_chain(key, value): + with pytest.raises(ValidationError, match=key): + FoldConfidence.model_validate(one_chain(**{key: value})) + + +@pytest.mark.parametrize( + "overrides", + [ + {"has_clash": 0}, + {"chain_ids": ["A", 2]}, + {"ptm": "0.5"}, + ], +) +def test_values_are_not_coerced(overrides): + with pytest.raises(ValidationError): + FoldConfidence.model_validate(two_chain(**overrides)) diff --git a/tests/fold/test_fold_models.py b/tests/fold/test_fold_models.py index 5abfe46..3386f14 100644 --- a/tests/fold/test_fold_models.py +++ b/tests/fold/test_fold_models.py @@ -1,31 +1,36 @@ """Test the models for the fold domain.""" +import typing from datetime import datetime, timezone from unittest.mock import MagicMock, patch +import numpy as np import pytest +from openprotein.align import AlignAPI from openprotein.base import APISession from openprotein.common.model_metadata import ModelDescription, ModelMetadata from openprotein.fold.alphafold2 import AlphaFold2Model +from openprotein.fold.boltz import Boltz1Model, Boltz1xModel, Boltz2Model from openprotein.fold.esmfold import ESMFoldModel from openprotein.fold.esmfold2 import ESMFold2FastModel, ESMFold2Model from openprotein.fold.future import FoldResultFuture from openprotein.fold.models import FoldModel +from openprotein.fold.opendde import OpenDDEAbagModel, OpenDDEModel from openprotein.fold.protenix import ProtenixModel, ProtenixV2Model +from openprotein.fold.rosettafold3 import RosettaFold3Model from openprotein.fold.schemas import FoldJob, FoldMetadata from openprotein.jobs.schemas import JobStatus, JobType +from openprotein.molecules import Complex, Ligand, Protein from openprotein.prompt import PromptAPI @pytest.fixture def mock_session(): - """Fixture for a mocked APISession.""" return MagicMock(spec=APISession) def test_fold_model_create(mock_session): - """Test FoldModel.create.""" # Test creating a known model model = FoldModel.create(mock_session, "esmfold") assert isinstance(model, ESMFoldModel) @@ -63,7 +68,6 @@ def test_fold_model_create(mock_session): @patch("openprotein.fold.api.fold_model_get") def test_fold_model_get_metadata(mock_fold_model_get, mock_session): - """Test FoldModel.get_metadata and caching.""" mock_metadata = ModelMetadata( model_id="esmfold", description=ModelDescription(summary="A test model"), @@ -91,7 +95,6 @@ def test_fold_model_get_metadata(mock_fold_model_get, mock_session): @patch("openprotein.fold.api.fold_models_post") @patch("openprotein.fold.api.fold_get") def test_fold_model_fold(mock_fold_get, mock_fold_models_post, mock_session): - """Test FoldModel.fold.""" mock_job = FoldJob( job_id="job123", status=JobStatus.PENDING, @@ -121,7 +124,6 @@ def test_fold_model_fold(mock_fold_get, mock_fold_models_post, mock_session): @patch("openprotein.fold.api.fold_models_post") @patch("openprotein.fold.api.fold_get") def test_protenix_model_fold(mock_fold_get, mock_fold_models_post, mock_session): - """Test ProtenixModel.fold.""" mock_job = FoldJob( job_id="job123", status=JobStatus.PENDING, @@ -148,6 +150,7 @@ def test_protenix_model_fold(mock_fold_get, mock_fold_models_post, mock_session) num_recycles=10, num_steps=200, templates=None, + seed=None, ) assert isinstance(future, FoldResultFuture) assert future.job.job_id == "job123" @@ -156,7 +159,6 @@ def test_protenix_model_fold(mock_fold_get, mock_fold_models_post, mock_session) @patch("openprotein.fold.api.fold_models_post") @patch("openprotein.fold.api.fold_get") def test_protenix_v2_model_fold(mock_fold_get, mock_fold_models_post, mock_session): - """Test ProtenixV2Model.fold posts the protenix-v2 model_id.""" mock_job = FoldJob( job_id="job123", status=JobStatus.PENDING, @@ -183,6 +185,7 @@ def test_protenix_v2_model_fold(mock_fold_get, mock_fold_models_post, mock_sessi num_recycles=10, num_steps=200, templates=None, + seed=None, ) assert isinstance(future, FoldResultFuture) assert future.job.job_id == "job123" @@ -191,7 +194,6 @@ def test_protenix_v2_model_fold(mock_fold_get, mock_fold_models_post, mock_sessi @patch("openprotein.fold.api.fold_models_post") @patch("openprotein.fold.api.fold_get") def test_esmfold2_model_fold(mock_fold_get, mock_fold_models_post, mock_session): - """Test ESMFold2Model.fold.""" mock_job = FoldJob( job_id="job123", status=JobStatus.PENDING, @@ -224,7 +226,6 @@ def test_esmfold2_model_fold(mock_fold_get, mock_fold_models_post, mock_session) @patch("openprotein.fold.api.fold_models_post") @patch("openprotein.fold.api.fold_get") def test_esmfold2_fast_model_fold(mock_fold_get, mock_fold_models_post, mock_session): - """Test ESMFold2FastModel.fold.""" mock_job = FoldJob( job_id="job123", status=JobStatus.PENDING, @@ -287,8 +288,9 @@ def test_esmfold2_fast_accepts_single_sequence_mode(mock_session): """ESMFold2-Fast must accept single_sequence_mode without raising.""" from openprotein.molecules import Complex, Protein - with patch("openprotein.fold.api.fold_models_post") as mock_post, patch( - "openprotein.fold.api.fold_get" + with ( + patch("openprotein.fold.api.fold_models_post") as mock_post, + patch("openprotein.fold.api.fold_get"), ): mock_post.return_value = FoldJob( job_id="job123", @@ -308,7 +310,6 @@ def test_esmfold2_fast_accepts_single_sequence_mode(mock_session): @pytest.mark.parametrize("model_id", ["protenix", "protenix-v2"]) def test_fold_result_future_get_confidence_supports_protenix(model_id): - """Test FoldResultFuture.get_confidence for Protenix and Protenix-v2.""" future = object.__new__(FoldResultFuture) future._metadata = FoldMetadata(job_id="job123", model_id=model_id) future.get = MagicMock(return_value=[[{"confidence_score": 0.5}]]) @@ -358,7 +359,7 @@ def test_fold_result_future_get_confidence_supports_esmfold2(model_id): assert len(result) == 1 assert isinstance(result[0], list) assert len(result[0]) == 1 - assert isinstance(result[0][0], dict) or isinstance(result[0][0], ESMFold2Confidence) + assert isinstance(result[0][0], (dict, ESMFold2Confidence)) @pytest.mark.parametrize( @@ -369,7 +370,9 @@ def test_fold_result_future_get_confidence_supports_esmfold2(model_id): "param", ["num_recycles", "num_steps", "diffusion_samples"], ) -def test_esmfold2_rejects_runtime_param_below_one(mock_session, model_cls, model_id, param): +def test_esmfold2_rejects_runtime_param_below_one( + mock_session, model_cls, model_id, param +): """Runtime params must be >= 1; the SDK rejects bad values before the request.""" model = model_cls(session=mock_session, model_id=model_id) with pytest.raises(ValueError, match=param): @@ -415,3 +418,389 @@ def test_fold_result_future_affinity_rejects_non_boltz2(model_id): future.get_affinity() with pytest.raises(AttributeError, match="boltz-2"): future.get_affinity_batch() + + +@pytest.mark.parametrize( + ("model_id", "expected"), + [("opendde", OpenDDEModel), ("opendde-abag", OpenDDEAbagModel)], +) +def test_fold_model_create_resolves_opendde_variants(mock_session, model_id, expected): + """Each variant resolves to its own class and keeps its own model id.""" + model = FoldModel.create(mock_session, model_id) + + assert type(model) is expected + assert model.id == model_id + + +@patch("openprotein.fold.api.fold_models_post") +@patch("openprotein.fold.api.fold_get") +@pytest.mark.parametrize( + ("model_id", "model_class"), + [("opendde", OpenDDEModel), ("opendde-abag", OpenDDEAbagModel)], +) +def test_opendde_model_fold( + mock_fold_get, mock_fold_models_post, mock_session, model_id, model_class +): + """The posted body carries the knobs the service actually forwards. + + The body carries the sequences, diffusion samples, recycles, steps and + seed; templates are not part of it. + """ + mock_fold_models_post.return_value = FoldJob( + job_id="job123", + status=JobStatus.PENDING, + job_type=JobType.embeddings_fold, + created_date=datetime.now(timezone.utc), + ) + mock_fold_get.return_value = FoldMetadata(job_id="job123", model_id=model_id) + mock_session.prompt = MagicMock(spec=PromptAPI) + + model = model_class(session=mock_session, model_id=model_id) + future = model.fold(sequences=["SEQ"]) + + mock_fold_models_post.assert_called_once_with( + session=mock_session, + model_id=model_id, + sequences=[[{"protein": {"id": "A", "sequence": "SEQ", "msa_id": None}}]], + diffusion_samples=1, + num_recycles=10, + num_steps=200, + seed=None, + ) + assert isinstance(future, FoldResultFuture) + assert future.job.job_id == "job123" + + +@pytest.mark.parametrize("model_id", ["opendde", "opendde-abag"]) +def test_opendde_confidence_parses_the_fields_the_model_emits(model_id): + """Guard the confidence schema against what the model actually emits. + + chain_pair_plddt is the field OpenDDE emits that Protenix does not, so + reusing ProtenixConfidence would silently drop it. + """ + from openprotein.fold.opendde import OpenDDEConfidence + + summary = { + "ranking_score": 0.82, + "ptm": 0.7, + "iptm": 0.85, + "plddt": 91.2, + "gpde": 1.1, + "has_clash": 0.0, + "num_recycles": 10, + "disorder": 0.0, + "chain_ptm": [0.7], + "chain_iptm": [0.85], + "chain_plddt": [91.2], + "chain_gpde": [1.1], + "chain_pair_iptm": [[0.85]], + "chain_pair_iptm_global": [[0.85]], + "chain_pair_gpde": [[1.1]], + "chain_pair_plddt": [[91.2]], + } + future = object.__new__(FoldResultFuture) + future._metadata = FoldMetadata(job_id="job123", model_id=model_id) + future.get = MagicMock(return_value=[[summary]]) + + parsed = OpenDDEConfidence.model_validate(summary) + + assert parsed.chain_pair_plddt == [[91.2]] + + # Scores the schema does not declare are kept, not rejected. + extended = OpenDDEConfidence.model_validate( + summary | {"pb_ranking_score": 0.7, "has_vdw_pl_clash": 0.0} + ) + assert extended.pb_ranking_score == 0.7 + + +@pytest.mark.parametrize("model_id", ["opendde", "opendde-abag"]) +def test_opendde_exposes_its_outputs(model_id): + """pae, pde, plddt and confidence are gated per model in FoldResultFuture. + + The service publishes exactly these four plus the mmCIF. ipae is not + among them, so asking for it has to raise rather than fail at fetch time. + """ + future = object.__new__(FoldResultFuture) + future._metadata = FoldMetadata(job_id="job123", model_id=model_id) + future.get = MagicMock(return_value=[]) + + for key in ("pae", "pde", "plddt", "confidence"): + getattr(future, f"get_{key}")() + + with pytest.raises(AttributeError, match="ipae not supported"): + future.get_ipae() + + +MSA_ID = "3f1c2a7e-9b4d-4e2a-8c1f-0d5e6a7b8c9d" + + +@pytest.fixture +def generic_fold(mock_session): + from openprotein.fold.fold import FoldAPI + + job = FoldJob( + job_id="job123", + status=JobStatus.PENDING, + job_type=JobType.embeddings_fold, + created_date=datetime.now(timezone.utc), + ) + metadata = FoldMetadata(job_id="job123", model_id="example-fold-v1") + with ( + patch("openprotein.fold.api.fold_models_post", return_value=job) as post, + patch("openprotein.fold.api.fold_get", return_value=metadata), + ): + model = FoldAPI(session=mock_session).get_model("example-fold-v1") + assert type(model) is FoldModel + yield model, post + + +class TestGenericFoldModel: + """A listed model without its own class folds through ``FoldModel``.""" + + def test_the_sequences_it_folds_are_sent(self, generic_fold): + model, post = generic_fold + + future = model.fold(["MKT", "AC:DE"], num_recycles=3) + + assert post.call_args.kwargs["sequences"] == [ + [{"protein": {"id": "A", "sequence": "MKT"}}], + [ + {"protein": {"id": "A", "sequence": "AC"}}, + {"protein": {"id": "B", "sequence": "DE"}}, + ], + ] + assert post.call_args.kwargs["num_recycles"] == 3 + assert [c.get_proteins()["A"].sequence for c in future.complexes] == [ + b"MKT", + b"AC", + ] + + @pytest.mark.parametrize( + ("msa", "msa_id"), + [(MSA_ID, MSA_ID), (Protein.single_sequence_mode, None)], + ) + def test_an_attached_msa_sends_an_msa_id_for_every_protein( + self, generic_fold, mock_session, msa, msa_id + ): + model, post = generic_fold + mock_session.align = MagicMock(spec=AlignAPI) + mock_session.align.get_seed.return_value = "MKT" + protein = Protein(sequence="MKT") + protein.msa = msa + + model.fold([protein, "AC"]) + + assert post.call_args.kwargs["sequences"] == [ + [{"protein": {"id": "A", "sequence": "MKT", "msa_id": msa_id}}], + [{"protein": {"id": "A", "sequence": "AC", "msa_id": None}}], + ] + + def test_a_protein_without_an_msa_beside_one_with_an_msa_is_refused( + self, generic_fold + ): + model, post = generic_fold + aligned = Protein(sequence="MKT") + aligned.msa = Protein.single_sequence_mode + + with pytest.raises(ValueError, match="`.msa` set"): + model.fold([aligned, Protein(sequence="AC")]) + post.assert_not_called() + + def test_an_empty_list_sends_no_sequences(self, generic_fold): + model, post = generic_fold + references = [{"job_id": "job456", "prompt_id": "prompt789"}] + + model.fold([], reference_structures=references) + + assert post.call_args.kwargs["sequences"] is None + assert post.call_args.kwargs["reference_structures"] == references + + +class TestFoldModelHierarchy: + def test_every_model_still_resolves(self, mock_session): + expected = { + "boltz-2": "Boltz2Model", + "boltz-1x": "Boltz1xModel", + "esmfold": "ESMFoldModel", + "alphafold2": "AlphaFold2Model", + "opendde-abag": "OpenDDEAbagModel", + } + for model_id, class_name in expected.items(): + model = FoldModel.create( + session=mock_session, model_id=model_id, default=FoldModel + ) + assert type(model).__name__ == class_name, model_id + + def test_fold_model_create_resolves_grandchildren(self, mock_session): + model = FoldModel.create( + session=mock_session, model_id="boltz-2", default=FoldModel + ) + assert type(model).__name__ == "Boltz2Model" + + def test_fold_api_lookups_are_typed_as_fold_model(self): + from openprotein.fold.fold import FoldAPI + + hints = typing.get_type_hints(FoldAPI.get_model) + assert hints["return"] is FoldModel + assert typing.get_type_hints(FoldAPI.list_models)["return"] == list[FoldModel] + + def test_bare_fold_model_reports_its_id(self, mock_session): + from openprotein.fold.models import FoldModel + + assert FoldModel(session=mock_session, model_id="unknown").model_id == "unknown" + + +@patch("openprotein.fold.api.fold_models_post") +@patch("openprotein.fold.api.fold_get") +def test_protenix_model_fold_sends_the_seed( + mock_fold_get, mock_fold_models_post, mock_session +): + mock_fold_models_post.return_value = FoldJob( + job_id="job123", + status=JobStatus.PENDING, + job_type=JobType.embeddings_fold, + created_date=datetime.now(timezone.utc), + ) + mock_fold_get.return_value = FoldMetadata(job_id="job123", model_id="protenix-v2") + mock_session.prompt = MagicMock(spec=PromptAPI) + + model = ProtenixV2Model(session=mock_session, model_id="protenix-v2") + model.fold(sequences=["SEQ"], seed=42) + + assert mock_fold_models_post.call_args.kwargs["seed"] == 42 + + +@patch("openprotein.fold.api.fold_models_post") +@patch("openprotein.fold.api.fold_get") +@pytest.mark.parametrize( + ("model_id", "model_class"), + [ + ("boltz-1", Boltz1Model), + ("boltz-1x", Boltz1xModel), + ("boltz-2", Boltz2Model), + ("opendde", OpenDDEModel), + ("opendde-abag", OpenDDEAbagModel), + ("rosettafold-3", RosettaFold3Model), + ], +) +def test_fold_sends_the_seed( + mock_fold_get, mock_fold_models_post, mock_session, model_id, model_class +): + mock_fold_models_post.return_value = FoldJob( + job_id="job123", + status=JobStatus.PENDING, + job_type=JobType.embeddings_fold, + created_date=datetime.now(timezone.utc), + ) + mock_fold_get.return_value = FoldMetadata(job_id="job123", model_id=model_id) + mock_session.prompt = MagicMock(spec=PromptAPI) + + model = model_class(session=mock_session, model_id=model_id) + model.fold(sequences=["SEQ"], seed=42) + + assert mock_fold_models_post.call_args.kwargs["seed"] == 42 + + +@patch("openprotein.fold.api.fold_models_post") +@patch("openprotein.fold.api.fold_get") +@pytest.mark.parametrize( + ("model_id", "model_class"), + [("boltz-2", Boltz2Model), ("protenix", ProtenixModel)], +) +def test_a_colon_string_folds_as_one_multichain_complex( + mock_fold_get, mock_fold_models_post, mock_session, model_id, model_class +): + mock_fold_models_post.return_value = FoldJob( + job_id="job123", + status=JobStatus.PENDING, + job_type=JobType.embeddings_fold, + created_date=datetime.now(timezone.utc), + ) + mock_fold_get.return_value = FoldMetadata(job_id="job123", model_id=model_id) + mock_session.prompt = MagicMock(spec=PromptAPI) + + model_class(session=mock_session, model_id=model_id).fold("MKT:AC") + + assert mock_fold_models_post.call_args.kwargs["sequences"] == [ + [ + {"protein": {"id": "A", "sequence": "MKT", "msa_id": None}}, + {"protein": {"id": "B", "sequence": "AC", "msa_id": None}}, + ] + ] + + +@patch("openprotein.fold.api.fold_models_post") +@patch("openprotein.fold.api.fold_get") +def test_a_later_complex_with_a_chain_the_first_lacks_folds( + mock_fold_get, mock_fold_models_post, mock_session +): + mock_fold_models_post.return_value = FoldJob( + job_id="job123", + status=JobStatus.PENDING, + job_type=JobType.embeddings_fold, + created_date=datetime.now(timezone.utc), + ) + mock_fold_get.return_value = FoldMetadata(job_id="job123", model_id="boltz-2") + mock_session.prompt = MagicMock(spec=PromptAPI) + + Boltz2Model(session=mock_session, model_id="boltz-2").fold(["MKT", "MKT:AC"]) + + assert [ + len(complex) for complex in mock_fold_models_post.call_args.kwargs["sequences"] + ] == [1, 2] + + +@patch("openprotein.fold.api.fold_models_post") +@patch("openprotein.fold.api.fold_get") +def test_shared_template_targets_are_checked_before_upload_or_submission( + mock_fold_get, mock_fold_models_post, mock_session +): + mock_fold_models_post.return_value = FoldJob( + job_id="job123", + status=JobStatus.PENDING, + job_type=JobType.embeddings_fold, + created_date=datetime.now(timezone.utc), + ) + mock_fold_get.return_value = FoldMetadata(job_id="job123", model_id="boltz-2") + mock_session.prompt = PromptAPI(mock_session) + template = Protein("ARNDCQ") + template = template._set_coordinates( + np.zeros(template.coordinates.shape, dtype=np.float32) + ) + first = Protein("ARNDCQ").set_msa(Protein.single_sequence_mode) + first.templates = [template] + later = Protein("MKT").set_msa(Protein.single_sequence_mode) + + with patch.object( + mock_session.prompt, "_resolve_query", return_value="query-id" + ) as upload: + with pytest.raises(ValueError, match="Template maps.*does not exist"): + Boltz2Model(session=mock_session, model_id="boltz-2").fold( + [Complex({"A": first}), Complex({"B": later})] + ) + upload.assert_not_called() + mock_fold_models_post.assert_not_called() + + +@patch("openprotein.fold.api.fold_models_post") +@patch("openprotein.fold.api.fold_get") +def test_boltz2_takes_an_affinity_binder_in_a_lone_complex( + mock_fold_get, mock_fold_models_post, mock_session +): + mock_fold_models_post.return_value = FoldJob( + job_id="job123", + status=JobStatus.PENDING, + job_type=JobType.embeddings_fold, + created_date=datetime.now(timezone.utc), + ) + mock_fold_get.return_value = FoldMetadata(job_id="job123", model_id="boltz-2") + mock_session.prompt = MagicMock(spec=PromptAPI) + protein = Protein(sequence="MKT") + protein.msa = Protein.single_sequence_mode + properties = [{"affinity": {"binder": "L"}}] + + Boltz2Model(session=mock_session, model_id="boltz-2").fold( + Complex({"A": protein, "L": Ligand(ccd="ATP")}), properties=properties + ) + + assert mock_fold_models_post.call_args.kwargs["properties"] == properties diff --git a/tests/fold/test_fold_namespace.py b/tests/fold/test_fold_namespace.py new file mode 100644 index 0000000..810b9ca --- /dev/null +++ b/tests/fold/test_fold_namespace.py @@ -0,0 +1,37 @@ +from unittest.mock import patch + +import openprotein.fold as fold_package +from openprotein.fold.esmfold import ESMFoldModel +from openprotein.fold.fold import FoldAPI +from openprotein.fold.models import FoldModel, _subclasses + + +def test_fold_package_classes_predict_rather_than_sample(): + exported = [getattr(fold_package, name) for name in fold_package.__all__] + assert not any( + isinstance(item, type) and hasattr(item, "sample") for item in exported + ) + + +def test_every_fold_model_class_folds(): + classes = [FoldModel, *_subclasses(FoldModel)] + assert all(callable(getattr(cls, "fold", None)) for cls in classes) + assert all( + issubclass(item, FoldModel) + for name in fold_package.__all__ + if isinstance(item := getattr(fold_package, name), type) + and name.endswith("Model") + ) + + +def test_a_listed_id_without_its_own_class_gets_the_generic_fold_model( + mock_session, +): + listed = ["esmfold", "example-fold-v1"] + with patch("openprotein.fold.fold.api.fold_models_list_get", return_value=listed): + fold = FoldAPI(mock_session) + models = fold.list_models() + assert type(vars(fold)["example_fold_v1"]) is FoldModel + assert type(fold.get_model("example-fold-v1")) is FoldModel + assert [model.id for model in models] == listed + assert [type(model) for model in models] == [ESMFoldModel, FoldModel] diff --git a/tests/fold/test_fold_schemas.py b/tests/fold/test_fold_schemas.py index b99519a..913781d 100644 --- a/tests/fold/test_fold_schemas.py +++ b/tests/fold/test_fold_schemas.py @@ -1,6 +1,5 @@ """Test the schemas for the fold domain.""" -import json from datetime import datetime from openprotein.fold.schemas import FoldJob, FoldMetadata @@ -8,7 +7,6 @@ def test_fold_metadata_creation(): - """Test successful creation of FoldMetadata.""" metadata = FoldMetadata( job_id="test_job_id", model_id="test_model_id", args={"param": "value"} ) @@ -18,7 +16,6 @@ def test_fold_metadata_creation(): def test_fold_metadata_deserialization(): - """Test successful deserialization of FoldMetadata from JSON.""" json_data = { "job_id": "test_job_id", "model_id": "test_model_id", @@ -31,7 +28,6 @@ def test_fold_metadata_deserialization(): def test_fold_job_creation(): - """Test successful creation of FoldJob.""" now = datetime.now() job = FoldJob( job_id="test_job_id", diff --git a/tests/fold/test_request.py b/tests/fold/test_request.py new file mode 100644 index 0000000..d2bb314 --- /dev/null +++ b/tests/fold/test_request.py @@ -0,0 +1,159 @@ +from datetime import datetime, timezone +from unittest.mock import MagicMock +from uuid import uuid4 + +import pytest +from pydantic import ValidationError + +from openprotein.fold import _request as request +from openprotein.fold.common import serialize_input +from openprotein.fold.future import FoldResultFuture +from openprotein.fold.schemas import FoldJob, FoldMetadata +from openprotein.jobs import JobStatus, JobType +from openprotein.molecules import DNA, RNA, Complex, Ligand, Protein + + +def test_every_chain_wrapper_accepts_its_entities(): + msa_id = uuid4() + chain = request.MsaChain.model_validate( + {"protein": {"id": "A", "sequence": "ACDE", "msa_id": str(msa_id)}} + ) + assert chain.protein is not None and chain.protein.msa_id == msa_id + assert chain.entity is chain.protein + assert request.NoMsaChain(ligand=request.Ligand(id="L", ccd="SAH")).ligand + assert request.ProteinChain( + protein=request.Protein(id="A", sequence="ACDE") + ).protein + assert request.MsaProteinChain( + protein=request.ProteinWithMSA(id="A", sequence="ACDE") + ).protein + assert request.MsaProteinLigandChain( + ligand=request.Ligand(id="L", smiles="CCO") + ).ligand + assert request.MsaChain(dna=request.DNA(id="D", sequence="ACGT")).dna + assert request.MsaChain(rna=request.RNA(id="R", sequence="ACGU")).rna + + +@pytest.mark.parametrize("chain_id", ["A", "h1", "ABCDE", "12345", ["A", "B"]]) +def test_chain_ids_are_one_to_five_letters_or_digits(chain_id): + assert request.Protein(id=chain_id, sequence="ACDE").id == chain_id + + +@pytest.mark.parametrize( + "chain_id", ["", "ABCDEF", "A B", "A-1", "α", [], ["A", ""]], ids=repr +) +def test_other_chain_ids_are_rejected(chain_id): + with pytest.raises(ValidationError, match="chain id"): + request.Protein(id=chain_id, sequence="ACDE") + + +@pytest.mark.parametrize( + "wrapper, payload", + [ + (request.MsaChain, {}), + ( + request.MsaChain, + { + "protein": {"id": "A", "sequence": "ACDE"}, + "dna": {"id": "D", "sequence": "ACGT"}, + }, + ), + (request.ProteinChain, {"ligand": {"id": "L", "ccd": "SAH"}}), + ( + request.NoMsaChain, + {"protein": {"id": "A", "sequence": "ACDE", "msa_id": None}}, + ), + ], + ids=["no-entity", "two-entities", "entity-outside-scope", "field-outside-scope"], +) +def test_a_chain_names_exactly_one_entity_the_wrapper_accepts(wrapper, payload): + with pytest.raises(ValidationError): + wrapper.model_validate(payload) + + +@pytest.mark.parametrize( + "payload", + [ + {"id": "L"}, + {"id": "L", "smiles": "CCO", "ccd": "SAH"}, + {"id": "L", "smiles": ""}, + ], + ids=["neither", "both", "empty-string"], +) +def test_a_ligand_is_exactly_one_of_smiles_or_ccd(payload): + with pytest.raises(ValidationError, match="smiles or ccd"): + request.Ligand.model_validate(payload) + + +def test_an_empty_ccd_counts_as_absent(): + assert request.Ligand(id="L", smiles="CCO", ccd="").ccd is None + + +def test_unknown_fields_are_rejected(): + with pytest.raises(ValidationError, match="cyclic"): + request.Protein.model_validate({"id": "A", "sequence": "ACDE", "cyclic": True}) + + +def _complex() -> Complex: + protein = Protein("MVTPEG") + protein.msa = Protein.NullMSA + return Complex( + { + "A": protein, + "L": Ligand(smiles="CCO"), + "D": DNA("ACGT"), + "R": RNA("ACGU"), + } + ) + + +def test_complex_chain_ids_expand_copies_in_request_order(): + chains = [ + request.ProteinChain(protein=request.Protein(id=["A", "B"], sequence="ACDE")), + request.NoMsaChain(ligand=request.Ligand(id="L", ccd="SAH")), + ] + + assert request.complex_chain_ids(chains) == ["A", "B", "L"] + + +def test_complex_chain_ids_refuse_a_repeated_id(): + chains = [ + request.ProteinChain(protein=request.Protein(id="A", sequence="ACDE")), + request.ProteinChain(protein=request.Protein(id="A", sequence="ACDF")), + ] + + with pytest.raises(ValueError, match="duplicate chain id 'A'"): + request.complex_chain_ids(chains) + + +def test_serialize_input_dumps_validated_chains(): + [entries] = serialize_input(MagicMock(), [_complex()], needs_msa=True) + assert entries == [ + {"protein": {"id": "A", "sequence": "MVTPEG", "msa_id": None}}, + {"ligand": {"id": "L", "smiles": "CCO"}}, + {"dna": {"id": "D", "sequence": "ACGT"}}, + {"rna": {"id": "R", "sequence": "ACGU"}}, + ] + + +def test_a_serialized_complex_reads_back_as_the_same_molecules(): + session = MagicMock() + job = FoldJob( + job_id="job", + job_type=JobType.embeddings_fold, + status=JobStatus.SUCCESS, + created_date=datetime.now(timezone.utc), + ) + sequences = serialize_input(session, [_complex()], needs_msa=True) + future = FoldResultFuture( + session, + job=job, + metadata=FoldMetadata(job_id="job", model_id="m", sequences=sequences), + sequences=[], + ) + [complex] = future.complexes + assert list(complex.get_chains()) == ["A", "L", "D", "R"] + assert complex.get_protein("A").sequence == b"MVTPEG" + assert complex.get_ligand("L").smiles == "CCO" + assert complex.get_dna("D").sequence == "ACGT" + assert complex.get_rna("R").sequence == "ACGU" diff --git a/tests/jobs/test_crossvalidate_rows.py b/tests/jobs/test_crossvalidate_rows.py new file mode 100644 index 0000000..bd71bcd --- /dev/null +++ b/tests/jobs/test_crossvalidate_rows.py @@ -0,0 +1,85 @@ +"""`CrossvalidateFuture` reads evaluation rows.""" + +from unittest.mock import MagicMock + +import numpy as np +import pytest + +from openprotein.jobs import Job +from openprotein.jobs.futures import CrossvalidateFuture + +JOB = { + "job_id": "cv-1", + "job_type": "/models", + "status": "SUCCESS", + "created_date": "2026-09-05T08:00:00Z", +} + + +def _row(index: int, **extra) -> dict: + return { + "row_index": index, + "sequence": "MKT", + "property": "activity", + "y": 1.0, + "mean": 0.9, + "variance": 0.1, + } | extra + + +def _read(session, rows: list[dict]): + gp = MagicMock() + gp.evaluations.return_value = {"rows": rows} + return CrossvalidateFuture(session, Job.model_validate(JOB), gp).get() + + +def test_rows_without_a_fold_key_give_no_fold(mock_session): + """Rows that omit ``fold`` read as results with ``fold`` None.""" + results = _read(mock_session, [_row(0), _row(1)]) + assert results.fold is None + assert results.row_index.tolist() == [0, 1] + + +def test_rows_with_a_null_fold_give_no_fold(mock_session): + """Any null ``fold`` makes the result's ``fold`` None.""" + assert _read(mock_session, [_row(0, fold=1), _row(1, fold=None)]).fold is None + + +def test_rows_with_folds_give_an_int_array(mock_session): + """Rows that all carry a ``fold`` read as an int array.""" + results = _read(mock_session, [_row(0, fold=0), _row(1, fold=-1)]) + assert results.fold is not None + assert results.fold.dtype == int + assert np.array_equal(results.fold, [0, -1]) + + +def test_a_row_missing_the_fold_key_among_folds_gives_no_fold(mock_session): + """A single row without ``fold`` makes the result's ``fold`` None.""" + assert _read(mock_session, [_row(0, fold=0), _row(1)]).fold is None + + +def test_get_and_wait_reject_an_output_name(mock_session, monkeypatch): + """A cross-validation has one result, so naming an output raises.""" + monkeypatch.setattr("openprotein.jobs.futures.time.sleep", lambda seconds: None) + mock_session.get.return_value.json.return_value = JOB + gp = MagicMock() + gp.evaluations.return_value = {"rows": [_row(0)]} + future = CrossvalidateFuture(mock_session, Job.model_validate(JOB), gp) + + with pytest.raises(ValueError, match="one result.*without output"): + future.get(output="nonexistent") + with pytest.raises(ValueError, match="one result.*without output"): + future.wait(output="nonexistent") + gp.evaluations.assert_not_called() + + +def test_wait_rejects_an_output_name_before_polling(mock_session): + """Naming an output on a cross-validation wait raises without polling.""" + pending = JOB | {"status": "PENDING"} + gp = MagicMock() + future = CrossvalidateFuture(mock_session, Job.model_validate(pending), gp) + mock_session.get.reset_mock() + + with pytest.raises(ValueError, match="one result.*without output"): + future.wait(output="nonexistent") + mock_session.get.assert_not_called() diff --git a/tests/jobs/test_future_base.py b/tests/jobs/test_future_base.py new file mode 100644 index 0000000..4b2395a --- /dev/null +++ b/tests/jobs/test_future_base.py @@ -0,0 +1,327 @@ +"""`Future` as the one job handle, with the positional protocol on result futures.""" + +from datetime import datetime +from typing import Any +from unittest.mock import MagicMock, patch + +import pytest + +from openprotein.align.msa import MSAFuture +from openprotein.errors import APIError, JobFailedException +from openprotein.jobs import Future, Job, JobsAPI, JobStatus +from openprotein.jobs import futures as results +from openprotein.prompt import Prompt, PromptJob +from openprotein.prompt.schemas import PromptMetadata + +MODEL_ID = "esm2_t33_650M_UR50D" + +METADATA: dict[str, Any] = { + "model_id": MODEL_ID, + "model_family": "esm2", + "name": None, + "version": None, + "is_system": True, + "base": True, + "tags": None, + "protein_types": None, + "description": {"summary": "ESM-2 650M protein language model."}, + "dimension": 1280, + "query": None, + "multichain": None, + "methods": [ + { + "path": "batch/embeddings", + "outputs": ["embeddings", "annotations"], + "description": "Per-residue embeddings.", + }, + ], + "max_sequence_length": 4094, +} + +MODELS_JOB: dict[str, Any] = { + "job_id": "job-1", + "job_type": f"/models/{MODEL_ID}/batch/embeddings", + "status": "SUCCESS", + "created_date": "2026-09-05T08:00:00Z", +} + +ALIGN_JOB: dict[str, Any] = { + "job_id": "job-2", + "job_type": "/align/mafft", + "status": "SUCCESS", + "created_date": "2026-09-05T08:00:00Z", +} + +UNITS = [{"position": 0, "unit_id": "u0", "state": "SUCCESS"}] + + +def _serve(session: MagicMock, args: dict | None = None) -> None: + def handler(path: str, **kwargs: Any) -> MagicMock: + response = MagicMock() + if path.endswith("/units"): + response.json.return_value = {"units": UNITS, "next_position": None} + elif path == f"v1/models/{MODEL_ID}": + response.json.return_value = METADATA + elif path.endswith("/args"): + response.json.return_value = args or {} + else: + raise AssertionError(f"unexpected GET {path}") + return response + + session.get.side_effect = handler + + +def _prompt(session: MagicMock, job_type: str = "/prompt/sample_msa") -> Prompt: + job = PromptJob( + job_id="job-3", + job_type=job_type, + status=JobStatus.SUCCESS, + created_date=datetime.now(), + ) + session.jobs = MagicMock(spec=JobsAPI) + session.jobs.get_job.return_value = job + return Prompt(session, job=job, num_replicates=1) + + +def _legacy(session: MagicMock, payload: dict) -> MSAFuture: + return MSAFuture(session, Job.model_validate(payload)) + + +def _legacy_futures(session: MagicMock) -> list[Future]: + return [_legacy(session, ALIGN_JOB), _prompt(session)] + + +def _prompt_with_own_id(session: MagicMock, job_id: str | None) -> Prompt: + job = PromptJob( + job_id="job-3", + job_type="/prompt/sample_msa", + status=JobStatus.SUCCESS, + created_date=datetime.now(), + ) + session.jobs = MagicMock(spec=JobsAPI) + session.jobs.get_job.return_value = job + metadata = PromptMetadata( + id="prompt-9", + name="prompt", + description=None, + created_date=job.created_date, + num_replicates=1, + job_id=job_id, + status=JobStatus.SUCCESS, + ) + return Prompt(session, metadata=metadata) + + +def test_job_reads_address_the_job_id_not_the_resource_id( + mock_session: MagicMock, +) -> None: + """A future whose `id` is a resource id reads its job's args and units by job id.""" + prompt = _prompt_with_own_id(mock_session, "job-3") + assert prompt.id == "prompt-9" + _serve(mock_session, args={"replicates": 1}) + + assert prompt.args == {"replicates": 1} + assert [unit.position for unit in prompt.units] == [0] + paths = [call.args[0] for call in mock_session.get.call_args_list] + assert paths and all("prompt-9" not in path for path in paths) + assert any("job-3" in path for path in paths) + + +def test_reading_args_of_a_future_without_a_job_raises_without_a_request( + mock_session: MagicMock, +) -> None: + """A future with no job has no args to read, and sends nothing.""" + prompt = _prompt_with_own_id(mock_session, None) + mock_session.reset_mock() + + with pytest.raises(APIError, match="no job"): + _ = prompt.args + mock_session.get.assert_not_called() + + +def test_a_legacy_future_is_not_falsy_and_makes_no_request( + mock_session: MagicMock, +) -> None: + """`bool()` of a future that subclasses `Future` directly sends nothing.""" + futures = _legacy_futures(mock_session) + mock_session.reset_mock() + + assert all(bool(future) for future in futures) + assert mock_session.method_calls == [] + + +@pytest.mark.parametrize( + "future_type", + [ + Future, + results.FitFuture, + results.GPFitFuture, + results.CrossvalidateFuture, + MSAFuture, + Prompt, + ], +) +def test_futures_other_than_result_futures_have_no_positional_protocol( + future_type: type[Future], +) -> None: + """`len()`, iteration and indexing belong to result futures alone.""" + for name in ("__len__", "__iter__", "__getitem__", "__keys__"): + assert not hasattr(future_type, name), name + assert issubclass(results.EmbeddingFuture, results._ResultFuture) + assert hasattr(results.EmbeddingFuture, "__len__") + + +def test_the_args_of_a_legacy_future_are_fetched_once(mock_session: MagicMock) -> None: + """A job without inline args reads them from the job once, then keeps them.""" + _serve(mock_session, args={"sequences": ["MKT"]}) + future = _legacy(mock_session, ALIGN_JOB) + + assert future.args == {"sequences": ["MKT"]} + assert future.args == {"sequences": ["MKT"]} + + arg_reads = [c for c in mock_session.get.call_args_list if "args" in c.args[0]] + assert len(arg_reads) == 1 + + +def test_a_legacy_future_without_its_own_repr_prints_the_compact_form( + mock_session: MagicMock, +) -> None: + """The repr names the class, job id, status and args, loaded or not.""" + future = _legacy(mock_session, ALIGN_JOB) + + assert repr(future) == ( + "MSAFuture(job_id='job-2', status='SUCCESS', args=)" + ) + assert str(future) == repr(future) + + inline = Job.model_validate(ALIGN_JOB | {"args": {"sequences": ["MKT" * 20]}}) + assert "args={'sequences': <1 items>}" in repr(MSAFuture(mock_session, inline)) + + +def test_a_legacy_future_reads_units_and_outputs_when_its_job_type_serves_them( + mock_session: MagicMock, +) -> None: + """`units` and `outputs` read a stored job's records and method outputs.""" + _serve(mock_session) + future = _legacy(mock_session, MODELS_JOB) + + assert [unit.position for unit in future.units] == [0] + assert future.outputs == ["embeddings", "annotations"] + + +def test_a_legacy_future_without_stored_outputs_raises_on_every_output_read( + mock_session: MagicMock, +) -> None: + """A job type that serves no outputs raises the same error from each reader.""" + future = _legacy(mock_session, ALIGN_JOB) + reads = [ + lambda: future.units, + lambda: future.outputs, + lambda: future.unit(0, output="embeddings"), + lambda: future.get_item(0, output="embeddings"), + lambda: future.stream(output="embeddings"), + ] + for read in reads: + with pytest.raises(APIError, match="has no stored outputs"): + read() + mock_session.get.assert_not_called() + + +def test_an_uploaded_prompt_has_no_stored_outputs(mock_session: MagicMock) -> None: + """A prompt with no job raises the stored-outputs error.""" + prompt = Prompt( + mock_session, + metadata=_prompt(mock_session).metadata.model_copy(update={"job_id": None}), + ) + + assert prompt.job is None + with pytest.raises(APIError, match="has no stored outputs"): + _ = prompt.units + + +def test_a_sampling_prompt_reads_its_units(mock_session: MagicMock) -> None: + """A prompt sampled from a job stores outputs, so its units are readable.""" + prompt = _prompt(mock_session) + _serve(mock_session) + + assert [unit.position for unit in prompt.units] == [0] + + +def _canceled(session: MagicMock, payload: dict, future_type: type[Future]) -> Future: + session.get.return_value.json.return_value = payload | {"status": "CANCELED"} + return future_type(session, Job.model_validate(payload | {"status": "RUNNING"})) + + +@pytest.mark.parametrize("future_type", [Future, results.EmbeddingFuture]) +def test_waiting_on_a_canceled_job_with_stored_outputs_raises( + mock_session: MagicMock, future_type: type[Future] +) -> None: + """`wait()` raises for a canceled job that stores outputs.""" + future = _canceled(mock_session, MODELS_JOB, future_type) + with ( + patch("time.sleep"), + patch.object(future_type, "get") as get, + pytest.raises(JobFailedException, match="canceled") as raised, + ): + future.wait(interval=0) + assert raised.value.job_id == "job-1" + get.assert_not_called() + + +@pytest.mark.parametrize( + ("job_type", "make"), + [ + ( + "/predictor/crossvalidate", + lambda session, job: results.CrossvalidateFuture(session, job, MagicMock()), + ), + ], +) +def test_waiting_on_a_canceled_result_future_raises_for_any_job_type( + mock_session: MagicMock, job_type: str, make: Any +) -> None: + """A cross-validation future raises on a canceled job of any type.""" + payload = MODELS_JOB | {"job_type": job_type} + mock_session.get.return_value.json.return_value = payload | {"status": "CANCELED"} + future = make(mock_session, Job.model_validate(payload | {"status": "RUNNING"})) + with ( + patch("time.sleep"), + patch.object(type(future), "_get", return_value="read"), + pytest.raises(JobFailedException, match="canceled"), + ): + future.wait(interval=0) + + +def test_waiting_on_a_canceled_job_without_stored_outputs_reads_its_results( + mock_session: MagicMock, +) -> None: + """A job type that stores no outputs reads its results whatever its status.""" + future = _canceled(mock_session, ALIGN_JOB, MSAFuture) + with ( + patch("time.sleep"), + patch.object(MSAFuture, "_get", return_value="results"), + ): + assert future.wait(interval=0) == "results" + assert future.status is JobStatus.CANCELED + + +def test_a_read_passes_a_named_output_to_stream( + mock_session: MagicMock, +) -> None: + """A plain `Future` reads its job's units through `stream` with the named output.""" + future = Future(mock_session, Job.model_validate(MODELS_JOB)) + with ( + patch.object(Future, "stream", return_value=iter(["a", "b"])) as stream, + patch.object(Future, "units", new=[MagicMock()]), + ): + assert future.get(verbose=True, output="annotations") == ["a", "b"] + stream.assert_called_once_with(output="annotations") + + +def test_a_job_without_a_models_identity_is_tracked_by_a_plain_future( + mock_session: MagicMock, +) -> None: + """An unresolved models identity falls back to exactly `Future`.""" + job = Job.model_validate(MODELS_JOB | {"job_type": "/models"}) + + assert type(Future.create(mock_session, job=job)) is Future diff --git a/tests/jobs/test_future_wait.py b/tests/jobs/test_future_wait.py new file mode 100644 index 0000000..6a8275d --- /dev/null +++ b/tests/jobs/test_future_wait.py @@ -0,0 +1,56 @@ +"""`Future.wait` on jobs that end unsuccessfully.""" + +from typing import Any +from unittest.mock import MagicMock, patch + +import pytest + +from openprotein.errors import JobFailedException +from openprotein.jobs import Job +from openprotein.jobs.futures import Future + +JOB: dict[str, Any] = { + "job_id": "job-1", + "job_type": "/models", + "status": "RUNNING", + "created_date": "2026-09-05T08:00:00Z", + "provider_id": "esm2_t33_650M_UR50D", + "path": "/batch/embeddings", + "args": {"sequences": ["MKT"]}, +} + + +def _future(session, final_status: str) -> Future: + session.get.return_value.json.return_value = JOB | { + "status": final_status, + "failure_message": "boom" if final_status == "FAILURE" else None, + } + return Future(session, Job.model_validate(JOB)) + + +def test_wait_raises_for_a_canceled_job(mock_session: MagicMock) -> None: + """`wait()` raises `JobFailedException` saying the job was canceled.""" + future = _future(mock_session, "CANCELED") + with ( + patch("time.sleep"), + patch.object(Future, "get") as get, + pytest.raises(JobFailedException, match="canceled") as raised, + ): + future.wait(interval=0) + assert raised.value.job_id == "job-1" + get.assert_not_called() + + +def test_wait_raises_for_a_failed_job(mock_session: MagicMock) -> None: + """`wait()` on a failed job raises with the job's failure message.""" + future = _future(mock_session, "FAILURE") + with patch("time.sleep"), pytest.raises(JobFailedException, match="boom"): + future.wait(interval=0) + + +def test_wait_until_done_returns_for_a_canceled_job(mock_session: MagicMock) -> None: + """`wait_until_done()` reports the terminal status without raising.""" + future = _future(mock_session, "CANCELED") + with patch("time.sleep"): + assert future.wait_until_done(interval=0) is True + assert future.cancelled() diff --git a/tests/jobs/test_job_outputs.py b/tests/jobs/test_job_outputs.py new file mode 100644 index 0000000..73b33ad --- /dev/null +++ b/tests/jobs/test_job_outputs.py @@ -0,0 +1,362 @@ +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.jobs import _api as jobs_wire +from openprotein.jobs._storage import DirectArtifactStorage, verified_artifact +from openprotein.jobs.jobs import JobsAPI, _JobOutput +from openprotein.jobs.schemas import _UnitRecord + + +@pytest.mark.parametrize( + "name", ["get_job_output", "iter_job_outputs", "iter_job_units"] +) +def test_jobs_api_has_no_public_output_reads(name): + """Job output reads are on the future; the jobs API has no public form of them.""" + assert not hasattr(JobsAPI, name) + + +def test_the_jobs_package_has_no_job_output_record(): + """The decoded output record is not part of the jobs package.""" + assert not hasattr(jobs_package, "JobOutput") + assert "JobOutput" not in jobs_package.__all__ + + +def test_a_future_has_no_iter_outputs(): + """A named output is read with `stream`.""" + 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} + return response + + +def _entry(position, unit_id, value): + return {"position": position, "unit_id": unit_id, "value": 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, + } + + +class MemoryStorage: + def __init__(self, payload): + self.payload = payload + self.reads = 0 + + def iter_bytes(self, reference): + self.reads += 1 + for start in range(0, len(self.payload), 7): + yield self.payload[start : start + 7] + + +def test_output_page_forwards_cursor_and_limit(): + session = MagicMock() + session.get.return_value = _page([]) + jobs_wire.job_output_page(session, "job", "embedding", cursor="opaque", limit=50) + session.get.assert_called_once_with( + "v1/data/results/job/embedding", params={"cursor": "opaque", "limit": 50} + ) + + +def test_inline_outputs_are_lazy_ordered_and_do_not_touch_storage(): + 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") + session.get.assert_not_called() + assert list(iterator) == [_JobOutput(0, "same", 1), _JobOutput(1, "same", 2)] + assert storage.reads == 0 + assert session.get.call_args_list[1].kwargs["params"] == {"cursor": "next"} + + +@pytest.mark.parametrize("inline", ["nan", {"mean": 1, "variance": -1}, [1, 2]]) +def test_inline_values_come_back_as_stored(inline): + session = MagicMock() + session.get.return_value = _page([_entry(0, "unit", {"inline": inline})]) + (output,) = JobsAPI(session)._iter_job_outputs("job", "score") + assert output.value == inline + + +def test_artifact_reads_directly_and_verifies_full_content(): + payload = b">query\nACGT\n" + 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") + assert entry.value == payload + assert storage.reads == 1 + session.get.assert_called_once_with("v1/data/results/job/msa") + + +@pytest.mark.parametrize( + "change,match", + [ + ({"sha256": "0" * 64}, "digest"), + ({"byte_length": 1}, "size"), + ({"byte_length": 100}, "size"), + ({"byte_length": True}, "byte_length"), + ({"sha256": "x" * 64}, "sha256"), + ], +) +def test_rejects_invalid_or_corrupt_reference(change, match): + reference = _reference(b"actual content") | change + with ( + pytest.raises(ValueError, match=match), + verified_artifact(MemoryStorage(b"actual content"), reference), + ): + pytest.fail("invalid bytes became visible") + + +def test_incomplete_output_fails_without_polling(): + session = MagicMock() + session.get.return_value = MagicMock(status_code=409) + with pytest.raises(JobOutputsNotReady) as raised: + list(JobsAPI(session)._iter_job_outputs("job", "embeddings")) + assert isinstance(raised.value, APIError) + assert str(raised.value) == "output 'embeddings' of job job is not complete yet" + session.get.assert_called_once_with("v1/data/results/job/embeddings") + + +def _unit_record(position, state="SUCCESS"): + return { + "position": position, + "unit_id": f"u{position}", + "state": state, + "retries": 0, + "waits_on": ["upstream"] if position else [], + "cached": position == 0, + } + + +def test_iter_job_units_yields_unit_records_paginated_by_position(): + session = MagicMock() + first, second = MagicMock(), MagicMock() + first.json.return_value = { + "units": [_unit_record(0), _unit_record(1)], + "next_position": 5, + } + second.json.return_value = { + "units": [_unit_record(5)], + "next_position": None, + } + session.get.side_effect = [first, second] + units = list(JobsAPI(session)._iter_job_units("job")) + assert [unit.position for unit in units] == [0, 1, 5] + assert all(isinstance(unit, _UnitRecord) for unit in units) + assert units[0].status is JobStatus.SUCCESS + assert not hasattr(units[0], "waits_on") + 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.""" + + def __init__(self, delays): + self.delays = delays + self.running = 0 + self.most = 0 + self.lock = threading.Lock() + + def iter_bytes(self, reference): + with self.lock: + self.running += 1 + self.most = max(self.most, self.running) + time.sleep(self.delays[reference["uri"]]) + with self.lock: + self.running -= 1 + yield reference["uri"].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) + ] + 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)} + ) + outputs = list(_jobs(session, storage)._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"] + + +def _emitted_page(entries, next_cursor, complete=False): + response = MagicMock(status_code=200) + response.json.return_value = { + "values": entries, + "next_cursor": next_cursor, + "complete": complete, + } + return response + + +def test_an_emitted_output_read_ends_at_the_items_registered_now(): + session = MagicMock() + session.get.side_effect = [ + _emitted_page( + [_entry(0, "u", {"inline": 0}), _entry(1, "u", {"inline": 1})], "c1" + ), + _emitted_page([], "c1"), + ] + outputs = list(JobsAPI(session)._iter_job_outputs("job", "losses")) + assert [output.value for output in outputs] == [0, 1] + assert session.get.call_count == 2 + + +def test_following_yields_each_item_before_waiting_until_complete(): + session = MagicMock() + session.get.side_effect = [ + _emitted_page([_entry(0, "u", {"inline": 0})], "c1"), + _emitted_page([], "c1"), + _emitted_page([_entry(1, "u", {"inline": 1})], "c2"), + _emitted_page([], None, complete=True), + ] + with patch("openprotein.jobs.jobs.time.sleep") as sleep: + stream = JobsAPI(session)._iter_job_outputs( + "job", "losses", follow=True, interval=7 + ) + assert next(stream).value == 0 + sleep.assert_not_called() + assert [output.value for output in stream] == [1] + sleep.assert_called_once_with(7) + cursors = [ + call.kwargs.get("params", {}).get("cursor") + for call in session.get.call_args_list + ] + assert cursors == [None, "c1", "c1", "c2"] + + +def test_a_failed_emitted_item_raises_with_its_error(): + session = MagicMock() + session.get.return_value = _emitted_page( + [_entry(0, "u", None) | {"error": "digest mismatch"}], None, complete=True + ) + with pytest.raises(JobFailedException) as raised: + list(JobsAPI(session)._iter_job_outputs("job", "embeddings")) + assert raised.value.job_id == "job" + assert ( + raised.value.failure_message == "output at position 0 failed: digest mismatch" + ) + + +@pytest.mark.parametrize("position", [-1, "0", True]) +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}} + ) + + +def test_a_final_output_page_without_successes_keeps_reading(): + session = MagicMock() + session.get.side_effect = [ + _page([], "100"), + _page([_entry(100, "u100", {"inline": 1})]), + ] + outputs = list(JobsAPI(session)._iter_job_outputs("job", "score")) + assert [output.position for output in outputs] == [100] diff --git a/tests/jobs/test_jobs.py b/tests/jobs/test_jobs.py index d87a33b..3371ca8 100644 --- a/tests/jobs/test_jobs.py +++ b/tests/jobs/test_jobs.py @@ -1,7 +1,9 @@ +import time from datetime import datetime from unittest.mock import MagicMock, patch import pytest +import requests from openprotein.errors import JobFailedException, TimeoutException from openprotein.jobs.futures import Future @@ -10,15 +12,12 @@ class ConcreteFuture(Future): - """A concrete implementation of the abstract Future for testing purposes.""" - def _get(self, verbose: bool = False, **kwargs) -> str: return "Result" @pytest.fixture def mock_job_object() -> Job: - """Provides a reusable mock Job object.""" return Job( job_id="job_123", job_type=JobType.stub, @@ -87,7 +86,6 @@ def test_jobs_api_list_rejects_both_limit_and_page_size( def test_jobs_api_get_job(mock_session: MagicMock, mock_job_object: Job) -> None: - """Tests that JobsAPI.get_job() calls the underlying api function.""" # Configure the mock session to return the job dictionary mock_session.get.return_value.status_code = 200 mock_session.get.return_value.json.return_value = mock_job_object.model_dump( @@ -103,7 +101,6 @@ def test_jobs_api_get_job(mock_session: MagicMock, mock_job_object: Job) -> None @pytest.fixture def pending_job_obj() -> Job: - """Provides a reusable mock Job object in PENDING state.""" return Job( job_id="job_123", job_type=JobType.stub, @@ -115,7 +112,6 @@ def pending_job_obj() -> Job: def test_future_wait_until_done_success( mock_session: MagicMock, pending_job_obj: Job ) -> None: - """Tests the polling logic of a future for a successful job.""" mock_session.get.return_value.json.side_effect = [ { "job_id": "job_123", @@ -143,7 +139,6 @@ def test_future_wait_until_done_success( def test_future_wait_until_done_failure( mock_session: MagicMock, pending_job_obj: Job ) -> None: - """Tests the polling logic of a future for a failed job.""" mock_session.get.return_value.json.side_effect = [ { "job_id": "job_123", @@ -229,7 +224,6 @@ def test_future_wait_raises_on_failed_job( def test_future_wait_until_done_timeout( mock_session: MagicMock, pending_job_obj: Job ) -> None: - """Tests that the future correctly times out if the job never finishes.""" mock_session.get.return_value.json.return_value = { "job_id": "job_123", "status": "RUNNING", @@ -241,3 +235,198 @@ def test_future_wait_until_done_timeout( with pytest.raises(TimeoutException): future.wait_until_done(interval=0.01, timeout=1) + + +def test_jobs_api_list_with_name(mock_session: MagicMock, mock_job_object: Job) -> None: + """JobsAPI.list forwards `name` to the wire alongside the page size.""" + mock_session.get.return_value.status_code = 200 + mock_session.get.return_value.json.return_value = [ + mock_job_object.model_dump(mode="json") + ] + + api = JobsAPI(mock_session) + api.list(name="my-run") + + mock_session.get.assert_called_once_with( + "v1/jobs", params={"name": "my-run", "page_size": 100} + ) + + +def test_jobs_api_update(mock_session: MagicMock, mock_job_object: Job) -> None: + """JobsAPI.update issues the PUT and returns the updated job.""" + mock_session.put.return_value.json.return_value = mock_job_object.model_dump( + mode="json" + ) | {"name": "my-run"} + + api = JobsAPI(mock_session) + job = api.update("job_123", name="my-run") + + mock_session.put.assert_called_once_with("v1/jobs/job_123", json={"name": "my-run"}) + assert job.name == "my-run" + + +def test_future_rename(mock_session: MagicMock, mock_job_object: Job) -> None: + """rename swaps in the job the server returns.""" + mock_session.put.return_value.json.return_value = mock_job_object.model_dump( + mode="json" + ) | {"name": "my-run", "description": "first pass"} + + future = ConcreteFuture(session=mock_session, job=mock_job_object) + future.rename(name="my-run", description="first pass") + + mock_session.put.assert_called_once_with( + "v1/jobs/job_123", + json={"name": "my-run", "description": "first pass"}, + ) + assert future.name == "my-run" + assert future.description == "first pass" + + +def test_future_rename_name_only_omits_description( + mock_session: MagicMock, mock_job_object: Job +) -> None: + """Renaming with only a name sends no description key.""" + mock_session.put.return_value.json.return_value = mock_job_object.model_dump( + mode="json" + ) | {"name": "my-run"} + + future = ConcreteFuture(session=mock_session, job=mock_job_object) + future.rename(name="my-run") + + mock_session.put.assert_called_once_with("v1/jobs/job_123", json={"name": "my-run"}) + + +def test_future_rename_preserves_extra_fields(mock_session: MagicMock) -> None: + """rename carries over extra fields the same way refresh does.""" + job_with_extra = Job( + job_id="job_123", + job_type=JobType.stub, + status=JobStatus.SUCCESS, + created_date=datetime.now(), + N=5, + ) + mock_session.put.return_value.json.return_value = { + "job_id": "job_123", + "job_type": "stub", + "status": "SUCCESS", + "created_date": datetime.now().isoformat(), + "name": "my-run", + } + + future = ConcreteFuture(session=mock_session, job=job_with_extra) + future.rename(name="my-run") + + assert future.job.N == 5 + + +def test_jobs_api_list_takes_more_recent_than_fourth(mock_session: MagicMock) -> None: + """Positional order is status, job_type, assay_id, more_recent_than.""" + mock_session.get.return_value.json.return_value = [] + + JobsAPI(mock_session).list(None, None, None, "2026-01-01T00:00:00") + + mock_session.get.assert_called_once_with( + "v1/jobs", + params={"more_recent_than": "2026-01-01T00:00:00", "page_size": 100}, + ) + + +def test_jobs_api_list_takes_name_by_keyword_only(mock_session: MagicMock) -> None: + with pytest.raises(TypeError): + JobsAPI(mock_session).list(None, None, None, None, None, None, None, "my-run") + + +class _Clock: + """A fake clock whose sleeps advance it.""" + + def __init__(self) -> None: + self.now = 1000.0 + self.sleeps: list[float] = [] + + def time(self) -> float: + return self.now + + def sleep(self, seconds: float) -> None: + self.sleeps.append(seconds) + self.now += seconds + + +def _running(mock_session: MagicMock) -> None: + mock_session.get.return_value.json.return_value = { + "job_id": "job_123", + "status": "RUNNING", + "job_type": "stub", + "created_date": datetime.now().isoformat(), + } + + +def test_wait_caps_each_poll_and_sleep_by_the_remaining_timeout( + mock_session: MagicMock, pending_job_obj: Job +) -> None: + """With a wait timeout, each poll and sleep is bounded by the remaining budget.""" + _running(mock_session) + clock = _Clock() + future = ConcreteFuture(mock_session, pending_job_obj) + + with patch("openprotein.jobs.futures.time", clock), pytest.raises(TimeoutException): + future.wait_until_done(interval=3, timeout=5) + + assert clock.sleeps == [3, 2] + assert [c.kwargs["timeout"] for c in mock_session.get.call_args_list] == [5, 2] + + +def test_wait_turns_a_poll_that_times_out_into_the_wait_timeout( + mock_session: MagicMock, pending_job_obj: Job +) -> None: + """A poll that fails once the budget is spent raises `TimeoutException`.""" + + def slow(*args, **kwargs): + time.sleep(0.1) + raise requests.exceptions.ReadTimeout("slow") + + mock_session.get.side_effect = slow + future = ConcreteFuture(mock_session, pending_job_obj) + + with pytest.raises(TimeoutException): + future.wait_until_done(interval=0, timeout=0.05) + + +def test_a_refresh_without_a_timeout_polls_with_the_session_timeout( + mock_session: MagicMock, pending_job_obj: Job +) -> None: + """`refresh()` passes no timeout of its own, even after a budgeted wait.""" + _running(mock_session) + future = ConcreteFuture(mock_session, pending_job_obj) + with pytest.raises(TimeoutException): + future.wait_until_done(interval=0, timeout=0) + + mock_session.get.reset_mock() + future.refresh() + + mock_session.get.assert_called_once_with("v1/jobs/job_123") + + +def test_wait_raises_a_poll_error_while_the_budget_remains( + mock_session: MagicMock, pending_job_obj: Job +) -> None: + """A poll that fails with budget left raises its own request error.""" + mock_session.get.side_effect = requests.exceptions.ReadTimeout("slow") + future = ConcreteFuture(mock_session, pending_job_obj) + + with pytest.raises(requests.exceptions.ReadTimeout): + future.wait_until_done(interval=0, timeout=5) + + +def test_wait_without_a_timeout_polls_with_the_session_timeout( + mock_session: MagicMock, pending_job_obj: Job +) -> None: + """Without a wait timeout, polls pass no timeout of their own.""" + mock_session.get.return_value.json.return_value = { + "job_id": "job_123", + "status": "SUCCESS", + "job_type": "stub", + "created_date": datetime.now().isoformat(), + } + future = ConcreteFuture(mock_session, pending_job_obj) + future.wait_until_done(interval=0) + mock_session.get.assert_called_once_with("v1/jobs/job_123") diff --git a/tests/jobs/test_jobs_api.py b/tests/jobs/test_jobs_api.py index 3b917d2..9b22746 100644 --- a/tests/jobs/test_jobs_api.py +++ b/tests/jobs/test_jobs_api.py @@ -4,13 +4,13 @@ import pytest +from openprotein.jobs import _api as jobs_wire from openprotein.jobs import api as jobs_api from openprotein.jobs.schemas import Job, JobStatus, JobType @pytest.fixture def job_response_json() -> dict[str, Any]: - """Provides a sample JSON response for a single job.""" return { "job_id": "job_123", "job_type": "stub", @@ -20,7 +20,6 @@ def job_response_json() -> dict[str, Any]: def test_job_get(mock_session: MagicMock, job_response_json: dict[str, Any]) -> None: - """Tests that job_get calls the correct endpoint and parses the response.""" mock_session.get.return_value.json.return_value = job_response_json job = jobs_api.job_get(mock_session, "job_123") @@ -34,7 +33,6 @@ def test_job_get(mock_session: MagicMock, job_response_json: dict[str, Any]) -> def test_jobs_list_no_params( mock_session: MagicMock, job_response_json: dict[str, Any] ) -> None: - """Tests jobs_list with no optional parameters.""" mock_session.get.return_value.json.return_value = [job_response_json] jobs = jobs_api.jobs_list(mock_session) @@ -48,7 +46,6 @@ def test_jobs_list_no_params( def test_jobs_list_with_all_params( mock_session: MagicMock, job_response_json: dict[str, Any] ) -> None: - """Tests jobs_list with all optional parameters provided.""" mock_session.get.return_value.json.return_value = [job_response_json] now = datetime.now() @@ -58,6 +55,7 @@ def test_jobs_list_with_all_params( status=JobStatus.SUCCESS, job_type=JobType.stub, assay_id="assay_456", + name="my-run", more_recent_than=now.isoformat(), limit=50, ) @@ -66,6 +64,7 @@ def test_jobs_list_with_all_params( "status": "SUCCESS", "job_type": "stub", "assay_id": "assay_456", + "name": "my-run", "more_recent_than": now.isoformat(), "limit": 50, } @@ -76,7 +75,6 @@ def test_jobs_list_with_all_params( def test_jobs_list_with_page_params( mock_session: MagicMock, job_response_json: dict[str, Any] ) -> None: - """Tests jobs_list forwards page_size and page_offset to the server.""" mock_session.get.return_value.json.return_value = [job_response_json] jobs_api.jobs_list(session=mock_session, page_size=25, page_offset=50) @@ -106,3 +104,86 @@ def test_jobs_list_legacy_limit_unchanged( jobs_api.jobs_list(session=mock_session, limit=10) mock_session.get.assert_called_once_with("v1/jobs", params={"limit": 10}) + + +def test_jobs_list_with_name( + mock_session: MagicMock, job_response_json: dict[str, Any] +) -> None: + """`name` is forwarded as a query param.""" + mock_session.get.return_value.json.return_value = [job_response_json] + + jobs_api.jobs_list(session=mock_session, name="my-run") + + mock_session.get.assert_called_once_with("v1/jobs", params={"name": "my-run"}) + + +def test_job_get_parses_name_and_description(mock_session: MagicMock) -> None: + """Name and description are declared fields, not extras.""" + mock_session.get.return_value.json.return_value = { + "job_id": "job_123", + "job_type": "stub", + "status": "SUCCESS", + "created_date": datetime.now().isoformat(), + "name": "my-run", + "description": "first pass", + } + + job = jobs_api.job_get(mock_session, "job_123") + + assert "name" in Job.model_fields + assert "description" in Job.model_fields + assert job.name == "my-run" + assert job.description == "first pass" + + +def test_job_update_sends_only_supplied_fields( + mock_session: MagicMock, job_response_json: dict[str, Any] +) -> None: + """A name-only rename does not clear the description.""" + mock_session.put.return_value.json.return_value = job_response_json | { + "name": "my-run" + } + + job = jobs_wire.job_update(mock_session, "job_123", name="my-run") + + mock_session.put.assert_called_once_with("v1/jobs/job_123", json={"name": "my-run"}) + assert job.name == "my-run" + + +def test_job_update_sends_both_fields( + mock_session: MagicMock, job_response_json: dict[str, Any] +) -> None: + """Name and description are sent together when both are given.""" + mock_session.put.return_value.json.return_value = job_response_json | { + "name": "my-run", + "description": "first pass", + } + + jobs_wire.job_update( + mock_session, "job_123", name="my-run", description="first pass" + ) + + mock_session.put.assert_called_once_with( + "v1/jobs/job_123", json={"name": "my-run", "description": "first pass"} + ) + + +def test_job_update_with_neither_field_sends_empty_body( + mock_session: MagicMock, job_response_json: dict[str, Any] +) -> None: + """Calling job_update with no name or description sends an empty body.""" + mock_session.put.return_value.json.return_value = job_response_json + + jobs_wire.job_update(mock_session, "job_123") + + mock_session.put.assert_called_once_with("v1/jobs/job_123", json={}) + + +def test_jobs_list_takes_more_recent_than_fourth(mock_session: MagicMock) -> None: + mock_session.get.return_value.json.return_value = [] + + jobs_api.jobs_list(mock_session, None, None, None, "2026-01-01T00:00:00") + + mock_session.get.assert_called_once_with( + "v1/jobs", params={"more_recent_than": "2026-01-01T00:00:00"} + ) diff --git a/tests/jobs/test_jobs_schemas.py b/tests/jobs/test_jobs_schemas.py index 5bf281e..53233d3 100644 --- a/tests/jobs/test_jobs_schemas.py +++ b/tests/jobs/test_jobs_schemas.py @@ -1,6 +1,6 @@ from datetime import datetime -from unittest.mock import MagicMock from typing import Any +from unittest.mock import MagicMock import pytest from requests import Response @@ -9,7 +9,6 @@ def test_job_status_done() -> None: - """Tests the done() method of the JobStatus enum.""" assert JobStatus.SUCCESS.done() is True assert JobStatus.FAILURE.done() is True assert JobStatus.CANCELED.done() is True @@ -19,7 +18,6 @@ def test_job_status_done() -> None: def test_job_status_cancelled() -> None: - """Tests the cancelled() method of the JobStatus enum.""" assert JobStatus.CANCELED.cancelled() is True assert JobStatus.SUCCESS.cancelled() is False assert JobStatus.FAILURE.cancelled() is False @@ -27,7 +25,6 @@ def test_job_status_cancelled() -> None: @pytest.fixture def base_job_dict() -> dict[str, Any]: - """Provides a basic dictionary to instantiate a Job model.""" return { "job_id": "job_123", "job_type": JobType.stub, @@ -43,14 +40,12 @@ def base_job_dict() -> dict[str, Any]: def test_job_model_validation_success(base_job_dict: dict[str, Any]) -> None: - """Tests successful validation of the Job model from a dictionary.""" job = Job.model_validate(base_job_dict) assert job.job_id == base_job_dict["job_id"] assert job.status == JobStatus.PENDING def test_job_model_missing_optional_fields(base_job_dict: dict[str, Any]) -> None: - """Tests that the Job model validates correctly when optional fields are missing.""" del base_job_dict["start_date"] del base_job_dict["end_date"] del base_job_dict["prerequisite_job_id"] @@ -63,14 +58,31 @@ def test_job_model_missing_optional_fields(base_job_dict: dict[str, Any]) -> Non def test_job_create_from_dict(base_job_dict: dict[str, Any]) -> None: - """Tests the Job.create() factory method from a dictionary.""" job = Job.create(base_job_dict) assert isinstance(job, Job) assert job.job_id == "job_123" +def test_job_metadata_round_trips(base_job_dict: dict[str, Any]) -> None: + job = Job.model_validate( + base_job_dict | {"metadata": {"svd": {"transform_job_id": "t"}}} + ) + assert job.metadata == {"svd": {"transform_job_id": "t"}} + + +def test_job_metadata_defaults_to_none(base_job_dict: dict[str, Any]) -> None: + assert Job.model_validate(base_job_dict).metadata is None + + +@pytest.mark.parametrize( + "field", + ["units_digest", "unit_count", "provider_id", "path", "version", "outputs"], +) +def test_job_does_not_declare_model_fields(field: str) -> None: + assert field not in Job.model_fields + + def test_job_create_from_mock_response(base_job_dict: dict[str, Any]) -> None: - """Tests the Job.create() factory method from a mocked Response object.""" mock_response = MagicMock(spec=Response) mock_response.json.return_value = base_job_dict @@ -78,3 +90,24 @@ def test_job_create_from_mock_response(base_job_dict: dict[str, Any]) -> None: assert isinstance(job, Job) assert job.job_id == "job_123" mock_response.json.assert_called_once() + + +@pytest.mark.parametrize( + ("job_type", "schema"), + [ + ("/models", "Job"), + ("/models/esm2_t33_650M_UR50D/batch/embeddings", "Job"), + ("/search/mmseqs2", "Job"), + ("/align/prompt", "PromptJob"), + ("/prompt/sample_msa", "PromptJob"), + ], +) +def test_a_job_loads_as_the_schema_its_type_names( + base_job_dict: dict[str, Any], job_type: str, schema: str +) -> None: + import openprotein.models # noqa: F401 + import openprotein.prompt # noqa: F401 + + job = Job.create(base_job_dict | {"job_type": job_type}) + + assert type(job).__name__ == schema diff --git a/tests/jobs/test_model_result_contracts.py b/tests/jobs/test_model_result_contracts.py new file mode 100644 index 0000000..629ee27 --- /dev/null +++ b/tests/jobs/test_model_result_contracts.py @@ -0,0 +1,145 @@ +import hashlib +import json +import time +from pathlib import Path +from unittest.mock import MagicMock, patch + +import numpy as np +import pytest +import requests + +from openprotein import auth_store +from openprotein.base import APISession +from openprotein.errors import HTTPError +from openprotein.jobs import JobsAPI +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" +) + + +def response(status, url, body, content_type="application/json"): + result = requests.Response() + result.status_code = status + result.url = url + result.headers["Content-Type"] = content_type + result._content = body + result._content_consumed = True + return result + + +@pytest.fixture +def jobs(tmp_path, monkeypatch): + monkeypatch.setattr( + "openprotein.base.TokenStore", + lambda *a, **k: auth_store.TokenStore(dir=tmp_path), + ) + login = MagicMock(status_code=200, ok=True, headers={}) + login.json.return_value = { + "access_token": "access", + "refresh_token": "refresh", + "expires_in": 900, + } + with patch.object(APISession, "post", return_value=login): + session = APISession("user@example.com", "password", backend=API) + session._expires_at = time.time() + 10_000 + return JobsAPI(session) + + +@pytest.mark.parametrize( + "status,detail", [(404, "output not available"), (502, "Bad Gateway")] +) +@pytest.mark.parametrize("paged", [False, True], ids=["item", "page"]) +def test_affinity_http_errors_propagate(jobs, monkeypatch, status, detail, paged): + path = "v1/data/results/job/affinity" + ("" if paged else "/0") + + def request(session, method, url, **kwargs): + assert method == "GET" + assert url == API + path + return response(status, url, json.dumps({"detail": detail}).encode()) + + monkeypatch.setattr(requests.Session, "request", request) + with pytest.raises(HTTPError) as caught: + if paged: + list(jobs._iter_job_outputs("job", "affinity")) + else: + jobs._get_job_output("job", 0, "affinity") + assert caught.value.status_code == status + assert caught.value.response.json() == {"detail": detail} + + +def test_affinity_json_ref_decodes_for_item_and_page(jobs, monkeypatch): + expected = {"affinity_pred_value": 1.2, "affinity_probability_binary": 0.8} + payload = json.dumps(expected).encode() + entry = { + "position": 0, + "unit_id": "unit", + "state": "SUCCESS", + "value": { + "ref": { + "uri": "s3://content/affinity", + "byte_length": len(payload), + "sha256": hashlib.sha256(payload).hexdigest(), + "codec": "json-utf8-v1", + "download_url": ARTIFACT, + } + }, + } + downloads = [] + + def request(session, method, url, **kwargs): + assert method == "GET" + if url == ARTIFACT: + downloads.append(url) + assert session.auth is None + assert "Authorization" not in session.headers + assert "Authorization" not in kwargs.get("headers", {}) + return response(200, url, payload) + if url == API + "v1/data/results/job/affinity/0": + body = entry + else: + assert url == API + "v1/data/results/job/affinity" + body = {"values": [entry], "next_cursor": None} + return response(200, url, json.dumps(body).encode()) + + monkeypatch.setattr(requests.Session, "request", request) + assert jobs._get_job_output("job", 0, "affinity").value == expected + assert [output.value for output in jobs._iter_job_outputs("job", "affinity")] == [ + expected + ] + assert downloads == [ARTIFACT, ARTIFACT] + + +def test_prediction_inline_values_preserve_quoted_property(jobs, monkeypatch): + expected = json.loads((PREDICTION_DATA / "quoted_predictions.json").read_text()) + assert expected == [{'p"q': {"mean": 1.5, "variance": 2.5}}] + entry = {"position": 0, "unit_id": "unit", "value": {"inline": expected[0]}} + + def request(session, method, url, **kwargs): + assert method == "GET" + if url == API + "v1/data/results/job/predictions/0": + body = entry + else: + assert url == API + "v1/data/results/job/predictions" + body = {"values": [entry], "next_cursor": None} + return response(200, url, json.dumps(body).encode()) + + monkeypatch.setattr(requests.Session, "request", request) + item = jobs._get_job_output("job", 0, "predictions") + page = list(jobs._iter_job_outputs("job", "predictions")) + assert (item.position, item.value) == (0, expected[0]) + assert [(output.position, output.value) for output in page] == [(0, expected[0])] + + +def test_decode_predict_batched_quoted_columns(): + expected = json.loads((PREDICTION_DATA / "quoted_predictions.json").read_text()) + mean, variance = decode_predict( + (PREDICTION_DATA / "quoted_predictions.csv").read_bytes(), batched=True + ) + assert mean.shape == (1, 1) + assert variance.shape == (1, 1) + np.testing.assert_array_equal(mean, [[expected[0]['p"q']["mean"]]]) + np.testing.assert_array_equal(variance, [[expected[0]['p"q']["variance"]]]) diff --git a/tests/jobs/test_outputs_listing.py b/tests/jobs/test_outputs_listing.py new file mode 100644 index 0000000..4fc4194 --- /dev/null +++ b/tests/jobs/test_outputs_listing.py @@ -0,0 +1,90 @@ +"""`Future.outputs` lists names only for jobs whose outputs the reads serve.""" + +from typing import Any + +import pytest + +from openprotein.errors import APIError +from openprotein.jobs import Future, Job, JobsAPI, SVDFitFuture +from openprotein.models import ModelsAPI +from openprotein.prompt.models import Prompt +from openprotein.prompt.schemas import PromptMetadata +from tests.models.support import SUBMITTED_JOB, ModelsSession + +NO_OUTPUTS = "has no stored outputs to read" + + +def _session_with_sampling_job() -> tuple[ModelsSession, dict[str, Any]]: + client = ModelsSession() + session = client.session + session.jobs = JobsAPI(session) + job = SUBMITTED_JOB | {"job_type": "/prompt/sample_msa"} + job_id = job["job_id"] + client.get_routes[f"v1/jobs/{job_id}"] = job + client.get_routes[f"v1/prompt/{job_id}"] = { + "id": job_id, + "job_id": job_id, + "name": "p", + "description": None, + "created_date": job["created_date"], + "num_replicates": 1, + "status": "SUCCESS", + } + client.outputs[(job_id, "prompt")] = ["value"] + return client, job + + +def test_a_sampling_job_lists_its_output_without_a_model_lookup(): + client, job = _session_with_sampling_job() + + future = Future(client.session, Job.model_validate(job)) + + assert future.outputs == ["prompt"] + assert not any( + call.args[0].startswith("v1/models/") + for call in client.session.get.call_args_list + ) + + +def test_a_reloaded_prompt_lists_its_output_without_a_model_lookup(): + client, job = _session_with_sampling_job() + metadata = PromptMetadata.model_validate( + client.get_routes[f"v1/prompt/{job['job_id']}"] + ) + + prompt = Prompt(client.session, metadata=metadata) + + assert prompt.outputs == ["prompt"] + assert not any( + call.args[0].startswith("v1/models/") + for call in client.session.get.call_args_list + ) + + +def test_a_submitted_projection_without_stored_outputs_refuses_to_list_outputs(): + client = ModelsSession() + models = ModelsAPI(client.session) + job = SUBMITTED_JOB | {"job_type": "/svd/embed"} + client.post_routes["v1/models/svd/s-1/batch/embeddings"] = job + + future = models.get_model("svd/s-1").transform(["AC"]) + + with pytest.raises(APIError, match=NO_OUTPUTS): + _ = future.outputs + with pytest.raises(APIError, match=NO_OUTPUTS): + future.get() + + +def test_a_fit_without_stored_outputs_refuses_to_list_outputs(): + client = ModelsSession() + job = Job.create(SUBMITTED_JOB | {"job_type": "/svd/fit"}) + + with pytest.raises(APIError, match=NO_OUTPUTS): + _ = SVDFitFuture(client.session, job).outputs + + +def test_a_fit_with_stored_outputs_lists_them(): + client = ModelsSession() + job = Job.create(SUBMITTED_JOB | {"job_type": "/models/svd/s-1/fit"}) + + assert SVDFitFuture(client.session, job).outputs == ["sequences"] diff --git a/tests/jobs/test_public_homes.py b/tests/jobs/test_public_homes.py new file mode 100644 index 0000000..09921d9 --- /dev/null +++ b/tests/jobs/test_public_homes.py @@ -0,0 +1,293 @@ +"""Where the job machinery shared by models and data jobs lives.""" + +import ast +import importlib +import subprocess +import sys +from datetime import datetime +from importlib.util import find_spec +from pathlib import Path +from typing import Any +from unittest.mock import MagicMock + +import pytest + +from openprotein import jobs, models +from openprotein.jobs import Future, Job, UnknownJobFuture + + +@pytest.mark.parametrize( + "module", + [ + "openprotein.jobs", + "openprotein.jobs.schemas", + "openprotein.models", + "openprotein.models.schemas", + ], +) +@pytest.mark.parametrize("name", ["ModelsJob", "MODELS_JOB_TYPE"]) +def test_models_jobs_have_no_schema_of_their_own(module, name): + assert not hasattr(importlib.import_module(module), name) + + +def _payload(job_type: str) -> dict[str, Any]: + return { + "job_id": "m-1", + "job_type": job_type, + "status": "SUCCESS", + "created_date": datetime(2026, 9, 10, 12, 0, 0).isoformat(), + "args": {"model_id": "poet-2"}, + } + + +@pytest.mark.parametrize( + ("job_type", "future_name"), + [ + ("/models", "Future"), + ("/models/poet-2/batch/embeddings", "EmbeddingFuture"), + ("/models/boltzgen", "UnknownJobFuture"), + ], +) +def test_a_models_job_reloads_as_a_plain_job_routed_by_its_type(job_type, future_name): + future = Future.create(session=MagicMock(), response=_payload(job_type)) + + assert type(future.job) is Job + assert type(future).__name__ == future_name + assert isinstance(future, UnknownJobFuture) == (future_name == "UnknownJobFuture") + + +TASK_FUTURES = [ + "Future", + "FitFuture", + "FutureUnit", + "EmbeddingFuture", + "LogitsFuture", + "AttentionFuture", + "LogLikelihoodFuture", + "SingleSiteScoreFuture", + "IndelScoreFuture", + "SequenceGenerationFuture", + "PredictionFuture", + "SingleSitePredictionFuture", + "StructureDesignFuture", + "StructurePredictionFuture", +] + + +@pytest.mark.parametrize("name", TASK_FUTURES) +def test_task_futures_live_in_jobs_futures(name): + from openprotein.jobs import futures + + future = getattr(futures, name) + assert getattr(jobs, name) is future + assert future.__module__ == "openprotein.jobs.futures" + assert name in jobs.__all__ + + +@pytest.mark.parametrize("name", TASK_FUTURES) +def test_task_futures_are_not_in_models(name): + assert not hasattr(models, name) + assert name not in models.__all__ + + +@pytest.mark.parametrize( + "module", + [ + "openprotein.models.future", + "openprotein.models.results", + "openprotein.models.unit", + "openprotein.models._dispatch", + ], +) +def test_the_old_future_modules_are_gone(module): + with pytest.raises(ModuleNotFoundError): + importlib.import_module(module) + + +def test_unit_records_are_read_by_the_jobs_api(): + from openprotein.jobs import _api + from openprotein.models import _api as model_api + + assert callable(_api.get_unit) + assert not hasattr(model_api, "get_unit") + + +@pytest.mark.parametrize("name", ["Unit", "UnitState", "JobOutput"]) +def test_the_unit_and_output_records_are_not_public(name): + from openprotein.jobs import schemas + + assert not hasattr(jobs, name) + assert name not in jobs.__all__ + assert name not in schemas.__all__ + assert not hasattr(schemas, name) + + +def test_units_are_handled_as_future_units(): + from openprotein.jobs import futures + + assert jobs.FutureUnit is futures.FutureUnit + assert not hasattr(futures.FutureUnit, "state") + + +def test_domain_futures_stay_with_their_domain(): + from openprotein.data import prompts + + assert not hasattr(prompts, "PromptFuture") + assert not issubclass(prompts.Prompt, jobs.Future) + assert not hasattr(jobs, "PromptFuture") + assert not hasattr(jobs, "MSASearchFuture") + + +def test_a_search_job_reloads_as_a_plain_future(): + future = Future.create(session=MagicMock(), response=_payload("/search/mmseqs2")) + + assert type(future.job) is Job + assert type(future) is jobs.Future + assert future.unit(0, output="msa").output == "msa" + assert find_spec("openprotein.search") is None + + +FIT_FUTURES = ["GPFitFuture", "SVDFitFuture", "UMAPFitFuture", "CrossvalidateFuture"] + + +@pytest.mark.parametrize("name", FIT_FUTURES) +def test_fit_futures_live_in_jobs_futures(name): + from openprotein.jobs import futures + + future = getattr(futures, name) + assert getattr(jobs, name) is future + assert future.__module__ == "openprotein.jobs.futures" + assert name in jobs.__all__ + assert not hasattr(models, name) + assert name not in models.__all__ + + +@pytest.mark.parametrize( + ("module", "name"), + [ + ("openprotein.models.gp", "CrossvalidateFuture"), + ("openprotein.models.gp", "GPFitFuture"), + ("openprotein.models.svd", "SVDFitFuture"), + ("openprotein.models.umap", "UMAPFitFuture"), + ], +) +def test_fit_futures_are_absent_from_their_old_defining_modules(module, name): + assert not hasattr(importlib.import_module(module), name) + + +LAZY_ONLY = ("openprotein.models", "openprotein.data", "openprotein.search") + + +def _is_type_checking(test: ast.expr) -> bool: + return (isinstance(test, ast.Name) and test.id == "TYPE_CHECKING") or ( + isinstance(test, ast.Attribute) and test.attr == "TYPE_CHECKING" + ) + + +def _executed_at_import(body: list[ast.stmt]): + """Statements that run when the module is imported, function bodies excluded.""" + for node in body: + yield node + if isinstance(node, ast.If): + if not _is_type_checking(node.test): + yield from _executed_at_import(node.body) + yield from _executed_at_import(node.orelse) + elif isinstance(node, (ast.Try, getattr(ast, "TryStar", ast.Try))): + for block in (node.body, node.orelse, node.finalbody): + yield from _executed_at_import(block) + for handler in node.handlers: + yield from _executed_at_import(handler.body) + elif isinstance(node, (ast.With, ast.For, ast.While, ast.ClassDef)): + yield from _executed_at_import(node.body) + yield from _executed_at_import(getattr(node, "orelse", [])) + + +def _eager_imports(source: str, module: str) -> list[str]: + """Modules under LAZY_ONLY that `module` imports when it is imported.""" + package = ( + module.split(".") if module.endswith("__init__") else module.split(".")[:-1] + ) + package = [p for p in package if p != "__init__"] + found = [] + for node in _executed_at_import(ast.parse(source).body): + if isinstance(node, ast.Import): + targets = [alias.name for alias in node.names] + elif isinstance(node, ast.ImportFrom): + base = package[: len(package) - node.level + 1] if node.level else [] + parent = ".".join(base + ([node.module] if node.module else [])) + targets = [parent] + [f"{parent}.{alias.name}" for alias in node.names] + else: + continue + found += [ + t + for t in targets + if any(t == p or t.startswith(p + ".") for p in LAZY_ONLY) + ] + return found + + +@pytest.mark.parametrize( + "source", + [ + "from openprotein.models import Model", + "from ..models import Model", + "from openprotein import models", + "import openprotein.data.prompts", + "try:\n pass\nexcept ImportError:\n from openprotein.models import Model", + "if x:\n pass\nelse:\n from openprotein.search import SearchJob", + "try:\n pass\nfinally:\n from openprotein.models import Model", + "class A:\n from openprotein.models import Model", + "if TYPE_CHECKING:\n pass\nelse:\n from openprotein.models import Model", + ], +) +def test_the_eager_import_check_sees_each_import_form(source): + assert _eager_imports(source, "openprotein.jobs.futures") + + +@pytest.mark.parametrize( + "source", + [ + "if TYPE_CHECKING:\n from openprotein.models import Model", + "def f():\n from openprotein.models import Model", + "from openprotein.jobs import Job", + "from . import _api", + ], +) +def test_the_eager_import_check_ignores_lazy_and_local_imports(source): + assert _eager_imports(source, "openprotein.jobs.futures") == [] + + +def test_jobs_imports_models_data_and_search_only_lazily(): + package = Path(jobs.__file__).parent + eager = { + str(path.relative_to(package)): found + for path in sorted(package.rglob("*.py")) + if ( + found := _eager_imports( + path.read_text(), + "openprotein.jobs." + + ".".join(path.relative_to(package).with_suffix("").parts), + ) + ) + } + assert eager == {} + + +@pytest.mark.parametrize( + "first", + [ + "openprotein.jobs", + "openprotein.jobs.futures", + "openprotein.models", + "openprotein.data.prompts", + "openprotein.predictor", + ], +) +def test_each_package_imports_first_in_a_fresh_interpreter(first): + code = ( + f"import {first}\n" + "import openprotein\n" + "from openprotein.jobs import EmbeddingFuture, Future\n" + "from openprotein.jobs._dispatch import create\n" + ) + subprocess.run([sys.executable, "-c", code], check=True) diff --git a/tests/jobs/test_results_by_codec.py b/tests/jobs/test_results_by_codec.py new file mode 100644 index 0000000..18d1752 --- /dev/null +++ b/tests/jobs/test_results_by_codec.py @@ -0,0 +1,179 @@ +"""`/data/results` values decode by the codec their `Ref` names.""" + +import hashlib +import io +import sys +from pathlib import Path +from unittest.mock import MagicMock + +import numpy as np +import pytest + +from openprotein import codecs +from openprotein.codecs import ( + MSA, + Codec, + MSARecord, + PromptComplex, + PromptReplicate, + fasta_utf8_v1, + mmcif_utf8_v1, + msa_parquet_v1, + ndarray_v1, + prompt_npz_v1, +) +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 = { + "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") + return output.value + + +def test_ndarray_v1_decodes_to_an_array(): + expected = np.array([[1.0, np.nan], [np.inf, -np.inf]], dtype=np.float32) + actual = _read(ndarray_v1.encode(expected), "ndarray-v1") + assert actual.dtype == expected.dtype + assert np.array_equal(actual, expected, equal_nan=True) + + +@pytest.mark.parametrize( + "name,shape,values", + [ + ("none", (2,), [1, -2]), + ("one", (2,), [1, -2]), + ("two", (2, 2), [[1, -2], [3, 4]]), + ("selected", (2,), [3, 4]), + ], +) +def test_ndarray_v1_preserves_replicate_array(name, shape, values): + path = ( + Path(__file__).resolve().parents[1] + / "data" + / "model_result_contracts" + / f"replicate_{name}.npy" + ) + actual = _read(path.read_bytes(), "ndarray-v1") + assert actual.dtype.str == "q\nMKV\n"), codec.name) == ">q\nMKV\n" + + +def test_msa_parquet_v1_decodes_to_an_msa(): + pytest.importorskip("pyarrow") + msa = MSA( + records=[MSARecord("query", "MKV"), MSARecord("hit", "MK-")], + source_format="a3m", + num_match_columns=3, + ) + assert _read(msa_parquet_v1.encode(msa), "msa-parquet-v1") == msa + + +def test_msa_parquet_v1_without_pyarrow_names_the_extra(monkeypatch): + monkeypatch.setitem(sys.modules, "pyarrow", None) + monkeypatch.setitem(sys.modules, "pyarrow.parquet", None) + with pytest.raises(ImportError, match=r"openprotein-python\[msa\]"): + _read(b"PAR1", "msa-parquet-v1") + + +def test_prompt_npz_v1_decodes_to_a_prompt_replicate(): + payload = prompt_npz_v1.encode( + PromptReplicate([PromptComplex("MK:LV"), PromptComplex("ACDE")]) + ) + replicate = _read(payload, "prompt-npz-v1") + assert isinstance(replicate, PromptReplicate) + assert [c.sequence for c in replicate.complexes] == ["MK:LV", "ACDE"] + + +@pytest.mark.parametrize("codec", [None, "tests/unknown-v1"]) +def test_null_or_unknown_codec_returns_bytes(codec): + assert _read(b"\x00raw", codec) == b"\x00raw" + + +def test_registered_codec_decodes_its_refs(): + codecs._register( + Codec( + name="tests/measurement-v1", + encode=lambda value: str(value).encode(), + decode=lambda data: float(data) * 2, + ) + ) + assert _read(b"1.25", "tests/measurement-v1") == 2.5 + + +def test_ref_bytes_are_verified_before_decoding(): + session = MagicMock() + session.get.return_value.json.return_value = { + "position": 0, + "unit_id": "unit", + "state": "SUCCESS", + "value": { + "ref": { + "uri": "s3://content/abc", + "byte_length": 3, + "sha256": "0" * 64, + "codec": "fasta-utf8-v1", + } + }, + } + with pytest.raises(ValueError, match="digest"): + _jobs(session, MemoryStorage(b"abc"))._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} + ) diff --git a/tests/jobs/test_submission.py b/tests/jobs/test_submission.py new file mode 100644 index 0000000..8ab280f --- /dev/null +++ b/tests/jobs/test_submission.py @@ -0,0 +1,82 @@ +"""Shared submission retry: a 425 answer is resubmitted, body and key unchanged.""" + +from unittest.mock import MagicMock + +import pytest + +from openprotein.errors import HTTPError +from openprotein.jobs._submission import post_with_retry + + +def _response(status_code: int, headers: dict | None = None) -> MagicMock: + response = MagicMock() + response.status_code = status_code + response.headers = headers or {} + return response + + +def test_post_with_retry_returns_the_first_success(): + session = MagicMock() + session.post.return_value = _response(200) + + response = post_with_retry( + session, "v1/models/m/in/out", json={"a": 1}, headers={"Idempotency-Key": "k"} + ) + + assert response.status_code == 200 + session.post.assert_called_once_with( + "v1/models/m/in/out", json={"a": 1}, headers={"Idempotency-Key": "k"} + ) + + +def test_post_with_retry_resubmits_the_identical_body_and_key_on_425(monkeypatch): + sleeps: list[float] = [] + monkeypatch.setattr( + "openprotein.jobs._submission.time.sleep", + lambda seconds: sleeps.append(seconds), + ) + session = MagicMock() + session.post.side_effect = [ + HTTPError(_response(425, {"Retry-After": "2"})), + _response(200), + ] + + response = post_with_retry( + session, "v1/models/m/in/out", json={"a": 1}, headers={"Idempotency-Key": "k"} + ) + + assert response.status_code == 200 + assert sleeps == [2.0] + calls = session.post.call_args_list + assert calls[0] == calls[1] + + +def test_post_with_retry_gives_up_after_the_bound(monkeypatch): + monkeypatch.setattr("openprotein.jobs._submission.time.sleep", lambda _: None) + session = MagicMock() + session.post.side_effect = HTTPError(_response(425, {"Retry-After": "0"})) + + with pytest.raises(HTTPError) as exc: + post_with_retry( + session, + "v1/models/m/in/out", + json={}, + headers={"Idempotency-Key": "k"}, + max_retries=2, + ) + + assert exc.value.status_code == 425 + assert session.post.call_count == 3 + + +def test_post_with_retry_reraises_other_statuses(): + session = MagicMock() + session.post.side_effect = HTTPError(_response(422)) + + with pytest.raises(HTTPError) as exc: + post_with_retry( + session, "v1/models/m/in/out", json={}, headers={"Idempotency-Key": "k"} + ) + + assert exc.value.status_code == 422 + assert session.post.call_count == 1 diff --git a/tests/jobs/test_unknown_job.py b/tests/jobs/test_unknown_job.py new file mode 100644 index 0000000..f5be484 --- /dev/null +++ b/tests/jobs/test_unknown_job.py @@ -0,0 +1,135 @@ +"""A job type this client has no typed support for stays usable. + +The server can offer job types newer than this client, so resolving one +reports status and raw results, and fails only where typed data is genuinely +unavailable. +""" + +from datetime import datetime +from typing import Any +from unittest.mock import MagicMock + +import pytest +from pydantic import ValidationError + +from openprotein.jobs import _dispatch +from openprotein.jobs.futures import Future, UnknownJobFuture +from openprotein.jobs.schemas import Job, JobStatus, JobType + + +@pytest.fixture +def unknown_job_dict() -> dict[str, Any]: + """A job whose type no installed Future claims.""" + return { + "job_id": "job-unknown-1", + "job_type": "/some/type/added/later", + "status": "SUCCESS", + "created_date": datetime(2026, 9, 10, 12, 0, 0).isoformat(), + } + + +def test_an_unclaimed_job_type_resolves_to_the_fallback(unknown_job_dict) -> None: + future = Future.create(session=MagicMock(), job=Job(**unknown_job_dict)) + assert isinstance(future, UnknownJobFuture) + + +def test_the_fallback_reports_identity_and_status(unknown_job_dict) -> None: + future = Future.create(session=MagicMock(), job=Job(**unknown_job_dict)) + assert future.id == "job-unknown-1" + assert future.job_type == "/some/type/added/later" + assert future.status is JobStatus.SUCCESS + + +def test_the_fallback_names_the_job_type_when_asked_for_typed_results( + unknown_job_dict, +) -> None: + """The error arrives where the capability is missing, not at resolution.""" + future = Future.create(session=MagicMock(), job=Job(**unknown_job_dict)) + with pytest.raises(NotImplementedError, match="/some/type/added/later"): + future.get() + + +def test_a_claimed_job_type_still_resolves_to_its_own_future() -> None: + """The fallback is last resort: a known type is unaffected by it.""" + from openprotein.align.schemas import MSAJob + + job = MSAJob( + job_id="msa-1", + job_type=JobType.align_align, + status=JobStatus.SUCCESS, + created_date=datetime(2026, 9, 10, 12, 0, 0), + ) + future = Future.create(session=MagicMock(), job=job) + assert not isinstance(future, UnknownJobFuture) + assert type(future).__name__ == "MSAFuture" + + +def _models_payload(**overrides: Any) -> dict[str, Any]: + """A `/models` job payload.""" + return { + "job_id": "m-1", + "job_type": "/models", + "status": "SUCCESS", + "created_date": datetime(2026, 9, 10, 12, 0, 0).isoformat(), + } | overrides + + +def test_a_malformed_payload_for_a_known_type_is_not_silently_degraded() -> None: + """A schema error for a typed job type surfaces as a validation error.""" + with pytest.raises(ValidationError): + Job.create(_models_payload(job_type="/align/prompt", status="NOT_A_STATUS")) + + +def test_a_models_payload_loads_as_a_job_with_its_args() -> None: + job = Job.create(_models_payload(args={"model_id": "prompt"})) + assert type(job) is Job + assert _dispatch.is_models_job(job) + assert job.model_dump()["args"] == {"model_id": "prompt"} + + +def test_an_unreadable_response_reports_its_own_error() -> None: + """A body that is not JSON surfaces the decode failure.""" + from requests import Response + + response = Response() + response._content = b"gateway error" + response.status_code = 502 + with pytest.raises(ValueError): + Job.create(response) + + +def test_a_models_job_resolves_to_the_plain_future() -> None: + """The live models path is unaffected by the fallback.""" + job = Job.create(_models_payload(args={"model_id": "prompt"})) + future = Future.create(session=MagicMock(), job=job) + assert type(future) is Future + assert not isinstance(future, UnknownJobFuture) + + +@pytest.mark.parametrize("job_type", ["/models/boltzgen", "/models/rfdiffusion"]) +def test_a_models_type_naming_no_method_resolves_to_the_fallback(job_type) -> None: + """A ``/models/`` type names no method, so it parses as a plain job.""" + job = Job.create(_models_payload(job_type=job_type)) + + assert type(job) is Job + assert isinstance(Future.create(session=MagicMock(), job=job), UnknownJobFuture) + + +@pytest.mark.parametrize( + ("job_type", "future_name"), + [ + ("/models/poet-2/batch/embeddings", "EmbeddingFuture"), + ("/models/svd/fit", "SVDFitFuture"), + ], +) +def test_a_per_model_job_type_loads_as_a_job_and_its_future( + job_type, future_name +) -> None: + """Task-addressed types load as a plain job, keeping type and args.""" + job = Job.create(_models_payload(job_type=job_type, args={"model_id": "poet-2"})) + assert type(job) is Job + assert _dispatch.is_models_job(job) + assert job.job_type == job_type + assert job.model_dump()["args"] == {"model_id": "poet-2"} + future = Future.create(session=MagicMock(), job=job) + assert type(future).__name__ == future_name diff --git a/tests/jobs/test_wait_timeout.py b/tests/jobs/test_wait_timeout.py new file mode 100644 index 0000000..dfb45e5 --- /dev/null +++ b/tests/jobs/test_wait_timeout.py @@ -0,0 +1,80 @@ +"""``wait(timeout=)`` raises ``TimeoutException`` when polls stall past the timeout.""" + +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from unittest.mock import MagicMock, patch + +import pytest +import requests +from urllib3.util.retry import Retry + +from openprotein import auth_store +from openprotein.base import APISession +from openprotein.errors import TimeoutException +from openprotein.jobs import Future, Job + + +class _Stalled(Future): + def _get(self, **kwargs): + return None + + +def _job() -> Job: + return Job.model_validate( + { + "job_id": "j", + "job_type": "/models", + "status": "RUNNING", + "created_date": "2026-10-21T08:00:00Z", + } + ) + + +@pytest.fixture +def stalled_backend(tmp_path, monkeypatch): + class Stalls(BaseHTTPRequestHandler): + def do_GET(self): + time.sleep(1.5) + + def log_message(self, *args): + pass + + server = ThreadingHTTPServer(("127.0.0.1", 0), Stalls) + server.daemon_threads = True + threading.Thread(target=server.serve_forever, daemon=True).start() + monkeypatch.setattr( + "openprotein.base.TokenStore", + lambda *a, **k: auth_store.TokenStore(dir=tmp_path), + ) + login = MagicMock(status_code=200, ok=True, headers={}) + login.json.return_value = { + "access_token": "access", + "refresh_token": "refresh", + "expires_in": 900, + } + with patch.object(APISession, "post", return_value=login): + session = APISession( + "user@x.com", "pw", backend=f"http://127.0.0.1:{server.server_port}/" + ) + session._expires_at = time.time() + 10_000 + try: + yield session + finally: + server.shutdown() + + +def test_a_stalled_poll_past_the_timeout_raises_timeout_exception(stalled_backend): + future = _Stalled(stalled_backend, _job()) + with patch.object(Retry, "sleep"), pytest.raises(TimeoutException): + future.wait_until_done(interval=0, timeout=0.3) + + +def test_a_failed_poll_within_the_timeout_raises_the_request_error(stalled_backend): + stalled_backend.timeout = 0.2 + future = _Stalled(stalled_backend, _job()) + with ( + patch.object(Retry, "sleep"), + pytest.raises(requests.exceptions.RequestException), + ): + future.wait_until_done(interval=0, timeout=600) diff --git a/tests/models/conftest.py b/tests/models/conftest.py new file mode 100644 index 0000000..d604ea9 --- /dev/null +++ b/tests/models/conftest.py @@ -0,0 +1,124 @@ +"""Fixtures serving cards, params and outputs from ``support.ModelsSession``.""" + +from pathlib import Path +from types import SimpleNamespace + +import pytest + +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 + + +@pytest.fixture +def model_card(): + return card + + +@pytest.fixture +def task_outputs(mock_session, monkeypatch): + def make( + future_type, + *, + path="generate/structures", + provider="rfdiffusion", + values=None, + ): + values = values or { + "structures": [ + (Path(__file__).parents[1] / "data" / "test_protein.cif").read_text() + ] + } + primary = next(iter(values)) + job = Job.model_validate( + { + "job_id": "e0b1c3d4-0000-4000-8000-00000000000a", + "job_type": f"/models/{provider}/{path}", + "status": "SUCCESS", + "created_date": "2026-10-21T08:00:00Z", + } + ) + + def entries(self, job_id, output, *, follow=False, interval=5): + name = output or primary + return iter( + SimpleNamespace(position=i, unit_id="shared", value=value) + for i, value in enumerate(values[name]) + ) + + def item(self, job_id, position, output): + return SimpleNamespace( + position=position, + unit_id="shared", + value=values[output][position], + ) + + monkeypatch.setattr(JobsAPI, "_iter_job_outputs", entries) + monkeypatch.setattr(JobsAPI, "_get_job_output", item) + monkeypatch.setattr( + JobsAPI, + "_iter_job_units", + lambda self, job_id: iter( + SimpleNamespace( + position=i, unit_id="shared", status=JobStatus.SUCCESS, error=None + ) + for i in range(len(values[primary])) + ), + ) + monkeypatch.setattr( + jobs_api, "job_default_output", lambda session, job_id: primary + ) + monkeypatch.setattr( + jobs_api, + "get_unit", + lambda session, job_id, position: SimpleNamespace( + status=JobStatus.SUCCESS, + unit_id="shared", + error=None, + ), + ) + monkeypatch.setattr(Future, "_wait_job", lambda self, **kwargs: self.job) + monkeypatch.setattr("openprotein.jobs.futures.time.sleep", lambda seconds: None) + + future = future_type(mock_session, job) + future._resolved_descriptor = MethodDescriptor(path=path, outputs=list(values)) + return future, values + + return make + + +@pytest.fixture +def ensemble_reference(): + path = ( + Path(__file__).parents[1] + / "data" + / "boltzgen_entity_one_letter_missing_residues.cif" + ) + return Complex.from_filepath(path, verbose=False).get_proteins()["A"] + + +@pytest.fixture +def aligned_ensemble_session(models_session, ensemble_reference, monkeypatch): + align = AlignAPI(models_session.session) + monkeypatch.setattr( + align, + "get_seed", + lambda job_id: ensemble_reference.sequence.decode(), + ) + models_session.session.align = align + return models_session diff --git a/tests/models/foundational/test_boltzgen_schema.py b/tests/models/foundational/test_boltzgen_schema.py deleted file mode 100644 index c434958..0000000 --- a/tests/models/foundational/test_boltzgen_schema.py +++ /dev/null @@ -1,314 +0,0 @@ -"""Test the BoltzGen design specification schema.""" - -import pytest -from pydantic import ValidationError - -from openprotein.models.foundation.boltzgen_schema import ( - BoltzGenDesignSpec, - BondConstraint, - Constraint, - DesignInsertion, - Entity, - FileEntity, - LigandEntity, - ProteinEntity, - TotalLengthConstraint, -) - - -class TestProteinEntity: - """Test ProteinEntity schema.""" - - def test_protein_entity_basic(self): - """Test basic protein entity creation.""" - protein = ProteinEntity(id="A", sequence="ACDEFGHIKLMNPQRSTVWY") - assert protein.id == "A" - assert protein.sequence == "ACDEFGHIKLMNPQRSTVWY" - assert protein.cyclic is False - assert protein.secondary_structure is None - assert protein.binding_types is None - - def test_protein_entity_with_design_residues(self): - """Test protein entity with design residue patterns.""" - protein = ProteinEntity(id="G", sequence="15..20AAAAAAVTTTT18PPP") - assert protein.sequence == "15..20AAAAAAVTTTT18PPP" - - def test_protein_entity_with_cyclic(self): - """Test cyclic protein entity.""" - protein = ProteinEntity(id="T", sequence="C10C6C3C", cyclic=True) - assert protein.cyclic is True - - def test_protein_entity_with_binding_types_string(self): - """Test protein entity with binding types as string.""" - protein = ProteinEntity( - id="A", sequence="AAAAAAAAAAAAAAAAAAAAAAAA", binding_types="uuuuBBBuNNNuBuu" - ) - assert protein.binding_types == "uuuuBBBuNNNuBuu" - - def test_protein_entity_with_binding_types_dict(self): - """Test protein entity with binding types as dict.""" - protein = ProteinEntity( - id="B", - sequence="AAAAAAAAAAAAAAAAAAAAAAAA", - binding_types={"binding": "5..7,13", "not_binding": "9..11"}, - ) - assert protein.binding_types == {"binding": "5..7,13", "not_binding": "9..11"} - - def test_protein_entity_with_list_ids(self): - """Test protein entity with multiple chain IDs.""" - protein = ProteinEntity(id=["A", "B"], sequence="ACDEFG") - assert protein.id == ["A", "B"] - - -class TestLigandEntity: - """Test LigandEntity schema.""" - - def test_ligand_entity_with_ccd(self): - """Test ligand entity with CCD code.""" - ligand = LigandEntity(id="Q", ccd="WHL") - assert ligand.id == "Q" - assert ligand.ccd == "WHL" - assert ligand.smiles is None - - def test_ligand_entity_with_smiles(self): - """Test ligand entity with SMILES string.""" - ligand = LigandEntity(id=["E", "F"], smiles="N[C@@H](Cc1ccc(O)cc1)C(=O)O") - assert ligand.id == ["E", "F"] - assert ligand.smiles == "N[C@@H](Cc1ccc(O)cc1)C(=O)O" - assert ligand.ccd is None - - def test_ligand_entity_with_binding_types(self): - """Test ligand entity with binding types.""" - ligand = LigandEntity( - id=["E", "F"], smiles="N[C@@H](Cc1ccc(O)cc1)C(=O)O", binding_types="B" - ) - assert ligand.binding_types == "B" - - def test_ligand_entity_missing_ccd_and_smiles(self): - """Test that ligand entity requires either ccd or smiles.""" - with pytest.raises(ValidationError, match="Either 'ccd' or 'smiles'"): - LigandEntity(id="Q") - - -class TestFileEntity: - """Test FileEntity schema.""" - - def test_file_entity_basic(self): - """Test basic file entity creation.""" - file_entity = FileEntity(path="7rpz.cif", include="all") - assert file_entity.path == "7rpz.cif" - assert file_entity.include == "all" - - def test_file_entity_with_chain_include(self): - """Test file entity with chain inclusion.""" - file_entity = FileEntity( - path="7rpz.cif", include=[{"chain": {"id": "A"}}, {"chain": {"id": "B"}}] - ) - assert isinstance(file_entity.include, list) - assert len(file_entity.include) == 2 - - def test_file_entity_with_fuse(self): - """Test file entity with fuse parameter.""" - file_entity = FileEntity( - path="7rpz.cif", - fuse="A", - include=[{"chain": {"id": "A", "res_index": "..5"}}], - ) - assert file_entity.fuse == "A" - - def test_file_entity_with_all_options(self): - """Test file entity with multiple options.""" - file_entity = FileEntity( - path="7rpz.cif", - include=[{"chain": {"id": "A"}}], - exclude=[{"chain": {"id": "A", "res_index": "..5"}}], - binding_types=[{"chain": {"id": "A", "binding": "5..7,13"}}], - structure_groups=[ - {"group": {"visibility": 1, "id": "A", "res_index": "10..16"}} - ], - design=[{"chain": {"id": "A", "res_index": "..4,20..27"}}], - secondary_structure=[{"chain": {"id": "A", "loop": "1", "helix": "2..3"}}], - design_insertions=[ - { - "insertion": { - "id": "A", - "res_index": 20, - "num_residues": "2..9", - "secondary_structure": "HELIX", - } - } - ], - ) - assert file_entity.path == "7rpz.cif" - assert file_entity.design is not None - assert file_entity.secondary_structure is not None - - -class TestEntity: - """Test Entity wrapper schema.""" - - def test_entity_with_protein(self): - """Test entity with protein.""" - entity = Entity(protein=ProteinEntity(id="A", sequence="ACDEFG")) - assert entity.protein is not None - assert entity.ligand is None - assert entity.file is None - - def test_entity_with_ligand(self): - """Test entity with ligand.""" - entity = Entity(ligand=LigandEntity(id="B", ccd="ATP")) - assert entity.protein is None - assert entity.ligand is not None - assert entity.file is None - - def test_entity_with_file(self): - """Test entity with file.""" - entity = Entity(file=FileEntity(path="test.cif", include="all")) - assert entity.protein is None - assert entity.ligand is None - assert entity.file is not None - - def test_entity_requires_exactly_one(self): - """Test that entity requires exactly one entity type.""" - with pytest.raises(ValidationError, match="Exactly one"): - Entity() - - with pytest.raises(ValidationError, match="Exactly one"): - Entity( - protein=ProteinEntity(id="A", sequence="ACDEFG"), - ligand=LigandEntity(id="B", ccd="ATP"), - ) - - -class TestConstraints: - """Test constraint schemas.""" - - def test_bond_constraint(self): - """Test bond constraint creation.""" - bond = BondConstraint(atom1=["R", 4, "SG"], atom2=["Q", 1, "CK"]) - assert bond.atom1 == ["R", 4, "SG"] - assert bond.atom2 == ["Q", 1, "CK"] - - def test_bond_constraint_invalid_length(self): - """Test that bond constraint requires exactly 3 elements.""" - with pytest.raises(ValidationError): - BondConstraint(atom1=["R", 4], atom2=["Q", 1, "CK"]) - - def test_total_length_constraint(self): - """Test total length constraint creation.""" - total_len = TotalLengthConstraint(min=10, max=20) - assert total_len.min == 10 - assert total_len.max == 20 - - def test_constraint_with_bond(self): - """Test constraint wrapper with bond.""" - constraint = Constraint( - bond=BondConstraint(atom1=["R", 4, "SG"], atom2=["Q", 1, "CK"]) - ) - assert constraint.bond is not None - assert constraint.total_len is None - - def test_constraint_with_total_len(self): - """Test constraint wrapper with total length.""" - constraint = Constraint(total_len=TotalLengthConstraint(min=10, max=20)) - assert constraint.bond is None - assert constraint.total_len is not None - - def test_constraint_requires_at_least_one(self): - """Test that constraint requires at least one constraint type.""" - with pytest.raises(ValidationError, match="At least one constraint"): - Constraint() - - -class TestBoltzGenDesignSpec: - """Test complete BoltzGen design specification.""" - - def test_design_spec_minimal(self): - """Test minimal design spec with one entity.""" - spec = BoltzGenDesignSpec( - entities=[Entity(protein=ProteinEntity(id="A", sequence="ACDEFG"))] - ) - assert len(spec.entities) == 1 - assert spec.constraints is None - - def test_design_spec_with_constraints(self): - """Test design spec with entities and constraints.""" - spec = BoltzGenDesignSpec( - entities=[ - Entity(protein=ProteinEntity(id="A", sequence="ACDEFG")), - Entity(ligand=LigandEntity(id="B", ccd="ATP")), - ], - constraints=[ - Constraint( - bond=BondConstraint(atom1=["A", 10, "CA"], atom2=["B", 1, "O"]) - ) - ], - ) - assert len(spec.entities) == 2 - assert isinstance(spec.constraints, list) - assert len(spec.constraints) == 1 - - def test_design_spec_empty_entities(self): - """Test that design spec requires at least one entity.""" - with pytest.raises(ValidationError, match="At least one entity"): - BoltzGenDesignSpec(entities=[]) - - def test_design_spec_from_dict(self): - """Test creating design spec from dict.""" - data = { - "entities": [ - {"protein": {"id": "A", "sequence": "ACDEFG"}}, - {"ligand": {"id": "B", "ccd": "ATP"}}, - ], - "constraints": [ - {"bond": {"atom1": ["A", 10, "CA"], "atom2": ["B", 1, "O"]}} - ], - } - spec = BoltzGenDesignSpec.model_validate(data) - assert len(spec.entities) == 2 - assert isinstance(spec.constraints, list) - assert len(spec.constraints) == 1 - - def test_design_spec_round_trip(self): - """Test round-trip conversion (dict -> model -> dict).""" - original_data = { - "entities": [ - {"protein": {"id": "A", "sequence": "ACDEFG"}}, - {"ligand": {"id": "B", "ccd": "ATP"}}, - ], - "constraints": [ - {"bond": {"atom1": ["A", 10, "CA"], "atom2": ["B", 1, "O"]}} - ], - } - spec = BoltzGenDesignSpec.model_validate(original_data) - spec_dict = spec.model_dump(exclude_none=True) - spec2 = BoltzGenDesignSpec.model_validate(spec_dict) - assert len(spec2.entities) == len(spec.entities) - assert isinstance(spec2.constraints, list) - assert isinstance(spec.constraints, list) - assert len(spec2.constraints) == len(spec.constraints) - - def test_design_spec_complex_example(self): - """Test complex design spec with multiple entity types.""" - data = { - "entities": [ - {"protein": {"id": "G", "sequence": "15..20AAAAAAVTTTT18PPP"}}, - {"protein": {"id": "R", "sequence": "3..5C6C3"}}, - {"ligand": {"id": "Q", "ccd": "WHL"}}, - {"protein": {"id": "S", "sequence": "10C6C3"}}, - {"protein": {"id": "T", "sequence": "C10C6C3C", "cyclic": True}}, - ], - "constraints": [ - {"bond": {"atom1": ["R", 4, "SG"], "atom2": ["Q", 1, "CK"]}}, - {"bond": {"atom1": ["R", 11, "SG"], "atom2": ["Q", 1, "CH"]}}, - {"bond": {"atom1": ["S", 11, "SG"], "atom2": ["S", 18, "SG"]}}, - {"bond": {"atom1": ["T", 12, "SG"], "atom2": ["T", 19, "SG"]}}, - {"total_len": {"min": 10, "max": 20}}, - ], - } - spec = BoltzGenDesignSpec.model_validate(data) - assert len(spec.entities) == 5 - assert isinstance(spec.constraints, list) - assert len(spec.constraints) == 5 - assert spec.entities[4].protein is not None - assert spec.entities[4].protein.cyclic is True diff --git a/tests/models/foundational/test_esmif1.py b/tests/models/foundational/test_esmif1.py deleted file mode 100644 index 55ae855..0000000 --- a/tests/models/foundational/test_esmif1.py +++ /dev/null @@ -1,243 +0,0 @@ -"""Tests for the ESM-IF1 foundation model.""" - -from unittest.mock import MagicMock, patch - -import pytest - -from openprotein.embeddings.future import EmbeddingsScoreSingleSiteFuture -from openprotein.embeddings.schemas import ScoreSingleSiteJob -from openprotein.jobs import JobStatus -from openprotein.models.foundation.esmif1 import ESMIF1Model -from openprotein.models.structure_generation import ( - StructureGenerationFuture, - StructureGenerationJob, -) -from openprotein.prompt import PromptAPI - -# 1UBQ (ubiquitin) native sequence, 76 residues, single chain. -UBQ_NATIVE_SEQ = ( - b"MQIFVKTLTGKTITLEVEPSDTIENVKAKIQDKEGIPPDQQRLIFAGKQLEDGRTLSDYNIQKESTLHLVLRLRGG" -) -assert len(UBQ_NATIVE_SEQ) == 76 - -# Real UUIDs (rather than `"query-123"`-style stubs) so reviewers see -# what an actual server response looks like. Specific values are arbitrary; -# only their shape matters to the SDK forwarding logic these tests cover. -QUERY_ID = "9305b5de-9c9b-4313-95b9-2efb635cb908" -DESIGN_ID = "a1b2c3d4-5678-90ab-cdef-1234567890ab" -DESIGN_JOB_ID = "fb7e0c1a-2c33-4d6e-b8a9-7e5d4f2a1b6c" - -# Bytes form of `query=` accepts raw structure-file content -CIF_BYTES_STUB = ( - b"data_1UBQ\n" - b"_entry.id 1UBQ\n" - b"loop_\n" - b"_atom_site.group_PDB\n" - b"_atom_site.id\n" - b"...\n" -) - - -@pytest.fixture -def mock_model_session(): - """Mocked API session configured for ESM-IF1 tests.""" - session = MagicMock() - session.prompt = MagicMock(spec=PromptAPI) - session.prompt._resolve_query.return_value = QUERY_ID - session.get.return_value.json.return_value = { - "model_id": "esm-if1", - "description": { - "summary": ( - "ESM Inverse Folding: structure-conditioned encoder + " - "autoregressive decoder. Score sequences against coordinates " - "or generate new sequences from a structure." - ), - }, - "dimension": -1, - "output_types": ["score", "generate"], - "input_tokens": list("ACDEFGHIKLMNPQRSTVWY"), - "token_descriptions": [], - "max_sequence_length": 500, - } - return session - - -def test_score_forwards_query_and_sequences(mock_model_session: MagicMock): - """score() resolves query and forwards sequences + query_id to the API.""" - model = ESMIF1Model(session=mock_model_session) - sequences = [UBQ_NATIVE_SEQ] - - with ( - patch( - "openprotein.models.foundation.esmif1.embeddings_api.request_score_post", - return_value=MagicMock(), - ) as mock_post, - patch( - "openprotein.models.foundation.esmif1.EmbeddingsScoreFuture.create", - return_value=MagicMock(), - ), - ): - model.score(sequences=sequences, query=CIF_BYTES_STUB) - - mock_model_session.prompt._resolve_query.assert_called_once_with( - query=CIF_BYTES_STUB - ) - _, kwargs = mock_post.call_args - assert kwargs["model_id"] == "esm-if1" - assert kwargs["sequences"] == sequences - assert kwargs["query_id"] == QUERY_ID - - -def test_single_site_forwards_query_and_returns_single_site_future( - mock_model_session: MagicMock, -): - """single_site() forwards base_sequence + query_id and returns the single-site future. - - The job-type factory in Future.create dispatches a poet_single_site job to - EmbeddingsScoreSingleSiteFuture regardless of which Future subclass `.create` - is called on, so this also pins the declared return type to the concrete type. - """ - model = ESMIF1Model(session=mock_model_session) - job = ScoreSingleSiteJob( - job_id="11111111-2222-3333-4444-555555555555", - status=JobStatus.PENDING, - created_date="2026-01-01T00:00:00", - ) - - with patch( - "openprotein.models.foundation.esmif1.embeddings_api.request_score_single_site_post", - return_value=job, - ) as mock_post: - future = model.single_site(sequence=UBQ_NATIVE_SEQ, query=CIF_BYTES_STUB) - - mock_model_session.prompt._resolve_query.assert_called_once_with( - query=CIF_BYTES_STUB - ) - _, kwargs = mock_post.call_args - assert kwargs["model_id"] == "esm-if1" - assert kwargs["base_sequence"] == UBQ_NATIVE_SEQ - assert kwargs["query_id"] == QUERY_ID - assert isinstance(future, EmbeddingsScoreSingleSiteFuture) - - -def test_generate_forwards_query_and_sampling_params(mock_model_session: MagicMock): - """generate() forwards query_id, num_samples, temperature, and seed.""" - model = ESMIF1Model(session=mock_model_session) - - with ( - patch( - "openprotein.models.foundation.esmif1.embeddings_api.request_generate_post", - return_value=MagicMock(), - ) as mock_post, - patch( - "openprotein.models.foundation.esmif1.EmbeddingsGenerateFuture.create", - return_value=MagicMock(), - ), - ): - model.generate( - query=CIF_BYTES_STUB, - num_samples=5, - temperature=0.5, - seed=42, - ) - - mock_model_session.prompt._resolve_query.assert_called_once_with( - query=CIF_BYTES_STUB - ) - _, kwargs = mock_post.call_args - assert kwargs["model_id"] == "esm-if1" - assert kwargs["query_id"] == QUERY_ID - assert kwargs["num_samples"] == 5 - assert kwargs["temperature"] == 0.5 - assert kwargs["random_seed"] == 42 - - -def test_generate_with_design_id_without_query(mock_model_session: MagicMock): - """generate() forwards design_id when query is omitted.""" - model = ESMIF1Model(session=mock_model_session) - - with ( - patch( - "openprotein.models.foundation.esmif1.embeddings_api.request_generate_post", - return_value=MagicMock(), - ) as mock_post, - patch( - "openprotein.models.foundation.esmif1.EmbeddingsGenerateFuture.create", - return_value=MagicMock(), - ), - ): - model.generate(design=DESIGN_ID, num_samples=5) - - mock_model_session.prompt._resolve_query.assert_not_called() - _, kwargs = mock_post.call_args - assert kwargs["model_id"] == "esm-if1" - assert kwargs["design_id"] == DESIGN_ID - assert kwargs["query_id"] is None - assert kwargs["num_samples"] == 5 - - -def test_generate_with_structure_generation_future(mock_model_session: MagicMock): - """generate() extracts design_id from a StructureGenerationFuture.""" - model = ESMIF1Model(session=mock_model_session) - design_future = StructureGenerationFuture( - session=mock_model_session, - job=StructureGenerationJob( - job_id=DESIGN_JOB_ID, - job_type="/models/design", - status=JobStatus.SUCCESS, - created_date="2026-01-01T00:00:00", - ), - N=1, - result_format="pdb", - ) - - with ( - patch( - "openprotein.models.foundation.esmif1.embeddings_api.request_generate_post", - return_value=MagicMock(), - ) as mock_post, - patch( - "openprotein.models.foundation.esmif1.EmbeddingsGenerateFuture.create", - return_value=MagicMock(), - ), - ): - model.generate(design=design_future, num_samples=2) - - mock_model_session.prompt._resolve_query.assert_not_called() - _, kwargs = mock_post.call_args - assert kwargs["design_id"] == DESIGN_JOB_ID - assert kwargs["query_id"] is None - - -def test_generate_with_both_query_and_design(mock_model_session: MagicMock): - """generate() forwards both ids when both are provided.""" - model = ESMIF1Model(session=mock_model_session) - - with ( - patch( - "openprotein.models.foundation.esmif1.embeddings_api.request_generate_post", - return_value=MagicMock(), - ) as mock_post, - patch( - "openprotein.models.foundation.esmif1.EmbeddingsGenerateFuture.create", - return_value=MagicMock(), - ), - ): - model.generate(query=CIF_BYTES_STUB, design=DESIGN_ID) - - mock_model_session.prompt._resolve_query.assert_called_once_with( - query=CIF_BYTES_STUB - ) - _, kwargs = mock_post.call_args - assert kwargs["query_id"] == QUERY_ID - assert kwargs["design_id"] == DESIGN_ID - - -def test_generate_requires_query_or_design(mock_model_session: MagicMock): - """generate() validates that at least one of query or design is provided.""" - model = ESMIF1Model(session=mock_model_session) - with pytest.raises( - ValueError, - match="Expected either `query` or `design` to be provided", - ): - model.generate() diff --git a/tests/models/foundational/test_proteinmpnn.py b/tests/models/foundational/test_proteinmpnn.py deleted file mode 100644 index d6fabfc..0000000 --- a/tests/models/foundational/test_proteinmpnn.py +++ /dev/null @@ -1,113 +0,0 @@ -"""Tests for the ProteinMPNN foundation model.""" - -from unittest.mock import MagicMock, patch - -import pytest - -from openprotein.jobs import JobStatus -from openprotein.models.foundation.proteinmpnn import ProteinMPNNModel -from openprotein.models.structure_generation import ( - StructureGenerationFuture, - StructureGenerationJob, -) -from openprotein.prompt import PromptAPI - - -@pytest.fixture -def mock_model_session(): - """Create a mocked API session configured for ProteinMPNN tests.""" - session = MagicMock() - session.prompt = MagicMock(spec=PromptAPI) - session.prompt._resolve_query.return_value = "query-123" - session.get.return_value.json.return_value = { - "model_id": "proteinmpnn", - "description": {"summary": "ProteinMPNN"}, - "dimension": 0, - "output_types": ["sequence"], - "input_tokens": ["protein"], - "token_descriptions": [], - "max_sequence_length": 1024, - } - return session - - -def test_generate_with_design_id_without_query(mock_model_session: MagicMock): - """ProteinMPNN generate forwards design_id when query is omitted.""" - model = ProteinMPNNModel(session=mock_model_session) - - with patch( - "openprotein.models.foundation.proteinmpnn.embeddings_api.request_generate_post", - return_value=MagicMock(), - ) as mock_request_post, patch( - "openprotein.models.foundation.proteinmpnn.EmbeddingsGenerateFuture.create", - return_value=MagicMock(), - ): - model.generate(design="design-abc", num_samples=5) - - mock_model_session.prompt._resolve_query.assert_not_called() - _, kwargs = mock_request_post.call_args - assert kwargs["design_id"] == "design-abc" - assert kwargs["query_id"] is None - assert kwargs["num_samples"] == 5 - - -def test_generate_with_query_list_without_query(mock_model_session: MagicMock): - """ProteinMPNN generate forwards list-valued query via query_id.""" - model = ProteinMPNNModel(session=mock_model_session) - mock_model_session.prompt._resolve_query.return_value = ["q-1", "q-2"] - - with patch( - "openprotein.models.foundation.proteinmpnn.embeddings_api.request_generate_post", - return_value=MagicMock(), - ) as mock_request_post, patch( - "openprotein.models.foundation.proteinmpnn.EmbeddingsGenerateFuture.create", - return_value=MagicMock(), - ): - model.generate(query=["q-1", "q-2"], num_samples=3) - - mock_model_session.prompt._resolve_query.assert_called_once_with( - query=["q-1", "q-2"] - ) - _, kwargs = mock_request_post.call_args - assert kwargs["query_id"] == ["q-1", "q-2"] - assert kwargs["num_samples"] == 3 - - -def test_generate_with_structure_generation_future(mock_model_session: MagicMock): - """ProteinMPNN generate extracts design_id from StructureGenerationFuture.""" - model = ProteinMPNNModel(session=mock_model_session) - design_future = StructureGenerationFuture( - session=mock_model_session, - job=StructureGenerationJob( - job_id="design-job-789", - job_type="/models/design", - status=JobStatus.SUCCESS, - created_date="2026-01-01T00:00:00", - ), - N=1, - result_format="pdb", - ) - - with patch( - "openprotein.models.foundation.proteinmpnn.embeddings_api.request_generate_post", - return_value=MagicMock(), - ) as mock_request_post, patch( - "openprotein.models.foundation.proteinmpnn.EmbeddingsGenerateFuture.create", - return_value=MagicMock(), - ): - model.generate(query=b"ACDE", design=design_future) - - mock_model_session.prompt._resolve_query.assert_called_once_with(query=b"ACDE") - _, kwargs = mock_request_post.call_args - assert kwargs["design_id"] == "design-job-789" - assert kwargs["query_id"] == "query-123" - - -def test_generate_requires_query_or_design(mock_model_session: MagicMock): - """ProteinMPNN generate validates at least one input source.""" - model = ProteinMPNNModel(session=mock_model_session) - with pytest.raises( - ValueError, - match="Expected either `query` or `design` to be provided", - ): - model.generate() diff --git a/tests/models/foundational/test_structure_generation.py b/tests/models/foundational/test_structure_generation.py deleted file mode 100644 index fe3fa2d..0000000 --- a/tests/models/foundational/test_structure_generation.py +++ /dev/null @@ -1,56 +0,0 @@ -"""Tests for shared structure-generation futures.""" - -from unittest.mock import MagicMock, patch - -import pytest - -from openprotein.jobs import JobStatus -from openprotein.models.foundation.boltzgen import BoltzGenFuture -from openprotein.models.foundation.rfdiffusion import RFdiffusionFuture -from openprotein.models.structure_generation import ( - StructureGenerationFuture, - StructureGenerationJob, -) - - -def _make_job() -> StructureGenerationJob: - return StructureGenerationJob( - job_id="design-job-1", - job_type="/models/design", - status=JobStatus.SUCCESS, - created_date="2026-01-01T00:00:00", - ) - - -def test_structure_generation_future_get_item_uses_result_format(): - """The shared future fetches a replicate and parses it with configured format.""" - session = MagicMock() - session.get.return_value.text = "MOCK_STRUCTURE_TEXT" - future = StructureGenerationFuture( - session=session, job=_make_job(), N=1, result_format="cif" - ) - - with patch( - "openprotein.models.structure_generation.Complex.from_string", - return_value=MagicMock(), - ) as mock_from_string: - future.get_item(0) - - session.get.assert_called_once_with( - "v1/design/design-job-1/results", params={"replicate": 0} - ) - mock_from_string.assert_called_once_with("MOCK_STRUCTURE_TEXT", format="cif") - - -def test_rfdiffusion_future_emits_deprecation_warning(): - """RFdiffusionFuture remains as a deprecated alias.""" - session = MagicMock() - with pytest.warns(DeprecationWarning, match="RFdiffusionFuture is deprecated"): - RFdiffusionFuture(session=session, job=_make_job(), N=1, result_format="pdb") - - -def test_boltzgen_future_emits_deprecation_warning(): - """BoltzGenFuture remains as a deprecated alias.""" - session = MagicMock() - with pytest.warns(DeprecationWarning, match="BoltzGenFuture is deprecated"): - BoltzGenFuture(session=session, job=_make_job(), N=1, result_format="cif") diff --git a/tests/models/support.py b/tests/models/support.py new file mode 100644 index 0000000..cb43cd2 --- /dev/null +++ b/tests/models/support.py @@ -0,0 +1,222 @@ +"""A session serving the models API's cards and params, and checking submissions. + +``tests/data/models_params.json`` holds each method's params JSON Schema and +outputs, keyed ``/`` (fitted families as ``gp/...``, +``svd/...``, ``umap/...``), and the fit bodies under ``fits``. Every body +posted through ``ModelsSession`` is checked against its schema. +""" + +import hashlib +import itertools +import json +from pathlib import Path +from typing import Any +from unittest.mock import MagicMock + +from jsonschema import Draft202012Validator, FormatChecker + +from openprotein import codecs +from openprotein.base import APISession +from openprotein.prompt import PromptAPI + +PARAMS = json.loads( + (Path(__file__).parents[1] / "data" / "models_params.json").read_text() +) +FITTED_FAMILIES = ("gp", "svd", "umap") + +_ALL_CHAINS = ["protein", "dna", "rna", "ligand"] + +#: the inputs each structure prediction card names +CARD_FACTS: dict[str, dict[str, Any]] = { + "esmfold": {"input_types": ["protein"], "multichain": True}, + "minifold": {"input_types": ["protein"], "multichain": False}, + "alphafold2": {"input_types": ["protein"], "multichain": True}, + "rosettafold-3": {"input_types": ["protein", "ligand"], "multichain": True}, + **{ + model_id: {"input_types": _ALL_CHAINS, "multichain": True} + for model_id in ( + "boltz-1", + "boltz-1x", + "boltz-2", + "protenix", + "protenix-v2", + "esmfold2", + "esmfold2-fast", + "opendde", + "opendde-abag", + ) + }, +} +CARD_FACTS.update( + json.loads((Path(__file__).parents[1] / "data" / "ensemble_cards.json").read_text()) +) + +SUBMITTED_JOB: dict[str, Any] = { + "job_id": "e0b1c3d4-0000-4000-8000-00000000000a", + "job_type": "/models", + "status": "SUCCESS", + "created_date": "2026-10-21T08:00:00Z", +} + + +def created_query(n: int) -> str: + """The id ``ModelsSession`` gives the ``n``-th query created, from 1.""" + return f"aaaaaaaa-0000-4000-8000-{n:012d}" + + +def _family(model_id: str) -> str: + family = model_id.split("/", 1)[0] + return family if family in FITTED_FAMILIES and "/" in model_id else model_id + + +def card(model_id: str) -> dict[str, Any]: + """The model's card, listing the methods the params fixture has for it.""" + prefix = f"{_family(model_id)}/" + methods = [ + {"path": key.removeprefix(prefix), "outputs": method["outputs"]} + for key, method in PARAMS["methods"].items() + if key.startswith(prefix) + ] + return { + "model_id": model_id, + "description": {"summary": model_id}, + "dimension": 1, + "max_sequence_length": 1024, + "methods": methods, + **CARD_FACTS.get(model_id, {}), + } + + +def _schema(path: str) -> dict[str, Any]: + """The params schema a ``POST v1/models/...`` path submits against.""" + route = path.removeprefix("v1/models/") + if route in PARAMS["fits"]: + return PARAMS["fits"][route] + if route.startswith("gp/") and route.endswith("/crossvalidate"): + return PARAMS["fits"]["gp/crossvalidate"] + # every method path in the fixture is two segments, so the model id is the rest + model, first, last = route.rsplit("/", 2) + key = f"{_family(model)}/{first}/{last}" + assert key in PARAMS["methods"], f"the model listing has no method {key}" + return PARAMS["methods"][key]["params"] + + +def check_body(path: str, body: dict[str, Any]) -> None: + """Raise unless the params schema for ``path`` accepts ``body``. + + Every key must be a declared param, whether or not the schema forbids + extras. A UMAP fit that lists sequences takes at least + ``max(3, n_components + 2)`` of them. + """ + schema = _schema(path) + Draft202012Validator(schema, format_checker=FormatChecker()).validate(body) + undeclared = set(body) - set(schema.get("properties", {})) + assert not undeclared, f"{path} declares no {sorted(undeclared)}" + if path == "v1/models/umap" and "sequences" in body: + minimum = max(3, body.get("n_components", 2) + 2) + assert len(body["sequences"]) >= minimum, f"UMAP fit needs {minimum}" + + +class Stored: + """An output value stored as a ref, encoded by ``codec``; None stores bytes.""" + + def __init__(self, codec: str | None, value: Any): + if codec is None: + self.data = value + else: + registered = codecs.get(codec) + assert registered is not None, f"no codec {codec}" + self.data = registered.encode(value) + self.codec = codec + + +class ModelsSession: + """Serves cards and outputs; ``post`` answers a query upload with a new id. + + ``outputs[(job_id, output)]`` lists one value per position: a ``Stored`` + ref, or an inline value. + """ + + def __init__(self): + self.session = MagicMock(spec=APISession) + self.session.timeout = 180 + self.session.headers = {} + self.session.prompt = PromptAPI(self.session) + self.queries: list[tuple[str, bytes]] = [] + self._query_ids = (created_query(n) for n in itertools.count(1)) + self.session.post.side_effect = self._post + self.session.get.side_effect = self._get + self.get_routes: dict[str, Any] = {} + self.post_routes: dict[str, Any] = {} + self.outputs: dict[tuple[str, str], list[Any]] = {} + self.blobs: dict[str, bytes] = {} + + def _response(self, body: Any) -> MagicMock: + response = MagicMock(status_code=200) + response.json.return_value = body + return response + + def _post(self, path: str, **kwargs: Any) -> MagicMock: + if path == "v1/prompt/query": + filename, content, _ = kwargs["files"]["query"] + self.queries.append((filename, content.read())) + return self._response( + {"id": next(self._query_ids), "created_date": "2026-10-21T08:00:00Z"} + ) + check_body(path, kwargs["json"]) + return self._response(self.post_routes.get(path, SUBMITTED_JOB)) + + 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 + return { + "ref": { + "uri": uri, + "byte_length": len(value.data), + "sha256": hashlib.sha256(value.data).hexdigest(), + "codec": value.codec, + } + } + + def _results(self, job_id: str, output: str) -> dict[str, Any]: + return { + "output": output, + "values": [ + { + "position": position, + "unit_id": f"u{position}", + "value": self._value(job_id, output, position), + } + for position in range(len(self.outputs[(job_id, output)])) + ], + "next_cursor": None, + } + + def _get(self, path: str, **kwargs: Any) -> MagicMock: + if path in self.get_routes: + return self._response(self.get_routes[path]) + if path.startswith("v1/data/results/"): + job_id, _, output = path.removeprefix("v1/data/results/").partition("/") + if not output: + output = next(o for j, o in self.outputs if j == job_id) + return self._response(self._results(job_id, output)) + if path.startswith("v1/models/") and path.endswith("/params"): + return self._response(_schema(path.removesuffix("/params"))) + return self._response(card(path.removeprefix("v1/models/"))) + + @property + def submissions(self) -> list[tuple[str, Any]]: + """``(path, body)`` of every post other than a query upload.""" + return [ + (call.args[0], call.kwargs.get("json")) + for call in self.session.post.call_args_list + if call.args[0] != "v1/prompt/query" + ] + + @property + def submitted(self) -> tuple[str, Any]: + (submission,) = self.submissions + return submission diff --git a/tests/models/test_deprecated_names.py b/tests/models/test_deprecated_names.py new file mode 100644 index 0000000..cac5ecb --- /dev/null +++ b/tests/models/test_deprecated_names.py @@ -0,0 +1,147 @@ +import importlib + +import pytest + +import openprotein.models.models as models_module +from openprotein import models +from openprotein.models import ModelsAPI + +MOVED = [ + *( + ("openprotein.fold", name) + for name in ( + "AlphaFold2Model", + "Boltz1Model", + "Boltz1xModel", + "Boltz2Model", + "ESMFold2FastModel", + "ESMFold2Model", + "ESMFoldModel", + "MiniFoldModel", + "ProtenixModel", + "ProtenixV2Model", + "RosettaFold3Model", + ) + ), + *( + ("openprotein.embeddings", name) + for name in ("ESMModel", "OpenProteinModel", "PoET2Model", "PoETModel") + ), +] + +RENAMED = [ + ("BoltzGenModel", "BoltzGen"), + ("ESMIF1Model", "ESMIF1"), + ("ProteinMPNNModel", "ProteinMPNN"), + ("RFdiffusionModel", "RFdiffusion"), +] + + +def _message(name: str, use: str) -> str: + return ( + f"`{name}` is deprecated since 0.18.0 and will be removed in 0.19.0. Use {use}." + ) + + +@pytest.mark.parametrize(("module", "name"), MOVED) +def test_moved_model_names_resolve_to_their_new_module_and_warn(module, name): + with pytest.warns(FutureWarning) as record: + resolved = getattr(models, name) + assert resolved is getattr(importlib.import_module(module), name) + assert [str(w.message) for w in record] == [ + _message(f"openprotein.models.{name}", f"`{module}.{name}`") + ] + assert record[0].filename == __file__ + + +@pytest.mark.parametrize(("old", "new"), RENAMED) +def test_renamed_model_names_resolve_to_the_new_name_and_warn(old, new): + with pytest.warns(FutureWarning) as record: + resolved = getattr(models, old) + assert resolved is getattr(models, new) + assert [str(w.message) for w in record] == [ + _message(f"openprotein.models.{old}", f"`openprotein.models.{new}`") + ] + + +@pytest.mark.parametrize(("old", "new"), RENAMED) +def test_renamed_names_on_the_models_module_resolve_and_warn(old, new): + with pytest.warns(FutureWarning) as record: + resolved = getattr(models_module, old) + assert resolved is getattr(models, new) + assert [str(w.message) for w in record] == [ + _message(f"openprotein.models.models.{old}", f"`openprotein.models.{new}`") + ] + + +def test_from_import_of_a_deprecated_name_warns(): + with pytest.warns(FutureWarning, match="openprotein.models.ESMModel"): + from openprotein.models import ESMModel # noqa: F401 + + +@pytest.mark.parametrize("module", [models, models_module]) +def test_unknown_names_raise_attribute_error(module): + with pytest.raises(AttributeError): + module.__getattr__("NotAModel") + + +@pytest.mark.parametrize( + ("module", "path"), + [(models, "openprotein.models"), (models_module, "openprotein.models.models")], +) +def test_soluble_mpnn_model_builds_a_solublempnn_proteinmpnn( + module, path, mock_session +): + with pytest.warns(FutureWarning) as record: + resolved = getattr(module, "SolubleMPNNModel") + assert [str(w.message) for w in record] == [ + _message(f"{path}.SolubleMPNNModel", "`session.models.solublempnn`") + ] + handle = resolved(mock_session) + assert isinstance(handle, models.ProteinMPNN) + assert handle.id == "solublempnn" + + +def test_deprecated_names_are_not_in_all(): + deprecated = ( + {name for _, name in MOVED} | {old for old, _ in RENAMED} | {"SolubleMPNNModel"} + ) + assert deprecated.isdisjoint(models.__all__) + + +QUERY_UUID = "c0ffee00-0000-4000-8000-000000000001" + + +@pytest.mark.parametrize("model", ["esmif1", "proteinmpnn", "solublempnn"]) +def test_inverse_folding_generate_takes_seed_as_random_seed(models_session, model): + handle = getattr(ModelsAPI(models_session.session), model) + with pytest.warns( + FutureWarning, match=r"generate\(seed=\.\.\.\).*0\.18\.0.*0\.19\.0" + ): + handle.generate(query=QUERY_UUID, seed=7) + assert models_session.submitted[1]["random_seed"] == 7 + assert "seed" not in models_session.submitted[1] + + +@pytest.mark.parametrize("model", ["esmif1", "proteinmpnn"]) +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=\.\.\.\)"): + handle.single_site(sequence="MKT", query=QUERY_UUID) + assert models_session.submitted[1]["base_sequence"] == "MKT" + + +@pytest.mark.parametrize( + "call", + [ + lambda m: m.esmif1.generate(query=QUERY_UUID, seed=1, random_seed=2), + lambda m: m.esmif1.single_site("MKT", sequence="MKT", query=QUERY_UUID), + ], + ids=["generate", "single_site"], +) +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() diff --git a/tests/models/test_empty_sources.py b/tests/models/test_empty_sources.py new file mode 100644 index 0000000..74b9afb --- /dev/null +++ b/tests/models/test_empty_sources.py @@ -0,0 +1,35 @@ +"""A verb takes a query or a design, not both, and refuses an empty query.""" + +import pytest + +from openprotein.jobs import Future, Job +from openprotein.models import ModelsAPI +from tests.models.support import SUBMITTED_JOB +from tests.models.test_handles import DESIGN_UUID, QUERY_UUID + + +def _design(session) -> Future: + job = Job.create( + SUBMITTED_JOB + | {"job_id": DESIGN_UUID, "job_type": "/models/rfdiffusion/generate/structures"} + ) + return Future.create(session.session, job=job) + + +class TestStructureSources: + def test_a_query_and_a_design_are_refused_together(self, models_session): + models = ModelsAPI(models_session.session) + + with pytest.raises(TypeError, match="pass query or design, not both"): + models.poet2.generate(query=QUERY_UUID, design=_design(models_session)) + + assert models_session.queries == [] + assert models_session.submissions == [] + + def test_an_empty_query_is_refused(self, models_session): + models = ModelsAPI(models_session.session) + + with pytest.raises(ValueError, match="query has no entries; pass query=None"): + models.poet2.generate(query=[]) + + assert models_session.submissions == [] diff --git a/tests/models/test_ensemble_contracts.py b/tests/models/test_ensemble_contracts.py new file mode 100644 index 0000000..650f1b9 --- /dev/null +++ b/tests/models/test_ensemble_contracts.py @@ -0,0 +1,79 @@ +import pytest + +from tests.models.support import PARAMS, card + +ENSEMBLE_IDS = ( + "bioemu-v1-1", + "alphaflow-md-base-v1", + "alphaflow-md-distilled-v1", + "esmflow-md-base-v1", + "esmflow-md-distilled-v1", +) +FLOW_IDS = ENSEMBLE_IDS[1:5] + + +@pytest.mark.parametrize("model_id", ENSEMBLE_IDS) +def test_ensemble_cards_declare_structure_prediction(model_id): + metadata = card(model_id) + assert "ensemble" in metadata["tags"] + assert metadata["input_types"] == ["protein"] + assert metadata["multichain"] is False + method = PARAMS["methods"][f"{model_id}/batch/structures"] + assert method["outputs"] == ( + ["structures", "plddt", "confidence"] + if model_id in FLOW_IDS + else ["structures"] + ) + + +@pytest.mark.parametrize("model_id", FLOW_IDS) +def test_distilled_flow_cards_are_a_variant_of_their_base(model_id): + metadata = card(model_id) + distilled = "distilled" in model_id + assert metadata["variant"] == ("distilled" if distilled else None) + assert metadata["base"] is not distilled + + +@pytest.mark.parametrize("model_id", ENSEMBLE_IDS) +def test_ensemble_params_use_public_names(model_id): + properties = PARAMS["methods"][f"{model_id}/batch/structures"]["params"][ + "properties" + ] + assert "num_samples" in properties + assert "random_seed" in properties + assert not {"steps", "seed", "batch_size", "batch_size_100"} & properties.keys() + assert "complexes" in properties + + +@pytest.mark.parametrize( + ("model_id", "expected"), + [ + ( + "bioemu-v1-1", + { + "num_samples": 1, + "denoiser": "dpm", + "filter_samples": True, + "random_seed": None, + }, + ), + *[ + ( + model_id, + { + "num_samples": 1, + "num_steps": 10, + "tmax": 1.0, + "self_cond": None, + "random_seed": None, + }, + ) + for model_id in FLOW_IDS + ], + ], +) +def test_ensemble_defaults_match_the_card(model_id, expected): + properties = PARAMS["methods"][f"{model_id}/batch/structures"]["params"][ + "properties" + ] + assert {name: properties[name]["default"] for name in expected} == expected diff --git a/tests/models/test_ensemble_examples.py b/tests/models/test_ensemble_examples.py new file mode 100644 index 0000000..ff1217f --- /dev/null +++ b/tests/models/test_ensemble_examples.py @@ -0,0 +1,49 @@ +import inspect +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest + +from openprotein.align import MSAFuture +from openprotein.jobs.futures import StructurePredictionFuture +from openprotein.models import AlphaFlow, BioEmu, ESMFlow, ModelsAPI + +MSA_ID = "3f1c2a7e-9b4d-4e2a-8c1f-0d5e6a7b8c9d" + + +def _example(method) -> str: + """The method's doctest lines as one script.""" + lines = (inspect.getdoc(method) or "").splitlines() + return "\n".join( + line.strip()[4:] + for line in lines + if line.strip().startswith((">>> ", "... ")) or line.strip() in (">>>", "...") + ) + + +@pytest.mark.parametrize( + ("handle", "paths"), + [ + (BioEmu, ["bioemu-v1-1"] * 2), + (AlphaFlow, ["alphaflow-md-base-v1", "alphaflow-md-distilled-v1"]), + (ESMFlow, ["esmflow-md-base-v1", "esmflow-md-distilled-v1"]), + ], +) +def test_sample_examples_submit_valid_requests( + models_session, ensemble_reference, monkeypatch, handle, paths +): + monkeypatch.setattr(StructurePredictionFuture, "get", lambda self, **kwargs: []) + msa = MagicMock(spec=MSAFuture) + msa.id = MSA_ID + sequence = ensemble_reference.sequence.decode() + namespace = { + "session": SimpleNamespace(models=ModelsAPI(models_session.session)), + "msa": msa, + "sequence": sequence, + "sequences": [sequence, sequence[:40]], + "reference": ensemble_reference, + } + exec(compile(_example(handle.sample), handle.__name__, "exec"), namespace) # noqa: S102 + assert [path for path, _ in models_session.submissions] == [ + f"v1/models/{model_id}/batch/structures" for model_id in paths + ] diff --git a/tests/models/test_ensemble_inputs.py b/tests/models/test_ensemble_inputs.py new file mode 100644 index 0000000..b16cab6 --- /dev/null +++ b/tests/models/test_ensemble_inputs.py @@ -0,0 +1,184 @@ +import re +from pathlib import Path + +import gemmi +import numpy as np +import pytest + +from openprotein.models.ensemble import _inputs as _ensemble_inputs +from openprotein.molecules import Complex, Protein, Structure + +DATA = Path(__file__).parents[1] / "data" +FIELD = "inputs[0].reference_structure" + + +def _residues(pdb: str) -> int: + return len(gemmi.read_pdb_string(pdb)[0][0]) + + +def _flow(value, sequence) -> str: + if isinstance(sequence, Protein): + sequence = sequence.sequence.decode() + return _ensemble_inputs.flow_reference(value, sequence, FIELD) + + +@pytest.mark.parametrize("representation", ["protein", "complex", "structure"]) +def test_flow_molecules_become_matching_protein_pdb(ensemble_reference, representation): + complex = Complex({"A": ensemble_reference}) + value = { + "protein": ensemble_reference, + "complex": complex, + "structure": Structure([complex, complex.copy()]), + }[representation] + parsed = gemmi.read_pdb_string(_flow(value, ensemble_reference)) + assert len(parsed) == 1 + assert len(parsed[0]) == 1 + assert len(parsed[0][0]) == len(ensemble_reference) + sequence = "".join( + gemmi.find_tabulated_residue(residue.name).one_letter_code + for residue in parsed[0][0] + ) + assert sequence == ensemble_reference.sequence.decode() + for residue in parsed[0][0]: + atom_name = "CA" if residue.name == "GLY" else "CB" + assert residue.find_atom(atom_name, "*") is not None + + +def test_flow_raw_mmcif_requires_explicit_molecule_parsing(ensemble_reference): + with pytest.raises(ValueError, match="PDB"): + _flow(ensemble_reference.to_string(format="cif"), ensemble_reference) + + +def test_flow_pdb_waters_are_not_submitted_as_residues(ensemble_reference): + lines = ensemble_reference.to_string(format="pdb").splitlines() + end = next( + ( + index + for index, line in enumerate(lines) + if line.startswith(("ENDMDL", "END")) + ), + len(lines), + ) + lines.insert( + end, + "HETATM99998 O HOH A 901 10.000 11.000 12.000" + " 1.00 20.00 O ", + ) + sent = _flow("\n".join(lines) + "\n", ensemble_reference) + assert "HOH" not in sent + assert len(gemmi.read_pdb_string(sent)[0][0]) == len(ensemble_reference) + + +def test_flow_rejects_declared_unmodelled_residues(): + path = ( + Path(__file__).parents[1] + / "data" + / "boltzgen_entity_one_letter_missing_residues.cif" + ) + protein = Complex.from_filepath(path, verbose=False).get_proteins()["B"] + assert protein.get_structure_mask().any() + with pytest.raises(ValueError, match="unmodelled residues"): + _flow(protein, protein) + + +def test_flow_accepts_a_reference_trimmed_to_its_modelled_residues(): + path = Path(__file__).parents[1] / "data" / "1GCM.pdb" + chain = Structure.from_filepath(path, verbose=False)[0].get_proteins()["A"] + with pytest.raises(ValueError, match="trim"): + _flow(chain, chain) + modelled = chain[~chain.get_structure_mask()] + assert _residues(_flow(modelled, modelled)) == len(modelled) + + +def test_flow_rejects_multiple_protein_chains(ensemble_reference): + value = Complex({"A": ensemble_reference, "B": ensemble_reference}) + with pytest.raises(ValueError, match="one protein chain"): + _flow(value, ensemble_reference) + + +def test_reference_requires_coordinates(): + with pytest.raises(ValueError, match="coordinates"): + _flow(Protein(sequence="MKT"), "MKT") + + +@pytest.mark.parametrize("filename", ["1A3N.cif", "1MSW.cif"]) +def test_flow_rejects_present_nonprotein_chains(filename): + reference = Structure.from_filepath(DATA / filename, verbose=False) + with pytest.raises(ValueError, match="non-protein"): + _flow(reference, "MKT") + + +def test_flow_without_references_sends_none(): + assert _ensemble_inputs.flow_references([None, None], ["MKT", "MKT"]) is None + + +def test_flow_reads_pdb_bytes(ensemble_reference): + pdb = ensemble_reference.to_string(format="pdb").encode() + assert _residues(_flow(pdb, ensemble_reference)) == len(ensemble_reference) + + +@pytest.mark.parametrize( + ("value", "message"), + [ + (Structure([]), "contains no structure"), + ("not a structure\n", "contains no protein chain"), + (" \n", "is empty"), + (b"", "is empty"), + (42, "must be structure text"), + ], +) +def test_flow_rejects_unusable_structures(value, message): + with pytest.raises((TypeError, ValueError), match=rf"{re.escape(FIELD)} {message}"): + _flow(value, "MKT") + + +def test_flow_pdb_ligand_error_names_the_field(ensemble_reference): + lines = ensemble_reference.to_string(format="pdb").splitlines() + ligand = ( + "HETATM99990 MG MG B 501 10.000 11.000 12.000" + " 1.00 20.00 MG " + ) + with pytest.raises(ValueError, match=r"inputs\[0\]\.reference_structure .*ligand"): + _flow("\n".join([*lines, ligand]) + "\n", ensemble_reference) + + +@pytest.mark.parametrize( + ("edit", "message"), + [ + (lambda s: s[:-1], "residues and the sequence has"), + (lambda s: ("A" if s[0] != "A" else "G") + s[1:], "at position 1"), + ], +) +def test_flow_reference_must_match_the_sequence(ensemble_reference, edit, message): + sequence = edit(ensemble_reference.sequence.decode()) + with pytest.raises(ValueError, match=message): + _flow(ensemble_reference, sequence) + + +def test_flow_reference_matches_an_unknown_residue(ensemble_reference): + sequence = "X" + ensemble_reference.sequence.decode()[1:] + assert _residues(_flow(ensemble_reference, sequence)) == len(ensemble_reference) + + +def test_a_protein_with_only_plddt_has_no_coordinates(): + protein = Protein(sequence="MKT") + protein._plddt[:] = 90.0 + assert protein.has_structure + with pytest.raises(ValueError, match="coordinates"): + _flow(protein, "MKT") + + +def test_references_use_the_first_complex_of_a_structure(ensemble_reference): + shorter = ensemble_reference[:50] + structure = Structure([Complex({"A": ensemble_reference}), Complex({"A": shorter})]) + assert _residues(_flow(structure, ensemble_reference)) == len(ensemble_reference) + + +def test_references_leave_caller_molecules_unchanged(ensemble_reference): + pdb = ensemble_reference.to_string(format="pdb") + coordinates = ensemble_reference.coordinates.copy() + + _flow(ensemble_reference, ensemble_reference) + + assert ensemble_reference.to_string(format="pdb") == pdb + np.testing.assert_array_equal(ensemble_reference.coordinates, coordinates) diff --git a/tests/models/test_ensemble_models.py b/tests/models/test_ensemble_models.py new file mode 100644 index 0000000..2967270 --- /dev/null +++ b/tests/models/test_ensemble_models.py @@ -0,0 +1,295 @@ +from typing import Any +from unittest.mock import MagicMock + +import gemmi +import pytest +from jsonschema import ValidationError + +from openprotein.errors import HTTPError +from openprotein.jobs.futures import StructurePredictionFuture +from openprotein.models import ( + AlphaFlow, + AlphaFlowInput, + BioEmu, + BioEmuInput, + ESMFlow, + ESMFlowInput, + ModelsAPI, + StructureEnsemblePredictionModel, + StructurePredictionModel, +) +from openprotein.molecules import Protein + +HANDLES = { + "bioemu-v1-1": BioEmu, + "alphaflow-md-base-v1": AlphaFlow, + "alphaflow-md-distilled-v1": AlphaFlow, + "esmflow-md-base-v1": ESMFlow, + "esmflow-md-distilled-v1": ESMFlow, +} +IDS = tuple(HANDLES) +FLOW_IDS = IDS[1:5] +MSA_ID = "3f1c2a7e-9b4d-4e2a-8c1f-0d5e6a7b8c9d" + +CARD_DEFAULTS = { + BioEmu: { + "num_samples": 1, + "denoiser": "dpm", + "filter_samples": True, + "random_seed": None, + }, + AlphaFlow: { + "num_samples": 1, + "num_steps": 10, + "tmax": 1.0, + "msa_subsample": None, + "self_cond": None, + "resample": None, + "random_seed": None, + }, + ESMFlow: { + "num_samples": 1, + "num_steps": 10, + "tmax": 1.0, + "self_cond": None, + "random_seed": None, + }, +} + + +def _handle(models_session, model_id) -> Any: + return ModelsAPI(models_session.session).get_model(model_id) + + +def _input(model_id: str, sequence: str = "MKT", reference: Any = None) -> Any: + if model_id == "bioemu-v1-1": + return BioEmuInput(sequence, msa=MSA_ID) + if model_id.startswith("alphaflow-"): + return AlphaFlowInput(sequence, msa=MSA_ID, reference_structure=reference) + return ESMFlowInput(sequence, reference_structure=reference) + + +@pytest.mark.parametrize("model_id", IDS) +def test_accessor_and_get_model_share_an_ensemble_handle(models_session, model_id): + models = ModelsAPI(models_session.session) + handle = getattr(models, model_id.replace("-", "_")) + assert handle is models.get_model(model_id) + assert type(handle) is HANDLES[model_id] + assert isinstance(handle, StructureEnsemblePredictionModel) + + +@pytest.mark.parametrize("handle", sorted(set(HANDLES.values()), key=str)) +def test_ensemble_handles_are_not_structure_prediction_handles(handle): + assert not issubclass(handle, StructurePredictionModel) + + +@pytest.mark.parametrize( + ("handle", "input_type"), + [ + (BioEmu, BioEmuInput), + (AlphaFlow, AlphaFlowInput), + (ESMFlow, ESMFlowInput), + ], +) +def test_each_handle_names_its_input_type(handle, input_type): + assert handle.Input is input_type + + +@pytest.mark.parametrize("model_id", IDS) +def test_unset_controls_send_the_card_defaults(models_session, model_id): + future = _handle(models_session, model_id).sample([_input(model_id)]) + assert type(future) is StructurePredictionFuture + 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 + + +def test_bioemu_sends_one_protein_per_input(models_session): + ModelsAPI(models_session.session).bioemu_v1_1.sample( + [ + BioEmuInput("MKT", msa=None), + BioEmuInput(b"ACDE", msa=Protein.single_sequence_mode), + BioEmuInput(Protein(sequence="GG"), msa=None), + ] + ) + assert models_session.submitted[1]["complexes"] == [ + [{"protein": {"id": "A", "sequence": sequence, "msa_id": None}}] + for sequence in ("MKT", "ACDE", "GG") + ] + + +@pytest.mark.parametrize("model_id", ["alphaflow-md-base-v1", "bioemu-v1-1"]) +def test_aligned_inputs_send_their_msa(models_session, model_id): + _handle(models_session, model_id).sample([_input(model_id), _input(model_id)]) + proteins = [c[0]["protein"] for c in models_session.submitted[1]["complexes"]] + assert [protein["msa_id"] for protein in proteins] == [MSA_ID, MSA_ID] + + +@pytest.mark.parametrize("msa", [None, Protein.single_sequence_mode]) +def test_alphaflow_refuses_an_input_without_an_msa(models_session, msa): + with pytest.raises(ValueError, match=r"inputs\[0\]\.msa is required"): + ModelsAPI(models_session.session).alphaflow_md_base_v1.sample( + [AlphaFlowInput("MKT", msa=msa)] + ) + models_session.session.post.assert_not_called() + + +def test_esmflow_sends_no_msa(models_session): + ModelsAPI(models_session.session).esmflow_md_base_v1.sample([ESMFlowInput("MKT")]) + assert models_session.submitted[1]["complexes"] == [ + [{"protein": {"id": "A", "sequence": "MKT"}}] + ] + + +@pytest.mark.parametrize("model_id", ["bioemu-v1-1", *FLOW_IDS]) +@pytest.mark.parametrize( + ("sequence", "error", "message"), + [ + ("MKT:ACDE", ValueError, "several chains"), + ("", ValueError, "is empty"), + (42, TypeError, "Protein or sequence text"), + ], +) +def test_sequence_inputs_take_one_protein_chain( + models_session, model_id, sequence, error, message +): + with pytest.raises(error, match=message): + _handle(models_session, model_id).sample([_input(model_id, sequence)]) + models_session.session.post.assert_not_called() + + +@pytest.mark.parametrize("model_id", IDS) +@pytest.mark.parametrize( + ("inputs", "error", "message"), + [ + ("MKT", TypeError, "must be a list"), + ([], ValueError, "at least one input"), + (["MKT"], TypeError, r"inputs\[0\] must be a"), + ], +) +def test_inputs_are_a_list_of_the_handles_input_type( + models_session, model_id, inputs, error, message +): + with pytest.raises(error, match=message): + _handle(models_session, model_id).sample(inputs) + models_session.session.post.assert_not_called() + + +def test_an_input_of_another_model_is_refused(models_session): + with pytest.raises(TypeError, match=r"inputs\[0\] must be a ESMFlowInput"): + ModelsAPI(models_session.session).esmflow_md_base_v1.sample( + [BioEmuInput("MKT", msa=None)] # ty: ignore[invalid-argument-type] + ) + + +@pytest.mark.parametrize("model_id", FLOW_IDS) +def test_flow_without_references_sends_none(models_session, model_id): + _handle(models_session, model_id).sample([_input(model_id)]) + assert "reference_structures" not in models_session.submitted[1] + + +@pytest.mark.parametrize("model_id", FLOW_IDS) +def test_flow_sends_every_reference_in_input_order( + models_session, ensemble_reference, model_id +): + shorter = ensemble_reference[:50] + _handle(models_session, model_id).sample( + [ + _input(model_id, ensemble_reference.sequence.decode(), ensemble_reference), + _input(model_id, shorter.sequence.decode(), shorter), + ] + ) + references = models_session.submitted[1]["reference_structures"] + residues = [ + len(gemmi.read_pdb_string(record["structure_file"])[0][0]) + for record in references + ] + assert residues == [len(ensemble_reference), 50] + + +@pytest.mark.parametrize("model_id", FLOW_IDS) +def test_flow_references_are_given_for_every_input_or_none( + models_session, ensemble_reference, model_id +): + sequence = ensemble_reference.sequence.decode() + with pytest.raises(ValueError, match=r"every input.*inputs\[1\] has none"): + _handle(models_session, model_id).sample( + [ + _input(model_id, sequence, ensemble_reference), + _input(model_id, sequence), + ] + ) + models_session.session.post.assert_not_called() + + +@pytest.mark.parametrize("seed", [None, 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 + ) + assert models_session.submitted[1]["random_seed"] == seed + + +@pytest.mark.parametrize( + ("model_id", "name", "value"), + [ + ("bioemu-v1-1", "num_samples", 0), + ("alphaflow-md-base-v1", "num_steps", 101), + ("esmflow-md-base-v1", "tmax", 0), + ("esmflow-md-distilled-v1", "num_samples", 251), + ], +) +def test_out_of_range_controls_fail_the_card_schema( + models_session, model_id, name, value +): + with pytest.raises(ValidationError) as error: + _handle(models_session, model_id).sample([_input(model_id)], **{name: value}) + assert list(error.value.absolute_path) == [name] + + +def test_a_card_refusal_reaches_the_caller_without_a_submission(models_session): + refused = HTTPError(MagicMock(status_code=404, text="not found")) + models_session.session.get.side_effect = refused + with pytest.raises(HTTPError): + ModelsAPI(models_session.session).bioemu_v1_1.sample( + [BioEmuInput("MKT", msa=None)] + ) + models_session.session.post.assert_not_called() + + +def test_a_submission_refusal_reaches_the_caller_once(models_session): + accepted = models_session._post + + def post(path, **kwargs): + accepted(path, **kwargs) + raise HTTPError(MagicMock(status_code=422, text="unsupported reference")) + + models_session.session.post.side_effect = post + with pytest.raises(HTTPError): + ModelsAPI(models_session.session).esmflow_md_base_v1.sample( + [ESMFlowInput("MKT")] + ) + assert [path for path, _ in models_session.submissions] == [ + "v1/models/esmflow-md-base-v1/batch/structures" + ] + + +def test_a_425_resubmit_sends_the_same_body_and_headers(models_session, monkeypatch): + monkeypatch.setattr("openprotein.jobs._submission.time.sleep", lambda _: None) + pending = MagicMock(status_code=425, headers={"Retry-After": "0"}) + accepted = models_session._post + answers = iter([HTTPError(pending)]) + + def post(path, **kwargs): + error = next(answers, None) + accepted(path, **kwargs) + if error is not None: + raise error + return accepted(path, **kwargs) + + models_session.session.post.side_effect = post + ModelsAPI(models_session.session).bioemu_v1_1.sample([BioEmuInput("MKT", msa=None)]) + + first, second = models_session.session.post.call_args_list + assert first == second diff --git a/tests/models/test_ensemble_results.py b/tests/models/test_ensemble_results.py new file mode 100644 index 0000000..0f573fa --- /dev/null +++ b/tests/models/test_ensemble_results.py @@ -0,0 +1,198 @@ +import numpy as np +import pytest + +from openprotein.fold import api as fold_api +from openprotein.fold.future import FoldResultFuture +from openprotein.fold.schemas import FoldMetadata +from openprotein.jobs import Future, Job, JobsAPI, _dispatch +from openprotein.jobs import api as job_api +from openprotein.jobs.futures import StructurePredictionFuture +from openprotein.jobs.schemas import JobType +from openprotein.models import ( + AlphaFlowInput, + BioEmuInput, + ESMFlowInput, + ModelsAPI, +) +from openprotein.molecules import Complex, Protein, Structure +from tests.models.support import SUBMITTED_JOB, Stored + +IDS = ( + "bioemu-v1-1", + "alphaflow-md-base-v1", + "alphaflow-md-distilled-v1", + "esmflow-md-base-v1", + "esmflow-md-distilled-v1", +) +MSA_ID = "3f1c2a7e-9b4d-4e2a-8c1f-0d5e6a7b8c9d" +PROMPT_ID = "5b2d8e4a-1c7f-4a3e-9d6b-2e8f0a1c3b5d" + + +#: x-offsets of each position's conformations, distinct so order is checked +SHIFTS = [[0.0, 10.0], [100.0, 110.0]] + + +def _ensemble(reference: Protein, shifts: list[float]) -> str: + conformations = [ + Complex({"A": reference.copy()}).transform(t=np.array([shift, 0.0, 0.0])) + for shift in shifts + ] + return Structure(conformations).to_string(format="cif") + + +def _shifts(value: object, reference: Protein) -> list[float]: + assert isinstance(value, Structure) + origin = np.nanmean(reference.coordinates[..., 0]) + return [ + round( + float( + np.nanmean(conformation.get_proteins()["A"].coordinates[..., 0]) + - origin + ), + 1, + ) + for conformation in value + ] + + +def _submit(models, model_id, reference): + handle = models.get_model(model_id) + sequence = reference.sequence + if model_id == "bioemu-v1-1": + entry = BioEmuInput(sequence, msa=MSA_ID) + elif model_id.startswith("alphaflow-"): + entry = AlphaFlowInput(sequence, msa=MSA_ID) + else: + entry = ESMFlowInput(sequence) + return handle.sample([entry, entry], num_samples=2, random_seed=7) + + +@pytest.mark.parametrize("model_id", IDS) +@pytest.mark.parametrize( + ("job_type", "operation"), + [ + ("/models", "submitted"), + ("/models", "get"), + ("/models", "explicit"), + ], +) +def test_ensemble_results_preserve_positions_and_conformations( + aligned_ensemble_session, + ensemble_reference, + monkeypatch, + model_id, + operation, + job_type, +): + monkeypatch.setattr("openprotein.jobs.futures.time.sleep", lambda seconds: None) + models_session = aligned_ensemble_session + is_flow = model_id.startswith(("alphaflow-", "esmflow-")) + outputs = ["structures", "plddt", "confidence"] if is_flow else ["structures"] + payload = { + **SUBMITTED_JOB, + "job_type": ( + f"/models/{model_id}/batch/structures" + if job_type == "/models" + else job_type + ), + "model_id": model_id, + "args": {"random_seed": 7}, + } + route = f"v1/models/{model_id}/batch/structures" + models_session.post_routes[route] = payload + submitted = _submit(ModelsAPI(models_session.session), model_id, ensemble_reference) + assert type(submitted) is StructurePredictionFuture + + job_id = submitted.id + models_session.outputs[(job_id, "structures")] = [ + Stored(None, _ensemble(ensemble_reference, shifts).encode()) + for shifts in SHIFTS + ] + if is_flow: + models_session.outputs[(job_id, "plddt")] = [ + [[80.0 + shift] * len(ensemble_reference) for shift in shifts] + for shifts in SHIFTS + ] + models_session.outputs[(job_id, "confidence")] = [0.8, 0.81] + + for output in outputs: + for position in range(2): + models_session.get_routes[ + f"v1/data/results/{job_id}/{output}/{position}" + ] = { + "position": position, + "unit_id": f"u{position}", + "value": models_session._value(job_id, output, position), + } + + job = Job.create(payload) + monkeypatch.setattr(job_api, "job_get", lambda session, job_id: job) + jobs = JobsAPI(models_session.session) + future = ( + jobs.get(job_id) + if operation == "get" + else _dispatch.create(models_session.session, job) + if operation == "explicit" + else submitted + ) + assert isinstance(future, StructurePredictionFuture) + assert type(future) is StructurePredictionFuture + assert future.args == payload["args"] + + for values in ( + future.get(), + future.wait(), + list(future.stream()), + list(future), + ): + assert [_shifts(value, ensemble_reference) for value in values] == SHIFTS + + for position, shifts in enumerate(SHIFTS): + for value in ( + future.get_item(position), + future[position], + future.unit(position).get(), + ): + assert _shifts(value, ensemble_reference) == shifts + + if is_flow: + assert future.get(output="confidence") == [0.8, 0.81] + assert future.unit(1, output="confidence").get() == 0.81 + plddt = np.asarray(future.get_item(1, output="plddt")) + assert plddt[:, 0].tolist() == [80.0 + shift for shift in SHIFTS[1]] + + +@pytest.mark.parametrize("model_id", IDS) +def test_fold_records_keep_their_compatibility_reader( + models_session, + ensemble_reference, + monkeypatch, + model_id, +): + payload = { + **SUBMITTED_JOB, + "job_type": JobType.embeddings_fold.value, + } + job = Job.create(payload) + monkeypatch.setattr(job_api, "job_get", lambda session, job_id: job) + monkeypatch.setattr( + fold_api, + "fold_get", + lambda session, job_id: FoldMetadata(job_id=job_id, model_id=model_id), + ) + monkeypatch.setattr( + fold_api, + "fold_get_sequences", + lambda session, job_id: [ensemble_reference.sequence], + ) + future = JobsAPI(models_session.session).get(job.job_id) + assert type(future) is FoldResultFuture + + +@pytest.mark.parametrize("job_type", ["/models", JobType.embeddings_fold.value]) +def test_explicit_task_reconstruction_needs_method_identity(mock_session, job_type): + job = Job.create({**SUBMITTED_JOB, "job_type": job_type}) + future = _dispatch.create(mock_session, job) + assert type(future) is Future + assert future.id == job.job_id + mock_session.get.assert_not_called() diff --git a/tests/models/test_estimators.py b/tests/models/test_estimators.py new file mode 100644 index 0000000..601c67f --- /dev/null +++ b/tests/models/test_estimators.py @@ -0,0 +1,1185 @@ +"""Estimators on ``session.models`` and the futures they fit on.""" + +from typing import Any +from unittest.mock import MagicMock + +import pandas as pd +import pytest + +from openprotein.data import AssayDataset, DataAPI +from openprotein.embeddings.future import EmbeddingsResultFuture +from openprotein.errors import HTTPError, JobFailedException +from openprotein.jobs import Future, Job +from openprotein.jobs import futures as results +from openprotein.jobs.futures import ( + GPFitFuture, + SVDFitFuture, + UMAPFitFuture, + _Submission, +) +from openprotein.models import ( + GPModel, + ModelsAPI, + SVDModel, + UMAPModel, + _inputs, +) +from openprotein.models.estimators import GP, SVD, UMAP, _dataset_of, _job_id +from openprotein.svd.models import SVDModel as SVDFit +from tests.models.support import SUBMITTED_JOB + +ESM2 = "esm2_t33_650M_UR50D" +SEQUENCES = ["MKTA", "MKTC", "MKTD", "MKTE"] +ASSAY = "6f1c2c1e-0000-4000-a000-0000000000a1" + + +def _assay(*measurements: str) -> AssayDataset: + rows = pd.DataFrame({"sequence": SEQUENCES}) + assay = MagicMock( + spec=AssayDataset, + id=ASSAY, + page_size=3, + measurement_names=list(measurements or ("fitness",)), + ) + assay.get_slice.side_effect = lambda start, end: rows.iloc[start:end] + return assay + + +def _job(job_id: str, status: str = "PENDING") -> dict[str, Any]: + return { + "job_id": job_id, + "job_type": "/models", + "status": status, + "created_date": "2026-10-29T08:00:00Z", + } + + +@pytest.fixture +def models(models_session) -> ModelsAPI: + return ModelsAPI(models_session.session) + + +class TestEmbedAnAssay: + def test_it_is_named_by_id_and_stays_on_the_future(self, models, models_session): + assay = _assay() + + future = models.esm2.embed(assay) + + body = {"assay_id": ASSAY, "reduction": "MEAN"} + assert models_session.submitted == ( + f"v1/models/{ESM2}/batch/embeddings", + body, + ) + assert isinstance(future, results.EmbeddingFuture) + assert future.dataset is assay + assert future._submission == _Submission(ESM2, "batch/embeddings", body) + assay.get_slice.assert_not_called() + + def test_a_projection_sends_its_sequences(self, models, models_session): + assay = _assay() + + future = models.get_model("svd/s-1").transform(assay) + + assert models_session.submitted[1] == {"sequences": SEQUENCES} + assert isinstance(future, results.EmbeddingFuture) + assert future.dataset is assay + + 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} + ) + + +class TestFittedSVD: + def test_get_model_returns_a_fitted_svd(self, models): + svd = models.get_model("svd/s-1") + + assert isinstance(svd, SVDModel) + assert svd.id == "svd/s-1" + + def test_a_bare_id_is_prefixed(self, models): + assert SVDModel(models.session, "s-1").id == "svd/s-1" + + def test_transform_projects_an_assay_and_keeps_it(self, models, models_session): + assay = _assay() + + future = models.get_model("svd/s-1").transform(assay) + + assert models_session.submitted == ( + "v1/models/svd/s-1/batch/embeddings", + {"sequences": SEQUENCES}, + ) + assert future.dataset is assay + + def test_transform_of_sequences_keeps_no_dataset(self, models): + assert models.get_model("svd/s-1").transform(SEQUENCES).dataset is None + + def test_embed_submits_what_transform_submits(self, models, models_session): + svd = models.get_model("svd/s-1") + assay = _assay() + + transformed = svd.transform(assay) + embedded = svd.embed(assay) + + assert models_session.submissions[-1] == models_session.submissions[-2] + assert isinstance(embedded, Future) + assert embedded.outputs == transformed.outputs + assert embedded.dataset is assay + + def test_it_fits_a_umap_and_a_gp_on_its_projections(self, models, models_session): + svd = models.get_model("svd/s-1") + assert isinstance(svd, SVDModel) + + umap = svd.fit_umap(sequences=SEQUENCES) + gp = svd.fit_gp(ASSAY, ["fitness"]) + + assert isinstance(umap, UMAPFitFuture) + assert isinstance(gp, GPFitFuture) + assert [path for path, _ in models_session.submissions] == [ + "v1/models/umap", + "v1/models/gp", + ] + + def test_its_record_is_read_from_its_card(self, models, models_session, model_card): + models_session.get_routes["v1/models/svd/s-1"] = model_card("svd/s-1") | { + "svd": {"id": "s-1", "n_components": 2} + } + + assert SVDModel(models.session, "svd/s-1").n_components == 2 + + +JOB_ID = SUBMITTED_JOB["job_id"] + + +@pytest.fixture +def distinct_ids(models_session): + """Give SVD fits and projections ids of their own, apart from their embeddings.""" + models_session.post_routes["v1/models/svd"] = _job("fit-1") + models_session.post_routes["v1/models/svd/s-1/batch/embeddings"] = _job("proj-1") + + +def _reloaded(job_id: str, **fields: Any) -> Job: + return Job.model_validate(_job(job_id, "SUCCESS") | fields) + + +def _reloaded_embeddings(job_id: str) -> Job: + return _reloaded( + job_id, + job_type=f"/models/{ESM2}/batch/embeddings", + ) + + +class TestJobId: + def test_a_fitted_svd_goes_by_its_bare_id(self, models): + assert _job_id(models.get_model("svd/s-1")) == "s-1" + + def test_an_earlier_api_svd_goes_by_its_id(self): + assert _job_id(MagicMock(spec=SVDFit, id="s-1")) == "s-1" + + @pytest.mark.parametrize("given, sent", [("e-1", "e-1"), ("svd/s-1", "s-1")]) + def test_an_id_goes_bare(self, given, sent): + assert _job_id(given) == sent + + @pytest.mark.parametrize( + "x", + [ + lambda m: m.esm2.embed(SEQUENCES), + lambda m: m.get_model("svd/s-1").transform(SEQUENCES), + lambda m: m.SVD().fit(m.esm2.embed(SEQUENCES)), + lambda m: m.get_model("umap/u-1").embed(SEQUENCES), + lambda m: Future(m.session, _reloaded("r-1")), + lambda m: MagicMock(spec=EmbeddingsResultFuture, id=JOB_ID), + lambda m: Future.create( + session=m.session, + response=_job(JOB_ID, "SUCCESS") | {"job_type": "/svd/embed"}, + ), + ], + ids=[ + "embeddings", + "projection", + "svd fit", + "umap embeddings", + "reloaded job", + "earlier api embeddings", + "earlier api projection", + ], + ) + def test_a_job_is_named_by_its_id_with_no_read(self, models, models_session, x): + x = x(models) + models_session.session.get.reset_mock() + + assert _job_id(x) == x.id + models_session.session.get.assert_not_called() + + @pytest.mark.parametrize( + "x, named", [(3, "int"), (_assay(), f"assay {ASSAY}")], ids=["int", "assay"] + ) + def test_anything_else_is_refused(self, x, named): + with pytest.raises(TypeError, match=f"{named} isn't an embeddings job"): + _job_id(x) + + +class TestDatasetOf: + def test_an_assay_is_its_own_dataset(self): + assay = _assay() + + assert _dataset_of(assay) is assay + + def test_a_future_carries_the_assay_it_embedded(self, models): + assay = _assay() + + assert _dataset_of(models.esm2.embed(assay)) is assay + + @pytest.mark.parametrize( + "x", + [ + lambda m: m.esm2.embed(SEQUENCES), + lambda m: m.get_model("svd/s-1"), + lambda m: 3, + ], + ids=["sequences", "fitted svd", "other"], + ) + def test_anything_else_has_none(self, models, x): + assert _dataset_of(x(models)) is None + + def test_a_reloaded_embedding_reads_its_assay_from_its_args( + self, models, models_session, monkeypatch + ): + assay = _assay() + loaded = [] + + def as_dataset(session, assay_id): + loaded.append(assay_id) + return assay + + monkeypatch.setattr(_inputs, "as_dataset", as_dataset) + models_session.get_routes["v1/jobs/e-1/args"] = {"assay_id": ASSAY} + x = Future(models.session, _reloaded_embeddings("e-1")) + + assert _dataset_of(x) is assay + assert _dataset_of(x) is assay + assert loaded == [ASSAY] + + def test_a_reloaded_embedding_of_sequences_has_none(self, models, models_session): + models_session.get_routes["v1/jobs/e-1/args"] = {"sequences": SEQUENCES} + + assert _dataset_of(Future(models.session, _reloaded_embeddings("e-1"))) is None + + +class TestAFitTheModelsApiRefuses: + @pytest.mark.parametrize( + "fit", + [ + lambda m, x: m.SVD().fit(x), + lambda m, x: m.UMAP().fit(x), + lambda m, x: m.GP().fit(x), + ], + ids=["SVD", "UMAP", "GP"], + ) + def test_its_422_reaches_the_caller(self, models, models_session, fit): + x = models.esm2.embed(_assay(), reduction=None) + models_session.session.post.reset_mock() + models_session.session.post.side_effect = HTTPError( + MagicMock(status_code=422, text="refused", url="v1/models") + ) + + with pytest.raises(HTTPError) as raised: + fit(models, x) + + assert raised.value.status_code == 422 + models_session.session.post.assert_called_once() + + +def _svd_fit_succeeds(models_session, model_card, job_id: str) -> None: + models_session.post_routes["v1/models/svd"] = _job(job_id, "SUCCESS") + models_session.get_routes[f"v1/jobs/{job_id}"] = _job(job_id, "SUCCESS") + models_session.get_routes[f"v1/models/svd/{job_id}"] = model_card( + f"svd/{job_id}" + ) | {"svd": {"id": job_id, "n_components": 2}} + + +class TestSVD: + def test_fit_names_the_embeddings_job_with_no_read(self, models, models_session): + embeddings = models.poet2.embed( + SEQUENCES, prompt="prompt-1", decoder_type="clm" + ) + models_session.session.get.reset_mock() + models_session.post_routes["v1/models/svd"] = _job("fit-1") + + future = models.SVD(n_components=2, seed=7).fit(embeddings) + + assert isinstance(future, SVDFitFuture) + assert models_session.submissions[-1] == ( + "v1/models/svd", + { + "embeddings_job_id": embeddings.id, + "n_components": 2, + "output": "embeddings", + "seed": 7, + }, + ) + models_session.session.get.assert_not_called() + + def test_fit_transform_is_fit_and_carries_the_assay(self, models): + assay = _assay() + svd = models.SVD(n_components=2) + + future = svd.fit_transform(models.esm2.embed(assay)) + + assert future.dataset is assay + + def test_a_fit_on_a_reloaded_job_reads_its_assay_only_when_asked( + self, models, models_session, monkeypatch + ): + assay = _assay() + monkeypatch.setattr(_inputs, "as_dataset", lambda session, assay_id: assay) + models_session.get_routes["v1/jobs/e-1/args"] = {"assay_id": ASSAY} + x = Future(models.session, _reloaded_embeddings("e-1")) + + future = models.SVD(n_components=2).fit(x) + + models_session.session.get.assert_not_called() + assert future.dataset is assay + + def test_waiting_with_an_output_reads_that_output_of_the_fit( + self, models, models_session, model_card + ): + _svd_fit_succeeds(models_session, model_card, "fit-1") + models_session.get_routes["v1/jobs/fit-1"] |= {"outputs": ["embeddings"]} + models_session.outputs[("fit-1", "embeddings")] = [[0.5, 0.25]] + + future = models.SVD(n_components=2).fit(models.esm2.embed(SEQUENCES)) + + assert future.wait(output="embeddings") == future.get(output="embeddings") + assert isinstance(future.wait(), SVDModel) + + def test_a_fitted_svd_as_x_goes_by_its_id(self, models, models_session): + models.SVD().fit(models.get_model("svd/s-1")) + + assert models_session.submissions[-1] == ( + "v1/models/svd", + {"embeddings_job_id": "s-1", "output": "embeddings"}, + ) + + def test_fit_on_a_models_embeddings_of_an_assay(self, models, models_session): + assay = _assay() + + future = models.SVD(n_components=2).fit( + model=models.esm2, assay=assay, reduction="MEAN" + ) + + assert models_session.submissions[-1] == ( + "v1/models/svd", + { + "model_id": ESM2, + "output": "embeddings", + "n_components": 2, + "assay_id": ASSAY, + "reduction": "MEAN", + }, + ) + assert future.dataset is assay + + def test_fit_on_a_models_embeddings_of_sequences(self, models, models_session): + models.SVD().fit(model="prot-seq", sequences=SEQUENCES) + + assert models_session.submissions[-1] == ( + "v1/models/svd", + {"model_id": "prot-seq", "output": "embeddings", "sequences": SEQUENCES}, + ) + + def test_waiting_on_the_fit_returns_the_fitted_svd( + self, models, models_session, model_card + ): + _svd_fit_succeeds(models_session, model_card, "fit-1") + + fitted = models.SVD(n_components=2).fit(models.esm2.embed(SEQUENCES)).wait() + + assert isinstance(fitted, SVDModel) + assert fitted.id == "svd/fit-1" + + def test_the_fit_future_projects_without_waiting_for_its_fit( + self, models, models_session + ): + models_session.post_routes["v1/models/svd"] = _job("fit-1") + future = models.SVD(n_components=2).fit(models.esm2.embed(SEQUENCES)) + assay = _assay() + + projected = future.transform(assay) + + assert models_session.submissions[-1] == ( + "v1/models/svd/fit-1/batch/embeddings", + {"sequences": SEQUENCES}, + ) + assert projected.dataset is assay + assert projected._path == "batch/embeddings" + assert projected.outputs == ["embeddings"] + assert all( + "fit-1" not in str(call) + for call in models_session.session.get.call_args_list + ) + + def test_the_svd_fit_future_embed_submits_what_transform_submits( + self, models, models_session + ): + models_session.post_routes["v1/models/svd"] = _job("fit-1") + future = models.SVD(n_components=2).fit(models.esm2.embed(SEQUENCES)) + + transformed = future.transform(SEQUENCES) + embedded = future.embed(SEQUENCES) + + assert models_session.submissions[-1] == models_session.submissions[-2] + assert isinstance(embedded, Future) + assert embedded._path == transformed._path + assert embedded.outputs == transformed.outputs + + def test_waiting_on_a_failed_fit_raises(self, models, models_session): + models_session.post_routes["v1/models/svd"] = _job("fit-1", "FAILURE") + models_session.get_routes["v1/jobs/fit-1"] = _job("fit-1", "FAILURE") + future = models.SVD(n_components=2).fit(models.esm2.embed(SEQUENCES)) + + with pytest.raises(JobFailedException): + future.wait() + + +class TestUMAP: + @pytest.mark.parametrize( + "x, sent", + [ + (lambda m: m.esm2.embed(SEQUENCES), lambda x: {"embeddings_job_id": x.id}), + ( + lambda m: m.get_model("svd/s-1").transform(SEQUENCES), + lambda x: {"embeddings_job_id": x.id}, + ), + ( + lambda m: m.SVD(n_components=2).fit(m.esm2.embed(SEQUENCES)), + lambda x: {"embeddings_job_id": x.id}, + ), + ( + lambda m: m.get_model("svd/s-1"), + lambda x: {"embeddings_job_id": "s-1"}, + ), + ], + ids=["embeddings", "projection", "svd fit", "fitted svd"], + ) + def test_fit_transform_names_its_source( + self, models, models_session, distinct_ids, x, sent + ): + x = x(models) + + future = models.UMAP(n_components=2).fit_transform(x) + + assert isinstance(future, UMAPFitFuture) + assert models_session.submissions[-1] == ( + "v1/models/umap", + {"n_components": 2, **sent(x)}, + ) + + def test_the_assay_stays_on_the_fit(self, models): + assay = _assay() + + future = models.UMAP().fit(models.esm2.embed(assay)) + + assert future.dataset is assay + + def test_fit_on_an_svds_features_of_sequences(self, models, models_session): + models.UMAP(n_components=2).fit( + model=models.get_model("svd/s-1"), sequences=SEQUENCES + ) + + assert models_session.submissions[-1] == ( + "v1/models/umap", + {"model_id": "svd/s-1", "sequences": SEQUENCES, "n_components": 2}, + ) + + def test_the_fit_future_maps_without_waiting_for_its_fit( + self, models, models_session + ): + models_session.post_routes["v1/models/umap"] = _job("u-1") + future = models.UMAP(n_components=2).fit(models.esm2.embed(SEQUENCES)) + assay = _assay() + + mapped = future.transform(assay) + + assert models_session.submissions[-1] == ( + "v1/models/umap/u-1/batch/embeddings", + {"sequences": SEQUENCES}, + ) + assert mapped.dataset is assay + assert mapped._path == "batch/embeddings" + assert mapped.outputs == ["embeddings"] + assert all( + "u-1" not in str(call) for call in models_session.session.get.call_args_list + ) + + def test_the_umap_fit_future_embed_submits_what_transform_submits( + self, models, models_session + ): + models_session.post_routes["v1/models/umap"] = _job("u-1") + future = models.UMAP(n_components=2).fit(models.esm2.embed(SEQUENCES)) + + transformed = future.transform(SEQUENCES) + embedded = future.embed(SEQUENCES) + + assert models_session.submissions[-1] == models_session.submissions[-2] + assert isinstance(embedded, Future) + assert embedded._path == transformed._path + assert embedded.outputs == transformed.outputs + + def test_a_fitted_umap_transform_submits_what_embed_submits( + self, models, models_session + ): + umap = models.get_model("umap/u-1") + assay = _assay() + + embedded = umap.embed(assay) + transformed = umap.transform(assay) + + assert models_session.submissions[-1] == models_session.submissions[-2] + assert isinstance(transformed, Future) + assert transformed.outputs == embedded.outputs + assert transformed.dataset is assay + + @pytest.mark.parametrize("by_id", [False, True], ids=["dataset", "id"]) + def test_a_fit_on_an_assay_keeps_the_assay( + self, models, models_session, monkeypatch, by_id + ): + assay = _assay() + monkeypatch.setattr(_inputs, "as_dataset", lambda session, given: assay) + models_session.post_routes["v1/models/umap"] = _job("u-1") + given = ASSAY if by_id else assay + + handle_fit = models.esm2.fit_umap(assay=given, reduction="MEAN") + estimator_fit = models.UMAP().fit( + model=models.esm2, assay=given, reduction="MEAN" + ) + + assert handle_fit.dataset is assay + assert estimator_fit.dataset is assay + + def test_waiting_on_the_fit_returns_the_fitted_umap( + self, models, models_session, model_card + ): + models_session.post_routes["v1/models/umap"] = _job("u-1", "SUCCESS") + models_session.get_routes["v1/jobs/u-1"] = _job("u-1", "SUCCESS") + models_session.get_routes["v1/models/umap/u-1"] = model_card("umap/u-1") + + fitted = models.UMAP().fit(models.esm2.embed(SEQUENCES)).wait() + + assert isinstance(fitted, UMAPModel) + assert fitted.id == "umap/u-1" + + +class TestGP: + def test_fit_trains_on_the_embeddings_job_and_its_assay( + self, models, models_session + ): + x = models.esm2.embed(_assay()) + + future = models.GP(kernel="rbf", name="gp", description="d").fit(x) + + assert isinstance(future, GPFitFuture) + assert models_session.submissions[-1] == ( + "v1/models/gp", + { + "embeddings_job_id": x.id, + "kernel": {"type": "rbf"}, + "training_dataset": {"assay_id": ASSAY, "properties": ["fitness"]}, + "name": "gp", + "description": "d", + }, + ) + + @pytest.mark.parametrize( + "kernel, given", + [("periodic", {"period": 2.0}), ("rational_quadratic", {"alpha": 0.5})], + ) + def test_a_kernel_param_is_sent_with_its_kernel( + self, models, models_session, kernel, given + ): + models.GP(kernel=kernel, **given).fit(models.esm2.embed(_assay())) + + assert models_session.submissions[-1][1]["kernel"] == {"type": kernel, **given} + + @pytest.mark.parametrize( + "kernel, given", [("rbf", {"period": 2.0}), ("periodic", {"alpha": 0.5})] + ) + def test_a_kernel_param_is_sent_whatever_the_kernel( + self, models, models_session, kernel, given + ): + models.GP(kernel=kernel, **given).fit(models.esm2.embed(_assay())) + + assert models_session.submissions[-1][1]["kernel"] == { + "type": kernel, + **given, + } + + @pytest.mark.parametrize( + "x", + [ + lambda m: m.get_model("svd/s-1").transform(_assay()), + lambda m: m.SVD(n_components=2).fit(m.esm2.embed(_assay())), + ], + ids=["projection", "svd fit"], + ) + def test_a_job_is_named_by_id_with_no_wait( + self, models, models_session, distinct_ids, x + ): + x = x(models) + assert x.id != JOB_ID + + models.GP().fit(x) + + body = models_session.submissions[-1][1] + assert body["embeddings_job_id"] == x.id + assert "features" not in body + reads = [c.args[0] for c in models_session.session.get.call_args_list] + assert f"v1/jobs/{x.id}" not in reads + + def test_a_fitted_svd_as_model_featurizes_a_named_assay( + self, models, models_session + ): + models.GP().fit( + model=models.get_model("svd/s-1"), property="fitness", assay=ASSAY + ) + + assert models_session.submissions[-1][1] == { + "features": {"model_id": "svd/s-1"}, + "kernel": {"type": "rbf"}, + "training_dataset": {"assay_id": ASSAY, "properties": ["fitness"]}, + } + + def test_a_fitted_svd_as_x_trains_on_its_embeddings(self, models, models_session): + models.GP().fit(models.get_model("svd/s-1"), property="fitness", assay=ASSAY) + + body = models_session.submissions[-1][1] + assert body["embeddings_job_id"] == "s-1" + assert "features" not in body + + def test_a_system_model_featurizes_with_its_embedding_params( + self, models, models_session + ): + models.GP().fit( + model=models.esm2, assay=ASSAY, property="fitness", reduction="MEAN" + ) + + assert models_session.submissions[-1][1]["features"] == { + "model_id": ESM2, + "reduction": "MEAN", + } + + def test_a_lone_measurement_is_the_property(self, models, models_session): + models.GP().fit(models.esm2.embed(_assay("stability"))) + + training = models_session.submissions[-1][1]["training_dataset"] + assert training["properties"] == ["stability"] + + def test_several_measurements_need_a_property(self, models, models_session): + x = models.esm2.embed(_assay("fitness", "stability")) + models_session.session.get.reset_mock() + models_session.session.post.reset_mock() + + with pytest.raises(ValueError, match="fitness, stability"): + models.GP().fit(x) + models_session.session.get.assert_not_called() + models_session.session.post.assert_not_called() + + def test_embeddings_of_sequences_need_an_assay(self, models, models_session): + x = models.esm2.embed(SEQUENCES) + models_session.session.get.reset_mock() + models_session.session.post.reset_mock() + + with pytest.raises(ValueError, match="pass assay"): + models.GP().fit(x, property="fitness") + models_session.session.get.assert_not_called() + models_session.session.post.assert_not_called() + + def test_an_assay_named_with_a_job_is_the_one_trained_on( + self, models, models_session + ): + x = models.esm2.embed(_assay()) + + models.GP().fit(x, property="fitness", assay="assay-2") + + body = models_session.submissions[-1][1] + assert body["training_dataset"] == { + "assay_id": "assay-2", + "properties": ["fitness"], + } + + def test_an_svd_fit_of_an_assay_trains_on_that_assay(self, models, models_session): + assay = _assay() + fit = models.esm2.fit_svd(assay=assay, n_components=2, reduction="MEAN") + + models.GP().fit(fit) + + assert fit.dataset is assay + assert models_session.submissions[-1][1]["training_dataset"] == { + "assay_id": ASSAY, + "properties": ["fitness"], + } + + def test_a_submitted_fit_keeps_the_assay_it_trained_on(self, models): + assay = _assay() + + assert models.GP().fit(assay=assay).dataset is assay + + def test_a_submitted_fit_on_a_projection_keeps_its_assay(self, models): + assay = _assay() + + assert models.GP().fit(models.esm2.embed(assay)).dataset is assay + + def test_a_fit_from_a_model_handle_keeps_the_assay_it_trained_on( + self, models, monkeypatch + ): + assay = _assay() + + def no_lookup(self, *args, **kwargs): + raise AssertionError("the assay is not looked up") + + monkeypatch.setattr(DataAPI, "get", no_lookup) + + future = models.esm2.fit_gp(assay, ["fitness"], reduction="MEAN") + + assert future.dataset is assay + + def test_a_reloaded_fit_reads_its_assay_from_the_training_dataset( + self, models, models_session, monkeypatch + ): + assay = _assay() + + def as_dataset(session, assay_id): + assert assay_id == ASSAY + return assay + + monkeypatch.setattr(_inputs, "as_dataset", as_dataset) + models_session.get_routes["v1/jobs/gp-1/args"] = { + "training_dataset": {"assay_id": ASSAY, "properties": ["fitness"]} + } + job = Job.create( + SUBMITTED_JOB | {"job_id": "gp-1", "job_type": "/models/gp/fit"} + ) + + assert GPFitFuture(models.session, job).dataset is assay + + def test_an_assay_trains_on_empty_features(self, models, models_session): + models.GP().fit(assay=_assay()) + + body = models_session.submitted[1] + assert body["features"] == {} + assert body["training_dataset"] == { + "assay_id": ASSAY, + "properties": ["fitness"], + } + + def test_an_assay_as_x_raises(self, models, models_session): + with pytest.raises(TypeError, match="isn't an embeddings job"): + models.GP().fit(_assay()) + models_session.session.post.assert_not_called() + + def test_a_reloaded_legacy_svd_is_named_by_id_with_no_read( + self, models, models_session + ): + models.GP().fit( + MagicMock(spec=SVDFit, id="s-1"), property="fitness", assay=ASSAY + ) + + assert models_session.submitted[1]["embeddings_job_id"] == "s-1" + models_session.session.get.assert_not_called() + + def test_a_reloaded_embedding_trains_on_the_assay_it_embedded( + self, models, models_session, monkeypatch + ): + monkeypatch.setattr(_inputs, "as_dataset", lambda session, assay_id: _assay()) + models_session.get_routes["v1/jobs/e-1/args"] = {"assay_id": ASSAY} + x = Future(models.session, _reloaded_embeddings("e-1")) + + models.GP().fit(x) + + assert models_session.submitted[1]["training_dataset"] == { + "assay_id": ASSAY, + "properties": ["fitness"], + } + + def test_a_reloaded_embedding_is_named_with_no_read(self, models, models_session): + x = Future(models.session, _reloaded_embeddings("e-1")) + + models.GP().fit(x, property="fitness", assay=ASSAY) + + assert models_session.submitted[1]["embeddings_job_id"] == "e-1" + models_session.session.get.assert_not_called() + + def test_waiting_on_the_fit_returns_the_trained_gp( + self, models, models_session, model_card + ): + models_session.post_routes["v1/models/gp"] = _job("p-1", "SUCCESS") + models_session.get_routes["v1/jobs/p-1"] = _job("p-1", "SUCCESS") + models_session.get_routes["v1/models/gp/p-1"] = model_card("gp/p-1") + + trained = models.GP().fit(models.esm2.embed(_assay())).wait() + + assert isinstance(trained, GPModel) + assert trained.id == "gp/p-1" + + +class TestAccessors: + @pytest.mark.parametrize("name", ["SVD", "UMAP", "GP"]) + def test_each_is_its_estimator_class_bound_to_the_session( + self, models, models_session, name + ): + bound = getattr(models, name) + other = ModelsAPI(MagicMock()) + + assert bound.__name__ == name + assert issubclass(bound, {"SVD": SVD, "UMAP": UMAP, "GP": GP}[name]) + assert getattr(models, name) is bound + assert bound.session is models_session.session + assert getattr(other, name).session is other.session + + @pytest.mark.parametrize( + "call", + [lambda: GP(), lambda: SVD(256), lambda: UMAP.list()], + ids=["gp", "svd", "umap list"], + ) + def test_an_estimator_class_needs_a_session(self, call): + with pytest.raises(TypeError, match="use session.models"): + call() + + def test_a_call_constructs_an_estimator(self, models): + assert isinstance(models.GP(kernel="matern52"), GP) + assert models.SVD(256).n_components == 256 + assert models.UMAP().n_components is None + + @pytest.mark.parametrize("model_id", ["p-1", "gp/p-1"]) + def test_gp_by_id_reads_its_card(self, models, models_session, model_id): + gp = models.GP(id=model_id) + + assert isinstance(gp, GPModel) + assert gp.id == "gp/p-1" + models_session.session.get.assert_called_once_with("v1/models/gp/p-1") + + @pytest.mark.parametrize("model_id", ["s-1", "svd/s-1"]) + def test_svd_by_id_reads_its_card( + self, models, models_session, model_card, model_id + ): + models_session.get_routes["v1/models/svd/s-1"] = model_card("svd/s-1") | { + "svd": {"id": "s-1"} + } + + svd = models.SVD(id=model_id) + + assert isinstance(svd, SVDModel) + assert svd.id == "svd/s-1" + + def test_umap_by_id_reads_its_card(self, models): + umap = models.UMAP(id="u-1") + + assert isinstance(umap, UMAPModel) + assert umap.id == "umap/u-1" + + @pytest.mark.parametrize( + "kind, family", [("GP", "gp"), ("SVD", "svd"), ("UMAP", "umap")] + ) + def test_list_follows_every_page( + self, models, models_session, model_card, monkeypatch, kind, family + ): + monkeypatch.setattr("openprotein.models._api._LIST_PAGE", 2) + cards = [model_card(f"{family}/x-{i}") for i in range(3)] + if family == "svd": + cards = [card | {"svd": {"id": f"x-{i}"}} for i, card in enumerate(cards)] + pages = iter([cards[:2], cards[2:]]) + models_session.session.get.side_effect = lambda *a, **k: MagicMock( + json=MagicMock(return_value=next(pages)) + ) + + listed = getattr(models, kind).list() + + assert [m.id for m in listed] == [f"{family}/x-{i}" for i in range(3)] + assert [ + (call.kwargs["params"]["limit"], call.kwargs["params"]["offset"]) + for call in models_session.session.get.call_args_list + ] == [(2, 0), (2, 2)] + + @pytest.mark.parametrize( + "kind, family", [("GP", "gp"), ("SVD", "svd"), ("UMAP", "umap")] + ) + def test_list_reads_up_to_the_limit_from_the_offset( + self, models, models_session, model_card, kind, family + ): + listed = model_card(f"{family}/x-1") + if family == "svd": + listed |= {"svd": {"id": "x-1"}} + models_session.get_routes["v1/models"] = [listed] + + page = getattr(models, kind).list(limit=2, offset=4) + + assert [m.id for m in page] == [f"{family}/x-1"] + models_session.session.get.assert_called_once_with( + "v1/models", + params={ + "scope": "mine", + "type": family, + "verbose": "true", + "limit": 2, + "offset": 4, + }, + ) + + @pytest.mark.parametrize( + "call", + [ + lambda m: m.GP(id="p-1", kernel="rbf"), + lambda m: m.SVD(256, id="s-1"), + lambda m: m.UMAP(id="u-1", n_neighbors=5), + lambda m: m.GP(id="p-1", alpha=None), + ], + ids=["gp", "svd", "umap", "explicit none"], + ) + def test_id_with_hyperparameters_raises(self, models, models_session, call): + with pytest.raises(TypeError, match="pass id alone"): + call(models) + models_session.session.get.assert_not_called() + + +class TestPipelines: + def test_an_svd_then_a_gp_on_an_embedded_assay(self, models, models_session): + models_session.post_routes["v1/models/svd"] = _job("fit-1") + dataset = _assay() + + embeddings = models.esm2.embed(dataset) + svd = models.SVD(256) + projected = svd.fit_transform(embeddings) + gp = models.GP(kernel="rbf") + gp.fit(projected, property="fitness") + + assert models_session.submissions[1:] == [ + ( + "v1/models/svd", + { + "embeddings_job_id": embeddings.id, + "n_components": 256, + "output": "embeddings", + }, + ), + ( + "v1/models/gp", + { + "embeddings_job_id": projected.id, + "kernel": {"type": "rbf"}, + "training_dataset": { + "assay_id": ASSAY, + "properties": ["fitness"], + }, + }, + ), + ] + + def test_a_gp_on_an_assay_projected_through_an_svd_of_other_sequences( + self, models, models_session, model_card + ): + _svd_fit_succeeds(models_session, model_card, "fit-1") + models_session.post_routes["v1/models/svd/fit-1/batch/embeddings"] = _job( + "proj-2" + ) + dataset = _assay() + + embeddings = models.esm2.embed(["MKTW", "MKTY", "MKTV"]) + svd = models.SVD(256).fit_transform(embeddings) + dataset_embeddings = svd.transform(dataset) + gp = models.GP(kernel="rbf") + gp.fit(dataset_embeddings) + + assert models_session.submissions[-2:] == [ + ("v1/models/svd/fit-1/batch/embeddings", {"sequences": SEQUENCES}), + ( + "v1/models/gp", + { + "embeddings_job_id": dataset_embeddings.id, + "kernel": {"type": "rbf"}, + "training_dataset": { + "assay_id": ASSAY, + "properties": ["fitness"], + }, + }, + ), + ] + + def test_a_one_hot_gp_then_loading_and_listing( + self, models, models_session, model_card + ): + models_session.get_routes["v1/models"] = [model_card("gp/p-1")] + + models.GP(kernel="rbf").fit(assay=_assay()) + gp = models.GP(id="p-1") + gps = models.GP.list() + + assert models_session.submitted[1]["features"] == {} + assert gp.id == "gp/p-1" + assert [listed.id for listed in gps] == ["gp/p-1"] + + +def test_the_fitted_collections_are_gone(models): + import openprotein.models as package + + assert not any(hasattr(models, name) for name in ("svds", "umaps", "gps")) + assert not any(hasattr(package, name) for name in ("GPsAPI", "SVDsAPI", "UMAPsAPI")) + + +@pytest.mark.parametrize( + "fit, unset", + [ + (lambda m: m.SVD().fit(m.esm2.embed(SEQUENCES)), {"n_components"}), + ( + lambda m: m.UMAP().fit(m.esm2.embed(SEQUENCES)), + {"n_components", "n_neighbors", "min_dist"}, + ), + (lambda m: m.esm2.fit_svd(SEQUENCES, reduction="MEAN"), {"n_components"}), + ( + lambda m: m.esm2.fit_umap(SEQUENCES), + {"n_components", "n_neighbors", "min_dist"}, + ), + ], + ids=["SVD", "UMAP", "fit_svd", "fit_umap"], +) +def test_a_fit_leaves_unset_hyperparameters_to_the_server( + models, models_session, fit, unset +): + fit(models) + + assert not unset & set(models_session.submissions[-1][1]) + + +def test_a_fit_sends_the_hyperparameters_given(models, models_session): + models.UMAP(n_neighbors=5).fit(models.esm2.embed(SEQUENCES)) + + body = models_session.submissions[-1][1] + assert body["n_neighbors"] == 5 + assert not {"n_components", "min_dist"} & set(body) + + +@pytest.mark.parametrize( + "fit, error, match", + [ + (lambda m: m.SVD().fit(), TypeError, "pass X"), + ( + lambda m: m.SVD().fit(m.esm2.embed(SEQUENCES), model=m.esm2), + TypeError, + "pass X", + ), + ( + lambda m: m.UMAP().fit(m.esm2.embed(SEQUENCES), assay=ASSAY), + TypeError, + "go with model=", + ), + ( + lambda m: m.SVD().fit(m.esm2.embed(SEQUENCES), reduction="MEAN"), + TypeError, + "go with model=", + ), + (lambda m: m.SVD().fit(model=m.esm2), ValueError, "one of sequences or assay"), + ( + lambda m: m.UMAP().fit(model=m.esm2, sequences=SEQUENCES, assay=ASSAY), + ValueError, + "one of sequences or assay", + ), + ( + lambda m: m.GP().fit(m.esm2.embed(_assay()), model=m.esm2), + TypeError, + "not both", + ), + ( + lambda m: m.GP().fit(m.esm2.embed(_assay()), reduction="MEAN"), + TypeError, + "go with model=", + ), + (lambda m: m.GP().fit(model=m.esm2), ValueError, "pass X, or assay"), + ], + ids=[ + "neither", + "both", + "x with assay", + "x with params", + "model alone", + "model with both inputs", + "gp both", + "gp x with params", + "gp model without assay", + ], +) +def test_a_fit_with_the_wrong_sources_raises_before_any_request( + models, models_session, fit, error, match +): + models_session.session.post.reset_mock() + + with pytest.raises(error, match=match): + fit(models) + + assert not [ + c + for c in models_session.session.post.call_args_list + if c.args and str(c.args[0]).rstrip("/").endswith(("svd", "umap", "gp")) + ] + + +def _missing_card(models_session): + served = models_session.session.get.side_effect + + def get(path: str, **kwargs: Any): + if path == "v1/models/no-such-model": + raise HTTPError(MagicMock(status_code=404, text="not found")) + return served(path, **kwargs) + + return get + + +class TestFitFeatureModel: + """``model=`` is the only feature-model selector of a fit.""" + + @pytest.mark.parametrize("estimator", ["SVD", "UMAP", "GP"]) + def test_model_id_in_embedding_params_is_refused_before_any_request( + self, models, models_session, estimator + ): + fit = getattr(models, estimator)().fit + models_session.session.get.reset_mock() + models_session.session.post.reset_mock() + + with pytest.raises(TypeError, match="pass the model as model="): + fit(model=models.esm2, assay=ASSAY, property="fitness", model_id="prot-seq") + + models_session.session.get.assert_not_called() + models_session.session.post.assert_not_called() + + def test_a_model_handle_features_the_gp_as_is(self, models, models_session): + models.GP().fit( + model=models.esm2, assay=ASSAY, property="fitness", reduction="MEAN" + ) + + assert models_session.submissions[-1][1]["features"]["model_id"] == ESM2 + + def test_a_model_id_is_resolved_through_the_model_lookup( + self, models, models_session + ): + models.GP().fit(model=ESM2, assay=ASSAY, property="fitness", reduction="MEAN") + + assert models_session.submissions[-1][1]["features"] == { + "model_id": ESM2, + "reduction": "MEAN", + } + + @pytest.mark.parametrize("estimator", ["SVD", "UMAP", "GP"]) + def test_an_unknown_model_id_is_refused(self, models, models_session, estimator): + models_session.session.get.side_effect = _missing_card(models_session) + models_session.session.post.reset_mock() + kwargs: dict[str, Any] = ( + {"assay": ASSAY, "property": "fitness"} + if estimator == "GP" + else {"sequences": SEQUENCES} + ) + + with pytest.raises(ValueError): + getattr(models, estimator)().fit(model="no-such-model", **kwargs) + + models_session.session.post.assert_not_called() diff --git a/tests/models/test_folds.py b/tests/models/test_folds.py new file mode 100644 index 0000000..d1efdfd --- /dev/null +++ b/tests/models/test_folds.py @@ -0,0 +1,86 @@ +"""Checks on the custom folds of a cross-validation.""" + +import pytest + +from openprotein.errors import InvalidParameterError +from openprotein.models._folds import EXCLUDED_FOLD, MAX_NUM_FOLDS, validate_folds + + +def test_valid_folds_are_normalized_to_ints(): + assert validate_folds(folds=[0, 1, 0, 1], num_assay_rows=4) == [0, 1, 0, 1] + + +def test_numpy_folds_are_accepted(): + np = pytest.importorskip("numpy") + folds = np.array([0, 1, EXCLUDED_FOLD, 1, 0]) + out = validate_folds(folds=folds, num_assay_rows=5) + assert out == [0, 1, -1, 1, 0] + assert all(isinstance(f, int) for f in out) + + +def test_excluded_rows_are_allowed(): + assert validate_folds(folds=[0, EXCLUDED_FOLD, 1, 0, 1], num_assay_rows=5) == [ + 0, + -1, + 1, + 0, + 1, + ] + + +@pytest.mark.parametrize( + "folds", + [ + [0, 1, 0, 1], # each repeated sequence split across both folds + [0, 0, 1, 1], # each repeated sequence kept together in one fold + [0, 1, 1, 0], + ], +) +def test_folds_ignore_which_rows_share_a_sequence(folds): + """Folds are per row, so nothing couples rows that share a sequence.""" + assert validate_folds(folds=folds, num_assay_rows=4) == folds + + +@pytest.mark.parametrize( + "folds,num_assay_rows,message", + [ + ([0, 1, 0], 4, "expected one fold per row of the training assay (4), got 3"), + ( + [0, 1, 0, 1, 0], + 4, + "expected one fold per row of the training assay (4), got 5", + ), + ([0, 1, -2, 1], 4, "got -2 at row 2"), + ([0, 2, 0, 2], 4, "no row is in fold 1"), + ([1, 2, 1, 2], 4, "no row is in fold 0"), + ([0, 0, 0, 0], 4, "expected between 2 and 10 folds, got 1"), + ([EXCLUDED_FOLD] * 4, 4, "expected between 2 and 10 folds, got 0"), + (list(range(MAX_NUM_FOLDS + 1)), MAX_NUM_FOLDS + 1, "got 11"), + (["a", "b"], 2, "folds must all be integers"), + ], +) +def test_invalid_folds_are_rejected(folds, num_assay_rows: int, message: str): + with pytest.raises(InvalidParameterError) as e: + validate_folds(folds=folds, num_assay_rows=num_assay_rows) + assert message in str(e.value) + + +@pytest.mark.parametrize( + "bad", + [-0.9, 1.0, 1.9, "1", True, False], +) +def test_folds_refuse_non_integer_values(bad): + """Only integers are folds; floats, numeric strings and booleans are refused.""" + with pytest.raises(InvalidParameterError, match="folds must all be integers"): + validate_folds(folds=[0, 1, 0, 1, bad], num_assay_rows=5) + + +def test_folds_refuse_numpy_floats_and_booleans(): + """NumPy floats and booleans are refused, NumPy integers are accepted.""" + np = pytest.importorskip("numpy") + for bad in (np.float64(1.0), np.bool_(True)): + with pytest.raises(InvalidParameterError, match="folds must all be integers"): + validate_folds(folds=[0, 1, 0, 1, bad], num_assay_rows=5) + out = validate_folds(folds=[np.int8(0), np.int64(1)], num_assay_rows=2) + assert out == [0, 1] + assert all(type(f) is int for f in out) diff --git a/tests/models/test_future_outputs.py b/tests/models/test_future_outputs.py new file mode 100644 index 0000000..58b9997 --- /dev/null +++ b/tests/models/test_future_outputs.py @@ -0,0 +1,134 @@ +import inspect +from typing import Any + +import pytest + +from openprotein.jobs import Job, _dispatch, futures +from openprotein.jobs.futures import ( + EmbeddingFuture, + Future, + GPFitFuture, + StructureDesignFuture, + SVDFitFuture, + UMAPFitFuture, + _ResultFuture, + _Submission, +) +from openprotein.models.schemas import MethodDescriptor +from tests.models.test_future_results import ( + JOB, + METADATA, + UNITS, + _get_side_effect, +) + +_RESULT_FUTURES = [ + future_type + for future_type in vars(futures).values() + if isinstance(future_type, type) + and issubclass(future_type, _ResultFuture) + and future_type is not _ResultFuture +] + +PAYLOAD_OUTPUTS = ["from-the-job-payload"] + + +def _fit_job(family: str) -> Job: + return Job.model_validate( + { + "job_id": "fit-1", + "job_type": f"/models/{family}/fit", + "status": "SUCCESS", + "created_date": "2026-10-30T00:00:00Z", + "outputs": PAYLOAD_OUTPUTS, + } + ) + + +def test_task_outputs_come_from_the_model_listing_not_the_job_payload(mock_session): + mock_session.get.side_effect = _get_side_effect(UNITS, METADATA) + job = Job.model_validate(JOB | {"outputs": PAYLOAD_OUTPUTS}) + + assert Future(mock_session, job).outputs == ["embeddings", "annotations"] + + +def test_task_outputs_come_from_the_submitting_method_not_the_job_payload( + mock_session, +): + job = Job.model_validate(JOB | {"outputs": PAYLOAD_OUTPUTS}) + descriptor = MethodDescriptor(path="batch/embeddings", outputs=["embeddings"]) + submission = _Submission(job.job_type.split("/")[2], "batch/embeddings") + + future = _dispatch.create( + mock_session, job, descriptor=descriptor, submission=submission + ) + + assert future.outputs == ["embeddings"] + mock_session.get.assert_not_called() + + +def test_a_future_is_built_from_a_session_and_a_job(): + """The base future constructor accepts exactly a session and a job.""" + parameters = inspect.signature(Future.__init__).parameters + + assert list(parameters) == ["self", "session", "job"] + + +@pytest.mark.parametrize("future_type", [EmbeddingFuture, StructureDesignFuture]) +def test_a_result_future_is_built_from_a_session_and_a_job(future_type): + """A result future constructor accepts exactly a session and a job.""" + parameters = inspect.signature(future_type.__init__).parameters + + assert list(parameters) == ["self", "session", "job"] + + +@pytest.mark.parametrize("future_type", _RESULT_FUTURES) +def test_a_result_future_has_no_max_workers(mock_session, future_type): + """A result future reads through the job's output stream and has no worker count.""" + future = future_type(mock_session, Job.model_validate(JOB)) + + assert not hasattr(future, "max_workers") + + +@pytest.mark.parametrize( + ("family", "future_type", "expected"), + [ + ("gp", GPFitFuture, []), + ("svd", SVDFitFuture, ["sequences"]), + ("umap", UMAPFitFuture, ["sequences", "embeddings"]), + ], +) +def test_each_fit_future_lists_its_fixed_outputs( + mock_session, family, future_type, expected +): + future = future_type(mock_session, _fit_job(family)) + + assert future.outputs == expected + mock_session.get.assert_not_called() + + +@pytest.mark.parametrize( + ("future_type", "family", "default"), + [(SVDFitFuture, "svd", "sequences"), (UMAPFitFuture, "umap", "sequences")], +) +def test_a_fit_future_defaults_to_its_first_output( + mock_session, future_type, family, default +): + assert future_type(mock_session, _fit_job(family))._default_output == default + + +def test_a_gp_fit_future_has_no_default_output(mock_session): + with pytest.raises(ValueError, match="no outputs"): + _ = GPFitFuture(mock_session, _fit_job("gp"))._default_output + + +def test_fit_job_payload_fields_do_not_change_fit_outputs(mock_session): + payload: dict[str, Any] = _fit_job("svd").model_dump() | { + "outputs": ["components"], + "provider_id": "other", + "path": "/other", + } + + future = SVDFitFuture(mock_session, Job.model_validate(payload)) + + assert future.outputs == ["sequences"] diff --git a/tests/models/test_future_results.py b/tests/models/test_future_results.py new file mode 100644 index 0000000..a8e3478 --- /dev/null +++ b/tests/models/test_future_results.py @@ -0,0 +1,420 @@ +"""Fetching a models API job's results through Future.""" + +import hashlib +import io +from typing import Any +from unittest.mock import MagicMock + +import numpy as np +import pytest + +from openprotein.errors import HTTPError +from openprotein.jobs import Job +from openprotein.jobs.futures import Future + +MODEL_ID = "esm2_t33_650M_UR50D" + +METADATA: dict[str, Any] = { + "model_id": MODEL_ID, + "model_family": "esm2", + "name": None, + "version": None, + "is_system": True, + "base": True, + "tags": None, + "protein_types": None, + "description": {"summary": "ESM-2 650M protein language model."}, + "dimension": 1280, + "query": None, + "multichain": None, + "methods": [ + { + "path": "batch/embeddings", + "outputs": ["embeddings", "annotations"], + "description": "Per-residue embeddings.", + }, + ], + "max_sequence_length": 4094, +} + +JOB: dict[str, Any] = { + "job_id": "e0b1c3d4-0000-4000-8000-000000000001", + "job_type": f"/models/{MODEL_ID}/batch/embeddings", + "status": "SUCCESS", + "created_date": "2026-09-05T08:00:00Z", + "args": {"sequences": ["MKTAYIAK", "MEEP"]}, +} + +UNITS: list[dict[str, Any]] = [ + {"position": 0, "unit_id": "f0", "state": "SUCCESS"}, + {"position": 1, "unit_id": "f1", "state": "SUCCESS"}, +] + + +def _vector_bytes(values: list[float]) -> bytes: + buf = io.BytesIO() + np.save(buf, np.array(values)) + return buf.getvalue() + + +def _get_side_effect(units: list[dict], metadata: dict): + def handler(path: str, **kwargs): + response = MagicMock() + if path.endswith("/units"): + response.json.return_value = {"units": units, "next_position": None} + elif path == f"v1/models/{MODEL_ID}": + response.json.return_value = metadata + else: + raise AssertionError(f"unexpected GET {path}") + return response + + return handler + + +@pytest.fixture +def future(mock_session) -> Future: + mock_session.get.side_effect = _get_side_effect(UNITS, METADATA) + return Future(mock_session, Job.model_validate(JOB)) + + +class TestArgs: + def test_the_method_is_read_from_the_job_type(self, mock_session): + job = Job.model_validate(JOB | {"args": {"provider_id": "other"}}) + future = Future(mock_session, job) + + assert (future._model_id, future._path) == (MODEL_ID, "batch/embeddings") + mock_session.get.assert_not_called() + + def test_a_job_without_its_method_is_refreshed_once(self, mock_session): + bare = JOB | {"job_type": "/models"} + future = Future(mock_session, Job.model_validate(bare)) + mock_session.get.side_effect = None + mock_session.get.return_value.json.return_value = JOB + + assert future._model_id == MODEL_ID + assert future._path == "batch/embeddings" + mock_session.get.assert_called_once_with(f"v1/jobs/{JOB['job_id']}") + + def test_missing_args_are_fetched_from_the_jobs_api_and_cached(self, mock_session): + job_without_args = dict(JOB) + job_without_args["args"] = None + future = Future(mock_session, Job.model_validate(job_without_args)) + + def handler(path, **kwargs): + response = MagicMock() + if path == f"v1/jobs/{JOB['job_id']}/args": + response.json.return_value = JOB["args"] + else: + raise AssertionError(f"unexpected GET {path}") + return response + + mock_session.get.side_effect = handler + + assert future.args == JOB["args"] + assert future.args == JOB["args"] + + args_calls = [ + c for c in mock_session.get.call_args_list if c.args[0].endswith("/args") + ] + assert len(args_calls) == 1 + + +class TestUnits: + def test_units_are_cached_after_one_call(self, future, mock_session): + first = future.units + second = future.units + + assert first == second + assert [u.position for u in first] == [0, 1] + units_calls = [ + c for c in mock_session.get.call_args_list if c.args[0].endswith("/units") + ] + assert len(units_calls) == 1 + + +class TestDescriptor: + def test_metadata_is_fetched_once_across_calls(self, future, mock_session): + assert future.outputs == ["embeddings", "annotations"] + assert future._default_output == "embeddings" + assert future._descriptor.path == "batch/embeddings" + + model_calls = [ + c + for c in mock_session.get.call_args_list + if c.args[0] == f"v1/models/{MODEL_ID}" + ] + assert len(model_calls) == 1 + + +def _model_listing_calls(mock_session) -> list: + return [ + c for c in mock_session.get.call_args_list if c.args[0].startswith("v1/models") + ] + + +def _not_found() -> HTTPError: + response = MagicMock(status_code=404) + response.json.return_value = {"detail": "no such output"} + return HTTPError(response) + + +def _unauthorized() -> HTTPError: + response = MagicMock(status_code=401) + response.json.return_value = {"detail": "not authorized"} + return HTTPError(response) + + +class TestGetItem: + def test_without_output_resolves_the_default_from_the_bare_route( + self, future, mock_session + ): + job_id = JOB["job_id"] + + def handler(path, **kwargs): + response = MagicMock(status_code=200) + if path == f"v1/data/results/{job_id}": + assert kwargs == {"params": {"limit": 1}} + response.json.return_value = { + "values": [], + "next_cursor": None, + "output": "annotations", + } + elif path.startswith(f"v1/data/results/{job_id}/annotations/"): + assert kwargs == {} + response.json.return_value = { + "position": int(path.rsplit("/", 1)[1]), + "unit_id": "u", + "value": {"inline": "some text"}, + } + else: + raise AssertionError(f"unexpected GET {path}") + return response + + mock_session.get.side_effect = handler + + assert future.get_item(0) == "some text" + assert future.get_item(1) == "some text" + + paths = [c.args[0] for c in mock_session.get.call_args_list] + assert paths.count(f"v1/data/results/{job_id}") == 1 + assert _model_listing_calls(mock_session) == [] + + def test_with_output_reads_the_named_route_without_the_model_listing( + self, future, mock_session + ): + job_id = JOB["job_id"] + + def handler(path, **kwargs): + if path == f"v1/data/results/{job_id}/annotations/1": + response = MagicMock() + response.json.return_value = { + "position": 1, + "unit_id": "u", + "value": {"inline": "some text"}, + } + return response + raise AssertionError(f"unexpected GET {path}") + + mock_session.get.side_effect = handler + + assert future.get_item(1, output="annotations") == "some text" + assert _model_listing_calls(mock_session) == [] + + def test_an_output_the_method_lacks_is_the_servers_404(self, future, mock_session): + mock_session.get.side_effect = _not_found() + + with pytest.raises(HTTPError) as error: + future.get_item(0, output="not-a-real-output") + + assert error.value.status_code == 404 + mock_session.get.assert_called_once_with( + f"v1/data/results/{JOB['job_id']}/not-a-real-output/0" + ) + + def test_missing_default_output_is_not_guessed(self, future, mock_session): + response = MagicMock(status_code=200) + response.json.return_value = {"values": [], "next_cursor": None} + mock_session.get.side_effect = None + mock_session.get.return_value = response + + with pytest.raises(ValueError, match="do not name their output"): + future.get_item(0) + + mock_session.get.assert_called_once_with( + f"v1/data/results/{JOB['job_id']}", params={"limit": 1} + ) + + def test_default_resolution_propagates_authorization_failures( + self, future, mock_session + ): + mock_session.get.side_effect = _unauthorized() + + with pytest.raises(HTTPError) as error: + future.get_item(0) + + assert error.value.status_code == 401 + mock_session.get.assert_called_once_with( + f"v1/data/results/{JOB['job_id']}", params={"limit": 1} + ) + + +class TestStream: + def test_stream_decodes_canonical_references_in_position_order( + self, future, mock_session, monkeypatch + ): + 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 handler(path, **kwargs): + response = MagicMock(status_code=200) + if path == f"v1/data/results/{job_id}": + assert kwargs == {"params": {"limit": 1}} + response.json.return_value = { + "output": "embeddings", + "values": [{"value": {"unknown": 1}}], + "next_cursor": "ignored", + } + elif path == f"v1/data/results/{job_id}/embeddings": + assert kwargs == {} + response.json.return_value = { + "values": [ + { + "position": position, + "unit_id": f"u{position}", + "value": { + "ref": { + "uri": f"s3://content/{position}", + "byte_length": len(payload), + "sha256": hashlib.sha256(payload).hexdigest(), + "codec": "ndarray-v1", + } + }, + } + for position, payload in enumerate(payloads) + ], + "next_cursor": None, + } + else: + raise AssertionError(f"unexpected GET {path}") + return response + + mock_session.get.side_effect = handler + + results = list(future.stream()) + + np.testing.assert_array_equal(results[0], [1.0]) + np.testing.assert_array_equal(results[1], [2.0]) + assert _model_listing_calls(mock_session) == [] + + def test_an_output_the_method_lacks_is_the_servers_404(self, future, mock_session): + mock_session.get.side_effect = _not_found() + + with pytest.raises(HTTPError): + list(future.stream(output="not-a-real-output")) + + mock_session.get.assert_called_once_with( + f"v1/data/results/{JOB['job_id']}/not-a-real-output" + ) + + def test_malformed_canonical_value_raises(self, future, mock_session): + job_id = JOB["job_id"] + + def handler(path, **kwargs): + response = MagicMock(status_code=200) + if path == f"v1/data/results/{job_id}": + response.json.return_value = { + "values": [], + "next_cursor": None, + "output": "embeddings", + } + elif path == f"v1/data/results/{job_id}/embeddings": + response.json.return_value = { + "values": [ + {"position": 0, "unit_id": "u0", "value": {"unknown": 1}} + ], + "next_cursor": None, + } + else: + raise AssertionError(f"unexpected GET {path}") + return response + + mock_session.get.side_effect = handler + + with pytest.raises(ValueError, match="inline or ref"): + list(future.stream()) + + +class TestGet: + def test_get_resolves_the_default_then_pages_its_named_route( + self, future, mock_session + ): + job_id = JOB["job_id"] + page = { + "values": [ + {"position": 0, "unit_id": "u0", "value": {"inline": 1.0}}, + {"position": 1, "unit_id": "u1", "value": {"inline": 2.0}}, + ], + "next_cursor": None, + } + + def handler(path, **kwargs): + response = MagicMock(status_code=200) + if path == f"v1/data/results/{job_id}": + assert kwargs == {"params": {"limit": 1}} + response.json.return_value = {"output": "embeddings", "values": []} + elif path == f"v1/data/results/{job_id}/embeddings": + assert kwargs == {} + response.json.return_value = page + elif path == f"v1/data/results/{job_id}/annotations": + response.json.return_value = page + else: + raise AssertionError(f"unexpected GET {path}") + return response + + mock_session.get.side_effect = handler + + assert future.get(verbose=False) == [1.0, 2.0] + assert future.get(output="annotations") == [1.0, 2.0] + assert [c.args[0] for c in mock_session.get.call_args_list] == [ + f"v1/data/results/{job_id}", + f"v1/data/results/{job_id}/embeddings", + f"v1/data/results/{job_id}/annotations", + ] + + +def test_stream_reads_a_named_output_without_resolving_the_default( + future, mock_session +): + job_id = JOB["job_id"] + + def handler(path, **kwargs): + assert path == f"v1/data/results/{job_id}/embeddings" + response = MagicMock(status_code=200) + response.json.return_value = { + "values": [{"position": 0, "unit_id": "u0", "value": {"inline": [1.0]}}], + "next_cursor": None, + } + return response + + mock_session.get.side_effect = handler + + assert list(future.stream("embeddings")) == [[1.0]] + + +@pytest.mark.parametrize("argument", ["limit", "headers"]) +def test_stream_takes_only_its_own_arguments(future, argument): + with pytest.raises(TypeError, match="unexpected keyword argument"): + future.stream(**{argument: 1}) + + +@pytest.mark.parametrize("argument", ["limit", "headers"]) +def test_get_item_takes_only_its_own_arguments(future, argument): + with pytest.raises(TypeError, match="unexpected keyword argument"): + future.get_item(0, **{argument: 1}) diff --git a/tests/models/test_future_unit.py b/tests/models/test_future_unit.py new file mode 100644 index 0000000..8994b79 --- /dev/null +++ b/tests/models/test_future_unit.py @@ -0,0 +1,548 @@ +"""One unit of a models job, handled on its own.""" + +import inspect +from typing import Any +from unittest.mock import MagicMock + +import numpy as np +import pytest +from requests import Response + +import openprotein.jobs as jobs_package +from openprotein.errors import APIError, HTTPError, JobFailedException, TimeoutException +from openprotein.jobs import Job, JobStatus +from openprotein.jobs.futures import ( + EmbeddingFuture, + Future, + FutureUnit, +) +from openprotein.prompt import PromptJob + +MODEL_ID = "esm2_t33_650M_UR50D" + +JOB: dict[str, Any] = { + "job_id": "job-1", + "job_type": f"/models/{MODEL_ID}/batch/embeddings", + "status": "RUNNING", + "created_date": "2026-09-05T08:00:00Z", +} + +DEFAULT = "v1/data/results/job-1" +LISTING = "v1/jobs/job-1/units" + + +def _unit_record(position: int, state: str, **extra: Any) -> dict: + return { + "position": position, + "unit_id": f"u{position}", + "state": state, + "retries": 0, + } | extra + + +class _Recorder: + """Serves the unit, listing and result endpoints, recording every path fetched.""" + + def __init__( + self, + state: str = "SUCCESS", + positions: int = 2, + error: dict[str, Any] | None = None, + ) -> None: + self.paths: list[str] = [] + self.state = state + self.positions = positions + self.error = error + + def __call__(self, path: str, **kwargs: Any) -> MagicMock: + self.paths.append(path) + response = MagicMock() + if "/units/" in path: + position = int(path.rsplit("/", 1)[1]) + response.json.return_value = _unit_record( + position, self.state, error=self.error + ) + elif path == LISTING: + response.json.return_value = { + "units": [ + _unit_record(position, self.state, error={"message": "boom"}) + for position in range(self.positions) + ], + "next_position": None, + } + elif path.startswith("v1/models/"): + raise AssertionError("a read must not consult the model listing") + elif path == DEFAULT: + assert kwargs["params"] == {"limit": 1} + response.json.return_value = { + "values": [], + "next_cursor": None, + "output": "embeddings", + } + elif "/results" in path: + output = "annotations" if "/annotations/" in path else "embeddings" + response.json.return_value = { + "position": int(path.rsplit("/", 1)[1]), + "unit_id": "unit", + "value": { + "inline": "some text" if output == "annotations" else [1.0, 2.0] + }, + } + else: + raise AssertionError(f"unexpected GET {path}") + return response + + def unit_reads(self, position: int) -> int: + return self.paths.count(f"v1/jobs/job-1/units/{position}") + + +@pytest.fixture +def recorder() -> _Recorder: + return _Recorder() + + +@pytest.fixture +def future(mock_session, recorder) -> Future: + mock_session.get.side_effect = recorder + return Future(mock_session, Job.model_validate(JOB)) + + +def _future_in(mock_session, state: str, **kwargs: Any) -> Future: + mock_session.get.side_effect = _Recorder(state=state, **kwargs) + return Future(mock_session, Job.model_validate(JOB)) + + +class TestSelection: + def test_a_unit_defaults_to_the_output_the_bare_route_names(self, future, recorder): + assert future.unit(0).output == "embeddings" + assert future.unit(1).output == "embeddings" + + assert recorder.paths == [DEFAULT] + + def test_a_unit_can_name_any_output(self, future, recorder): + assert future.unit(0, output="annotations").output == "annotations" + + assert recorder.paths == [] + + +class TestLaziness: + def test_creating_a_unit_fetches_nothing(self, future, recorder): + unit = future.unit(0) + future.unit(0, output="embeddings") + future.unit(1, output="annotations") + repr(unit) + + assert recorder.paths == [] + + def test_the_snapshot_is_read_from_one_position(self, future, recorder): + unit = future.unit(1, output="embeddings") + + assert unit.unit_id == "u1" + assert recorder.paths == ["v1/jobs/job-1/units/1"] + + def test_the_snapshot_is_read_once(self, future, recorder): + unit = future.unit(0) + assert unit.unit_id == "u0" + assert unit.status is JobStatus.SUCCESS + assert unit.error is None + + assert recorder.unit_reads(0) == 1 + + def test_refresh_reads_the_position_again(self, future, recorder): + unit = future.unit(0) + assert unit.status is JobStatus.SUCCESS + unit.refresh() + assert unit.status is JobStatus.SUCCESS + + assert recorder.unit_reads(0) == 2 + + def test_a_unit_carries_its_coordinate_without_fetching(self, future, recorder): + unit = future.unit(3, output="annotations") + + assert (unit.job_id, unit.position, unit.output) == ("job-1", 3, "annotations") + assert recorder.paths == [] + + +class TestListing: + def test_listed_units_hold_their_record_as_the_snapshot(self, future, recorder): + units = future.units + + assert all(isinstance(unit, FutureUnit) for unit in units) + assert [(u.position, u.unit_id, u.status) for u in units] == [ + (0, "u0", JobStatus.SUCCESS), + (1, "u1", JobStatus.SUCCESS), + ] + assert [unit.error for unit in units] == [{"message": "boom"}] * 2 + assert recorder.paths == [LISTING] + + def test_reading_units_does_not_request_the_default_output(self, future, recorder): + _ = future.units + + assert recorder.paths == [LISTING] + + def test_a_listed_unit_and_a_requested_unit_agree(self, future): + listed = future.units[1] + requested = future.unit(1) + + assert type(listed) is type(requested) is FutureUnit + assert (listed.job_id, listed.position, listed.output) == ( + requested.job_id, + requested.position, + requested.output, + ) + + def test_units_are_in_position_order(self, future, mock_session): + def handler(path: str, **kwargs: Any) -> MagicMock: + response = MagicMock() + response.json.return_value = { + "units": [_unit_record(2, "RUNNING"), _unit_record(0, "RUNNING")], + "next_position": None, + } + return response + + mock_session.get.side_effect = handler + + assert [unit.position for unit in future.units] == [0, 2] + + def test_a_result_future_selects_its_primary_output(self, mock_session, recorder): + mock_session.get.side_effect = recorder + future = EmbeddingFuture(mock_session, Job.model_validate(JOB)) + + assert [unit.output for unit in future.units] == ["embeddings", "embeddings"] + assert recorder.paths == [LISTING] + + +class TestListingLifetime: + @pytest.fixture + def listed(self, future, recorder, monkeypatch): + monkeypatch.setattr("openprotein.jobs.futures.time.sleep", lambda seconds: None) + done = Job.model_validate(JOB | {"status": "SUCCESS"}) + monkeypatch.setattr(Future, "_refresh_job", lambda self, timeout=None: done) + monkeypatch.setattr(Future, "_wait_job", lambda self, **kwargs: done) + monkeypatch.setattr(Future, "get", lambda self, **kwargs: None) + return future, recorder + + @pytest.mark.parametrize("reload", ["refresh", "wait_until_done", "wait"]) + def test_units_are_read_again_after_the_job_is_polled(self, listed, reload): + future, recorder = listed + first = future.units + assert future.units is first + assert recorder.paths.count(LISTING) == 1 + + getattr(future, reload)() + second = future.units + + assert second is not first + assert second is future.units + assert recorder.paths.count(LISTING) == 2 + + def test_a_handle_keeps_its_snapshot_across_a_poll(self, listed): + future, recorder = listed + unit = future.units[0] + + future.refresh() + + assert unit.status is JobStatus.SUCCESS + assert recorder.unit_reads(0) == 0 + + +class TestRetrieval: + def test_get_decodes_only_the_selected_position(self, future, recorder): + value = future.unit(1).get() + + np.testing.assert_array_equal(value, np.array([1.0, 2.0])) + assert "v1/data/results/job-1/embeddings/1" in recorder.paths + + 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: + response = Response() + response.status_code = 404 + response.url = path + response._content = b'{"detail": "no output is stored"}' + return HTTPError(response) + + +class TestFailedUnitRead: + def test_get_raises_for_a_snapshot_that_is_failed(self, mock_session): + future = _future_in(mock_session, "FAILED", error={"message": "boom"}) + unit = future.units[0] + + with pytest.raises(JobFailedException) as raised: + unit.get() + + assert raised.value.failure_message == "unit 0 failed: boom" + + def test_get_raises_for_a_snapshot_that_is_canceled(self, mock_session): + unit = _future_in(mock_session, "CANCELED").units[0] + + with pytest.raises(JobFailedException) as raised: + unit.get() + + assert raised.value.failure_message == "unit 0 was canceled" + + def test_a_missing_output_refreshes_and_raises_for_a_failed_unit( + self, mock_session + ): + 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( + 0, output="embeddings" + ) + + with pytest.raises(JobFailedException) as raised: + unit.get() + + assert raised.value.failure_message == "unit 0 failed: boom" + 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( + 0, output="embeddings" + ) + + with pytest.raises(HTTPError) as raised: + unit.get() + + 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") + + mock_session.get.side_effect = handler + unit = Future(mock_session, Job.model_validate(JOB)).unit( + 0, output="embeddings" + ) + + with pytest.raises(HTTPError) as raised: + unit.get() + + assert raised.value.status_code == 404 + assert isinstance(raised.value.__cause__, ConnectionError) + + def test_a_successful_read_requests_no_unit_status(self, future, recorder): + future.unit(0, output="embeddings").get() + + assert recorder.unit_reads(0) == 0 + + +class TestStatus: + @pytest.mark.parametrize( + ("state", "status", "done"), + [ + ("PENDING", JobStatus.PENDING, False), + ("READY", JobStatus.PENDING, False), + ("RUNNING", JobStatus.RUNNING, False), + ("SUCCESS", JobStatus.SUCCESS, True), + ("FAILED", JobStatus.FAILURE, True), + ("CANCELED", JobStatus.CANCELED, True), + ], + ) + def test_done_reads_the_snapshot(self, mock_session, state, status, done): + future = _future_in(mock_session, state) + unit = future.units[0] + reads = mock_session.get.call_count + + assert unit.status is status + assert unit.done() is done + assert mock_session.get.call_count == reads + + def test_a_stored_unit_is_done_while_its_job_runs(self, future): + assert future.status is JobStatus.RUNNING + assert future.unit(0).done() is True + + +class TestWait: + def test_wait_returns_the_value_of_a_successful_unit(self, future): + np.testing.assert_array_equal(future.unit(0).wait(), np.array([1.0, 2.0])) + + def test_wait_refreshes_until_the_unit_is_done(self, mock_session, monkeypatch): + states = iter(["PENDING", "RUNNING", "SUCCESS"]) + recorder = _Recorder() + + def handler(path: str, **kwargs: Any) -> MagicMock: + response = recorder(path, **kwargs) + if "/units/" in path: + response.json.return_value = _unit_record(0, next(states)) + return response + + mock_session.get.side_effect = handler + monkeypatch.setattr("openprotein.jobs.futures.time.sleep", lambda seconds: None) + future = Future(mock_session, Job.model_validate(JOB)) + + future.unit(0).wait() + + assert recorder.unit_reads(0) == 3 + + def test_wait_times_out_on_an_unfinished_unit(self, mock_session): + future = _future_in(mock_session, "PENDING") + + with pytest.raises(TimeoutException): + 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"}) + + with pytest.raises(JobFailedException) as raised: + future.unit(0).wait() + + assert raised.value.job_id == "job-1" + 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") + + with pytest.raises(JobFailedException) as raised: + future.unit(1).wait() + + assert raised.value.job_id == "job-1" + assert raised.value.failure_message == "unit 1 failed" + + def test_a_canceled_unit_raises_job_failed(self, mock_session): + future = _future_in(mock_session, "CANCELED") + + with pytest.raises(JobFailedException) as raised: + future.unit(0).wait() + + assert raised.value.job_id == "job-1" + assert raised.value.failure_message == "unit 0 was canceled" + + +class TestFailedPosition: + """A position whose entry reports an error and no value raises on every read.""" + + @pytest.fixture + def failed(self, mock_session) -> Future: + def handler(path: str, **kwargs: Any) -> MagicMock: + response = MagicMock(status_code=200) + if path == DEFAULT: + response.json.return_value = {"values": [], "output": "embeddings"} + elif path == f"{DEFAULT}/embeddings": + response.json.return_value = { + "values": [{"position": 0, "unit_id": "u0", "error": "boom"}], + "next_cursor": None, + } + elif path == f"{DEFAULT}/embeddings/0": + response.json.return_value = { + "position": 0, + "unit_id": "u0", + "error": "boom", + } + else: + raise AssertionError(f"unexpected GET {path}") + return response + + mock_session.get.side_effect = handler + return Future(mock_session, Job.model_validate(JOB)) + + @pytest.mark.parametrize( + "read", + [ + lambda future: future.get_item(0), + lambda future: list(future.stream()), + lambda future: future.unit(0).get(), + lambda future: future.get(), + ], + ids=["get_item", "stream", "unit.get", "get"], + ) + def test_a_read_raises_job_failed_with_the_job_id(self, failed, read): + with pytest.raises(JobFailedException) as raised: + read(failed) + + assert raised.value.job_id == "job-1" + assert raised.value.failure_message == "output at position 0 failed: boom" + + +class TestSurface: + def test_a_unit_exposes_its_protocol_fields(self, future): + unit = future.unit(0) + + for name in ( + "job_id", + "position", + "output", + "unit_id", + ): + assert hasattr(unit, name), name + + def test_a_unit_has_no_state(self): + assert not hasattr(FutureUnit, "state") + + def test_a_future_has_no_iter_units(self): + assert not hasattr(Future, "iter_units") + + @pytest.mark.parametrize("name", ["Unit", "UnitState"]) + def test_the_jobs_package_has_no_unit_record(self, name): + assert not hasattr(jobs_package, name) + assert name not in jobs_package.__all__ + + +def test_a_sampling_job_reads_its_prompt_without_the_model_listing(mock_session): + """The sampling provider is not in the model listing; reads must not need it.""" + + def handler(path: str, **kwargs: Any) -> MagicMock: + response = MagicMock() + if path == "v1/data/results/sample-1/prompt/0": + response.json.return_value = { + "position": 0, + "unit_id": "u0", + "state": "SUCCESS", + "value": {"inline": "prompt"}, + } + elif path == "v1/jobs/sample-1/units/0": + response.json.return_value = _unit_record(0, "SUCCESS") + else: + raise AssertionError(f"unexpected GET {path}") + return response + + mock_session.get.side_effect = handler + job = Job.create( + JOB + | { + "job_id": "sample-1", + "job_type": "/prompt/sample_msa", + } + ) + assert isinstance(job, PromptJob) + unit = Future(mock_session, job).unit(0, output="prompt") + + assert unit.wait(timeout=0) == "prompt" + assert all( + not c.args[0].startswith("v1/models") for c in mock_session.get.call_args_list + ) + + +def test_a_job_outside_the_models_api_has_no_outputs(mock_session): + job = Job.create(JOB | {"job_type": "/align/prompt"}) + future = Future(mock_session, job) + + for read in (lambda: future.units, lambda: future.unit(0)): + with pytest.raises(APIError, match="has no stored outputs"): + read() + mock_session.get.assert_not_called() + + +def test_a_unit_is_built_from_a_future_a_position_and_an_output(): + parameters = list(inspect.signature(FutureUnit).parameters) + + assert parameters == ["future", "position", "output"] diff --git a/tests/models/test_handles.py b/tests/models/test_handles.py new file mode 100644 index 0000000..c814977 --- /dev/null +++ b/tests/models/test_handles.py @@ -0,0 +1,796 @@ +"""Family handles convert SDK objects to card params.""" + +import copy +import inspect +from typing import Any +from unittest.mock import MagicMock + +import pytest + +from openprotein.align.msa import MSAFuture +from openprotein.errors import HTTPError +from openprotein.jobs import Job, JobStatus +from openprotein.jobs.futures import Future +from openprotein.models import ( + ESMIF1, + BoltzGen, + ModelsAPI, + PoET, + PoET2, + ProteinMPNN, + ProtSeq, + RFdiffusion, + StructureGenerationFuture, + StructureGenerationJob, +) +from openprotein.models.schemas import MethodDescriptor +from openprotein.molecules import Complex, Protein +from openprotein.prompt import Query +from openprotein.prompt.schemas import QueryMetadata +from tests.models import support +from tests.models.support import PARAMS, created_query + +QUERY_UUID = "c0ffee00-0000-4000-8000-000000000001" + + +def _query(session, query_id: str = QUERY_UUID) -> Query: + return Query( + session, + QueryMetadata(id=query_id, created_date="2026-10-21T08:00:00Z"), + ) + + +DESIGN_UUID = "d0000000-0000-4000-8000-000000000001" + + +def _design(session, status: str = "SUCCESS") -> Future: + job = Job.model_validate( + { + "job_id": DESIGN_UUID, + "job_type": "/models/rfdiffusion/generate/structures", + "status": status, + "created_date": "2026-10-21T08:00:00Z", + } + ) + future = Future(session, job) + future._resolved_descriptor = MethodDescriptor( + path="generate/structures", outputs=["structures"] + ) + return future + + +@pytest.fixture +def models(models_session) -> ModelsAPI: + return ModelsAPI(models_session.session) + + +class TestSeeds: + @pytest.mark.parametrize( + "call", + [ + lambda m: m.poet.generate(prompt="prompt-1"), + lambda m: m.proteinmpnn.generate(query=QUERY_UUID), + lambda m: m.esmif1.generate(query=QUERY_UUID), + lambda m: m.rfdiffusion.generate(query_id=QUERY_UUID), + lambda m: m.boltzgen.generate(query_id=QUERY_UUID), + ], + ids=["poet", "proteinmpnn", "esm-if1", "rfdiffusion", "boltzgen"], + ) + def test_an_unset_random_seed_is_not_sent(self, models, models_session, call): + call(models) + + assert "random_seed" not in models_session.submitted[1] + + def test_a_given_random_seed_is_kept(self, models, models_session): + models.poet.generate(prompt="prompt-1", random_seed=7) + + assert models_session.submitted[1]["random_seed"] == 7 + + def test_a_425_resubmit_sends_the_same_body_again( + self, models, models_session, monkeypatch + ): + monkeypatch.setattr("openprotein.jobs._submission.time.sleep", lambda _: None) + pending = MagicMock(status_code=425, headers={"Retry-After": "0"}) + accepted = models_session._post + answers = iter([HTTPError(pending)]) + + def post(path, **kwargs): + if path != "v1/prompt/query": + error = next(answers, None) + if error is not None: + accepted(path, **kwargs) + raise error + return accepted(path, **kwargs) + + models_session.session.post.side_effect = post + + models.proteinmpnn.generate(query=QUERY_UUID) + + first, second = models_session.submissions + 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 + ): + models.proteinmpnn.score(["MKT"], query=QUERY_UUID) + + assert "random_seed" not in models_session.submitted[1] + + +class TestPrompt: + def test_a_prompt_object_sends_its_id(self, models, models_session): + from openprotein.data.prompts.prompts import Prompt + from openprotein.data.prompts.schemas import PromptSummary + + prompt = Prompt( + models_session.session, + PromptSummary(id="prompt-1", created_at="2026-10-21T08:00:00Z"), + ) + + models.poet.score(["MKT"], prompt=prompt) + + assert models_session.submitted == ( + "v1/models/poet/batch/loglikelihood", + {"sequences": ["MKT"], "prompt_id": "prompt-1"}, + ) + + @pytest.mark.parametrize(("model", "verb"), [("poet", "score"), ("poet2", "embed")]) + def test_a_prompt_that_is_not_ready_sends_its_id( + self, models, models_session, model, verb + ): + from openprotein.data.prompts import Prompt, PromptSummary + + prompt = Prompt( + models_session.session, + PromptSummary(id="prompt-9", status=JobStatus.PENDING, job_id="prompt-9"), + ) + + getattr(getattr(models, model), verb)(["MKT"], prompt=prompt) + + assert models_session.submitted[1]["prompt_id"] == "prompt-9" + + def test_prompt_and_prompt_id_together_are_refused(self, models, models_session): + with pytest.raises(TypeError, match="prompt or prompt_id"): + models.poet.score(["MKT"], prompt="a", prompt_id="b") + assert models_session.submissions == [] + + @pytest.mark.parametrize("prompt", [1, b"prompt", ["prompt-1"]]) + def test_a_wrong_prompt_type_raises_before_any_request( + self, models, models_session, prompt + ): + with pytest.raises(TypeError, match="prompt must be"): + models.poet2.embed(["MKT"], prompt=prompt) + models_session.session.post.assert_not_called() + + +class TestQuery: + def test_a_sequence_creates_a_query(self, models, models_session): + models.poet2.embed(["MKT"], query="MKT") + + assert [name for name, _ in models_session.queries] == ["query.fasta"] + assert models_session.submitted[1]["query_id"] == created_query(1) + + def test_a_query_id_or_query_object_sends_its_id(self, models, models_session): + models.poet2.embed(["MKT"], query=QUERY_UUID) + models.poet2.embed(["MKT"], query=_query(models_session.session)) + + assert [body["query_id"] for _, body in models_session.submissions] == [ + QUERY_UUID, + QUERY_UUID, + ] + assert models_session.queries == [] + + def test_a_protein_and_a_complex_create_queries(self, models, models_session): + protein = Protein(sequence="MKT") + complex = Complex({"A": Protein(sequence="MKT"), "B": Protein(sequence="AC")}) + + models.poet2.generate(query=[protein, complex], random_seed=1) + + assert models_session.submitted[1]["query_id"] == [ + created_query(1), + created_query(2), + ] + assert len(models_session.queries) == 2 + + @pytest.mark.parametrize("query", [1, {"id": QUERY_UUID}, [QUERY_UUID, 2]]) + def test_a_wrong_query_type_raises_before_any_request( + self, models, models_session, query + ): + with pytest.raises(TypeError, match="query must be"): + models.poet2.generate(query=query) + models_session.session.post.assert_not_called() + + +class TestDesign: + @pytest.mark.parametrize("status", ["PENDING", "RUNNING", "SUCCESS"]) + def test_a_design_is_sent_as_its_id_whatever_its_status( + self, models, models_session, status + ): + design = _design(models_session.session, status=status) + + models.proteinmpnn.generate(design=design, random_seed=1) + + assert models_session.submitted == ( + "v1/models/proteinmpnn/generate/sequences", + {"design_id": DESIGN_UUID, "random_seed": 1}, + ) + assert models_session.queries == [] + + def test_a_design_id_is_sent_as_it_is(self, models, models_session): + models.esmif1.generate(design=DESIGN_UUID) + + assert models_session.submitted == ( + "v1/models/esm-if1/generate/sequences", + {"design_id": DESIGN_UUID}, + ) + + def test_a_legacy_structure_generation_future_sends_its_id( + self, models, models_session + ): + job = StructureGenerationJob( + job_id=DESIGN_UUID, + job_type="/models/design", + status=JobStatus.RUNNING, + created_date="2026-10-21T08:00:00Z", + ) + design = StructureGenerationFuture(models_session.session, job, N=1) + + models.esmif1.generate(design=design, random_seed=1) + + assert models_session.submitted[1] == { + "design_id": DESIGN_UUID, + "random_seed": 1, + } + + @pytest.mark.parametrize( + "kwargs", + [ + {"query": QUERY_UUID}, + {"query_id": QUERY_UUID}, + ], + ids=["query", "query_id"], + ) + def test_a_query_and_a_design_are_refused_before_any_upload( + self, models, models_session, kwargs + ): + with pytest.raises(TypeError, match="pass query or design, not both"): + models.proteinmpnn.generate( + design=_design(models_session.session), **kwargs + ) + assert models_session.queries == [] + models_session.session.post.assert_not_called() + + def test_a_design_and_a_design_id_are_refused(self, models, models_session): + with pytest.raises(TypeError, match="pass design or design_id, not both"): + models.proteinmpnn.generate( + design=_design(models_session.session), design_id=DESIGN_UUID + ) + models_session.session.post.assert_not_called() + + def test_generating_from_neither_a_query_nor_a_design_is_refused( + self, models, models_session + ): + with pytest.raises(TypeError, match="needs a query or a design"): + models.proteinmpnn.generate() + models_session.session.post.assert_not_called() + + @pytest.mark.parametrize( + "path, call", + [ + ( + "esm-if1/generate/sequences", + lambda m: m.esmif1.generate(query=[QUERY_UUID]), + ), + ( + "proteinmpnn/single-site/scores", + lambda m: m.proteinmpnn.single_site("MKT", query=[QUERY_UUID]), + ), + ( + "rfdiffusion/generate/structures", + lambda m: m.rfdiffusion.generate(query=[QUERY_UUID]), + ), + ], + ids=["esm-if1 generate", "proteinmpnn single site", "rfdiffusion"], + ) + def test_one_query_in_a_list_is_sent_as_its_id( + self, models, models_session, path, call + ): + call(models) + + submitted_path, body = models_session.submitted + assert submitted_path == f"v1/models/{path}" + assert body["query_id"] == QUERY_UUID + + def test_a_wrong_design_type_raises_before_any_request( + self, models, models_session + ): + with pytest.raises(TypeError, match="design must be"): + models.proteinmpnn.generate(query="MKT", design="design-1") + models_session.session.post.assert_not_called() + + def test_a_future_that_is_not_a_design_raises_before_any_request( + self, models, models_session + ): + """A future whose job serves no outputs is refused by type, with no request.""" + job = Job.model_validate( + { + "job_id": "msa-1", + "job_type": "/align/mafft", + "status": "SUCCESS", + "created_date": "2026-10-21T08:00:00Z", + } + ) + msa = MSAFuture(models_session.session, job) + models_session.session.get.reset_mock() + + with pytest.raises(TypeError, match="MSAFuture"): + models.proteinmpnn.generate(design=msa) + models_session.session.get.assert_not_called() + models_session.session.post.assert_not_called() + + def test_a_models_job_of_another_method_is_not_a_design( + self, models, models_session + ): + job = Job.model_validate( + { + "job_id": DESIGN_UUID, + "job_type": "/models/esm2_t6_8M_UR50D/batch/embeddings", + "status": "SUCCESS", + "created_date": "2026-10-21T08:00:00Z", + } + ) + models_session.session.get.reset_mock() + + with pytest.raises(TypeError, match="not generate/structures"): + models.proteinmpnn.generate(design=Future(models_session.session, job)) + models_session.session.get.assert_not_called() + models_session.session.post.assert_not_called() + + @pytest.mark.parametrize( + "call", + [ + lambda m, d: m.esmif1.generate(query=["MKT", "MKV"]), + lambda m, d: m.proteinmpnn.score(["MKT"], query=["MKT", "MKV"]), + lambda m, d: m.poet2.single_site("MKT", query=["MKT", "MKV"]), + lambda m, d: m.rfdiffusion.generate(query=["MKT", "MKV"]), + ], + ids=["esm-if1 list", "score", "single site", "rfdiffusion"], + ) + def test_several_queries_to_a_one_query_method_raise_before_any_upload( + self, models, models_session, call + ): + with pytest.raises(ValueError, match="takes one query, not 2"): + call(models, None) + assert models_session.queries == [] + models_session.session.post.assert_not_called() + + @pytest.mark.parametrize( + "model_id, call", + [ + ( + "rfdiffusion", + lambda m: m.rfdiffusion.generate(query=[QUERY_UUID, QUERY_UUID]), + ), + ( + "boltzgen", + lambda m: m.boltzgen.generate(query=[QUERY_UUID, QUERY_UUID]), + ), + ], + ) + def test_a_structure_design_takes_several_queries_where_its_query_id_takes_a_list( + self, models, models_session, monkeypatch, model_id, call + ): + path = f"{model_id}/generate/structures" + schema = copy.deepcopy(PARAMS["methods"][path]["params"]) + schema["properties"]["query_id"] = PARAMS["methods"][ + "proteinmpnn/generate/sequences" + ]["params"]["properties"]["query_id"] + models_session.get_routes[f"v1/models/{path}/params"] = schema + monkeypatch.setattr(support, "check_body", lambda path, body: None) + + call(models) + + assert models_session.submitted[1]["query_id"] == [QUERY_UUID, QUERY_UUID] + + @pytest.mark.parametrize( + "model_id, call", + [ + ( + "proteinmpnn", + lambda m: m.proteinmpnn.generate(query=[QUERY_UUID, QUERY_UUID]), + ), + ("poet-2", lambda m: m.poet2.generate(query=[QUERY_UUID, QUERY_UUID])), + ], + ) + def test_a_generate_takes_one_query_where_its_query_id_takes_no_list( + self, models, models_session, model_id, call + ): + path = f"{model_id}/generate/sequences" + schema = copy.deepcopy(PARAMS["methods"][path]["params"]) + schema["properties"]["query_id"] = PARAMS["methods"][ + "esm-if1/generate/sequences" + ]["params"]["properties"]["query_id"] + models_session.get_routes[f"v1/models/{path}/params"] = schema + + with pytest.raises(ValueError, match="takes one query, not 2"): + call(models) + models_session.session.post.assert_not_called() + + +class TestPLM: + @pytest.mark.parametrize( + "alias, model_id", + [("esm2", "esm2_t33_650M_UR50D"), ("esmc_300m", "esmc-300m")], + ) + def test_esm2_and_esmc_score_single_site_mutants( + self, models, models_session, alias, model_id + ): + getattr(models, alias).single_site(b"MKT") + + assert models_session.submitted == ( + f"v1/models/{model_id}/single-site/scores", + {"base_sequence": "MKT"}, + ) + + @pytest.mark.parametrize("alias", ["prot_seq", "ablang2", "prott5_xl", "poet"]) + def test_embed_pools_by_mean_by_default(self, models, models_session, alias): + getattr(models, alias).embed(["MKT"]) + + assert models_session.submitted[1]["reduction"] == "MEAN" + + 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 + + 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"}, + ) + + def test_fit_svd_submits_the_fit(self, models, models_session): + models.esm2.fit_svd(["MKT"], n_components=8, reduction="MEAN") + + assert models_session.submitted == ( + "v1/models/svd", + { + "n_components": 8, + "output": "embeddings", + "sequences": ["MKT"], + "model_id": "esm2_t33_650M_UR50D", + "reduction": "MEAN", + }, + ) + + def test_fit_umap_submits_the_fit_with_its_defaults(self, models, models_session): + models.prot_seq.fit_umap(["MKT", "AC", "DE", "FG"]) + + assert models_session.submitted == ( + "v1/models/umap", + { + "model_id": "prot-seq", + "sequences": ["MKT", "AC", "DE", "FG"], + "reduction": "MEAN", + }, + ) + + def test_fit_gp_submits_the_training(self, models, models_session): + models.ablang2.fit_gp("assay-1", ["fitness"], reduction="MEAN") + + assert models_session.submitted == ( + "v1/models/gp", + { + "features": { + "model_id": "ablang2", + "reduction": "MEAN", + }, + "kernel": {"type": "rbf"}, + "training_dataset": { + "assay_id": "assay-1", + "properties": ["fitness"], + }, + }, + ) + + def test_poet2_fits_carry_its_embedding_params(self, models, models_session): + models.poet2.fit_svd( + ["MKT"], + n_components=4, + prompt="prompt-1", + query=QUERY_UUID, + decoder_type="mlm", + ) + models.poet2.fit_gp( + "assay-1", + ["fitness"], + reduction="MEAN", + prompt="prompt-1", + query=QUERY_UUID, + use_query_structure_in_decoder=False, + ) + + svd, gp = (body for _, body in models_session.submissions) + assert (svd["prompt_id"], svd["query_id"], svd["decoder_type"]) == ( + "prompt-1", + QUERY_UUID, + "mlm", + ) + assert gp["features"] == { + "model_id": "poet-2", + "reduction": "MEAN", + "prompt_id": "prompt-1", + "query_id": QUERY_UUID, + "use_query_structure_in_decoder": False, + } + + def test_a_wrong_assay_type_raises_before_any_request(self, models, models_session): + with pytest.raises(TypeError, match="assay must be"): + models.esm2.fit_gp(3, ["fitness"], reduction="MEAN") + with pytest.raises(TypeError, match="assay must be"): + models.esm2.fit_svd(assay=3) + models_session.session.post.assert_not_called() + + +class TestChecksBeforeRequests: + """Every SDK object is type-checked before any request.""" + + @pytest.mark.parametrize( + "call", + [ + lambda m: m.poet2.fit_gp( + 3, ["fitness"], reduction="MEAN", query=Protein(sequence="MKT") + ), + lambda m: m.poet2.fit_svd(assay=3, query=Protein(sequence="MKT")), + lambda m: m.poet2.fit_umap(assay=3, query=Protein(sequence="MKT")), + lambda m: m.poet2.generate(query=Protein(sequence="MKT"), design=3), + lambda m: m.poet2.embed(["MKT"], prompt=3, query=Protein(sequence="MKT")), + lambda m: m.proteinmpnn.generate(query=[Protein(sequence="MKT"), 3]), + ], + ) + def test_a_wrong_type_raises_before_any_request(self, models, models_session, call): + with pytest.raises(TypeError): + call(models) + models_session.session.post.assert_not_called() + models_session.session.get.assert_not_called() + + def test_an_object_with_its_param_raises_before_any_request( + self, models, models_session + ): + with pytest.raises(TypeError, match="query or query_id"): + models.poet2.embed( + ["MKT"], query=Protein(sequence="MKT"), query_id=QUERY_UUID + ) + models_session.session.post.assert_not_called() + models_session.session.get.assert_not_called() + + +class TestPoET: + def test_indel_sends_insert_and_delete(self, models, models_session): + models.poet2.indel("MKT", delete=[1, 2], prompt="prompt-1", decoder_type="clm") + + assert models_session.submitted == ( + "v1/models/poet-2/indel/scores", + { + "base_sequence": "MKT", + "delete": [1, 2], + "prompt_id": "prompt-1", + "decoder_type": "clm", + }, + ) + + @pytest.mark.parametrize("handle,model_id", [("poet", "poet"), ("poet2", "poet-2")]) + @pytest.mark.parametrize( + "params", [{}, {"include_gaps": False}, {"include_gaps": True}] + ) + def test_single_site_forwards_include_gaps( + self, models, models_session, handle, model_id, params + ): + getattr(models, handle).single_site(b"A-:C-", prompt="prompt-1", **params) + + assert models_session.submitted == ( + f"v1/models/{model_id}/single-site/scores", + {"base_sequence": "A-:C-", "prompt_id": "prompt-1", **params}, + ) + + def test_single_site_takes_the_prompt_and_query(self, models, models_session): + models.poet2.single_site(b"MKT", prompt="prompt-1", query=QUERY_UUID) + + assert models_session.submitted == ( + "v1/models/poet-2/single-site/scores", + {"base_sequence": "MKT", "prompt_id": "prompt-1", "query_id": QUERY_UUID}, + ) + + +class TestInverseFolding: + @pytest.mark.parametrize("alias", ["proteinmpnn", "solublempnn", "esmif1"]) + def test_scoring_sends_the_query(self, models, models_session, alias): + model = getattr(models, alias) + model.score(["MKT"], query=QUERY_UUID) + model.single_site("MKT", query=QUERY_UUID) + + assert [body for _, body in models_session.submissions] == [ + {"sequences": ["MKT"], "query_id": QUERY_UUID}, + {"base_sequence": "MKT", "query_id": QUERY_UUID}, + ] + + @pytest.mark.parametrize("alias", ["proteinmpnn", "solublempnn"]) + def test_embed_pools_by_mean_by_default(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}, + ] + + +class TestDesignModels: + def test_rfdiffusion_sends_the_query_and_its_params(self, models, models_session): + models.rfdiffusion.generate( + query=Protein.from_expr(50), num_samples=2, random_seed=3 + ) + + path, body = models_session.submitted + assert path == "v1/models/rfdiffusion/generate/structures" + assert body == { + "query_id": created_query(1), + "num_samples": 2, + "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")}), + num_samples=2, + diffusion_batch_size=1, + random_seed=5, + ) + + path, body = models_session.submitted + assert path == "v1/models/boltzgen/generate/structures" + assert body == { + "query_id": created_query(1), + "num_samples": 2, + "diffusion_batch_size": 1, + "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} + + @pytest.mark.parametrize("model_id", ["boltzgen", "rfdiffusion"]) + def test_a_design_model_refuses_a_query_with_query_id( + self, models, models_session, model_id + ): + with pytest.raises(TypeError, match="query or query_id"): + getattr(models, model_id).generate( + query=Protein(sequence="MKT"), query_id=QUERY_UUID + ) + models_session.session.post.assert_not_called() + + +class TestHandleNames: + """The 0.17.0 handle names are the models API handles.""" + + @pytest.mark.parametrize( + "handle, model_id", + [ + (RFdiffusion, "rfdiffusion"), + (ProteinMPNN, "proteinmpnn"), + (ESMIF1, "esm-if1"), + (BoltzGen, "boltzgen"), + ], + ) + def test_each_resolves_from_session_models(self, models, handle, model_id): + resolved: Any = models.get_model(model_id) + + assert type(resolved) is handle + assert handle(models.session).id == model_id + + def test_family_handles(self, models): + assert type(models.poet) is PoET + assert type(models.poet2) is PoET2 + assert type(models.prot_seq) is ProtSeq + + def test_solublempnn_is_a_proteinmpnn_checkpoint(self, models): + resolved: Any = models.get_model("solublempnn") + + assert (type(resolved), resolved.id) == (ProteinMPNN, "solublempnn") + + +class TestParamsSchema: + def test_a_handle_reads_a_methods_params_schema_once(self, models, models_session): + handle = models.esmfold + + first = handle._params_schema("batch/structures") + second = handle._params_schema("batch/structures") + + assert first is second + assert "complexes" in first["properties"] + reads = [ + call.args[0] + for call in models_session.session.get.call_args_list + if call.args[0].endswith("/params") + ] + assert reads == ["v1/models/esmfold/batch/structures/params"] + + +@pytest.mark.parametrize( + "call", + [ + lambda m: m.poet2.score(["MKT"], decoder_type="mlm"), + lambda m: m.poet2.single_site("MKT", decoder_type="mlm"), + lambda m: m.poet2.indel("MKT", insert="A", decoder_type="mlm"), + lambda m: m.poet.generate(prompt="prompt-1", query_id=QUERY_UUID), + lambda m: m.rfdiffusion.generate(), + lambda m: m.boltzgen.generate(), + ], + ids=[ + "poet-2 mlm score", + "poet-2 mlm single site", + "poet-2 mlm indel", + "poet with a query_id", + "rfdiffusion without a query", + "boltzgen without a query", + ], +) +def test_a_refusal_from_the_models_api_reaches_the_caller(models, models_session, call): + refused = MagicMock(status_code=422, text="refused", url="v1/models") + models_session.session.post.side_effect = HTTPError(refused) + + with pytest.raises(HTTPError) as caught: + call(models) + + assert caught.value.status_code == 422 + + +@pytest.mark.parametrize( + ("model_id", "param", "value"), + [ + ("boltzgen", "design_spec", {"entities": []}), + ("boltzgen", "scaffolds", {"s.cif": QUERY_UUID}), + ("boltzgen", "extra_structure_files", {"t.cif": QUERY_UUID}), + ("boltzgen", "scaffold_set", "default_vhh"), + ("rfdiffusion", "contigs", "50-50"), + ("rfdiffusion", "hotspot", "A10"), + ("rfdiffusion", "scaffold_target_query_id", QUERY_UUID), + ("rfdiffusion", "symmetry", "cyclic"), + ], +) +def test_a_design_model_sends_a_param_it_does_not_name_as_given( + models, models_session, model_id, param, value +): + refused = MagicMock(status_code=422, text="refused", url="v1/models") + models_session.session.post.side_effect = HTTPError(refused) + + with pytest.raises(HTTPError) as caught: + getattr(models, model_id).generate(query_id=QUERY_UUID, **{param: value}) + + assert caught.value.status_code == 422 + assert models_session.session.post.call_args.kwargs["json"] == { + "query_id": QUERY_UUID, + param: value, + } diff --git a/tests/models/test_input_checks.py b/tests/models/test_input_checks.py new file mode 100644 index 0000000..698e2db --- /dev/null +++ b/tests/models/test_input_checks.py @@ -0,0 +1,206 @@ +"""Input checks of ``session.models`` run locally, before any upload or submission.""" + +import pytest + +from openprotein.errors import InvalidParameterError +from openprotein.models import ModelsAPI +from openprotein.models.svd import SVDModel +from openprotein.molecules import Complex, Ligand +from tests.models.support import card + + +@pytest.fixture +def models(models_session) -> ModelsAPI: + return ModelsAPI(models_session.session) + + +def _nothing_sent(models_session) -> None: + assert models_session.queries == [] + assert models_session.submissions == [] + + +class TestEmptyQueryBatch: + """A query or design that resolves to no targets is refused, not dropped.""" + + @pytest.mark.parametrize( + "call", + [ + lambda m: m.poet2.score(["AC"], query=[]), + lambda m: m.poet2.generate(query=[], num_samples=2), + lambda m: m.poet2.embed(["AC"], query=[]), + ], + ids=["score", "generate", "embed"], + ) + def test_an_empty_query_list_raises(self, models, models_session, call): + with pytest.raises(ValueError, match="query=None"): + call(models) + _nothing_sent(models_session) + + def test_an_omitted_query_is_sent_without_query_id(self, models, models_session): + models.poet2.score(["AC"]) + assert "query_id" not in models_session.submitted[1] + + def test_one_query_is_sent_as_a_bare_id(self, models, models_session): + models.poet2.score(["AC"], query=["AC"]) + assert isinstance(models_session.submitted[1]["query_id"], str) + + +class TestQueryEntryChecks: + """A query entry that can't be uploaded is refused before any request.""" + + @pytest.mark.parametrize( + "call", + [ + lambda m: m.poet2.generate(query=":"), + lambda m: m.poet2.score(["AC"], query=":"), + ], + ids=["generate", "score"], + ) + def test_an_invalid_query_sequence_makes_no_request( + self, models, models_session, call + ): + _ = models.poet2 + models_session.session.get.reset_mock() + with pytest.raises(InvalidParameterError): + call(models) + models_session.session.get.assert_not_called() + models_session.session.post.assert_not_called() + + +class TestBareStringBatch: + """A bare str or bytes where a list of sequences is expected raises TypeError.""" + + @pytest.mark.parametrize("value", ["ACD", b"ACD"], ids=["str", "bytes"]) + @pytest.mark.parametrize( + "call", + [ + lambda m, v: m.esm2.embed(v), + lambda m, v: m.esm2.logits(v), + lambda m, v: m.esm2.score(v), + lambda m, v: m.esm2.fit_svd(v), + lambda m, v: m.esm2.fit_umap(v), + lambda m, v: m.proteinmpnn.embed(v, query="MKT"), + ], + ids=["embed", "logits", "score", "fit_svd", "fit_umap", "proteinmpnn_embed"], + ) + def test_a_bare_sequence_raises_before_any_request( + self, models, models_session, call, value + ): + with pytest.raises(TypeError, match=r'\["ACD"\]'): + call(models, value) + models_session.session.post.assert_not_called() + + def test_a_single_base_sequence_stays_scalar(self, models, models_session): + models.esm2.single_site("ACD") + assert models_session.submitted[1]["base_sequence"] == "ACD" + + def test_projection_sequences_must_be_a_list(self, models): + svd = SVDModel._from_record(models.session, {"id": "s-1"}) + with pytest.raises(TypeError, match="list of sequences"): + svd.embed("ACD") + + +def _without(models_session, model_id: str, path: str) -> None: + listing = card(model_id) + listing["methods"] = [m for m in listing["methods"] if m["path"] != path] + models_session.get_routes[f"v1/models/{model_id}"] = listing + + +class TestLocalChecksBeforeUpload: + """A call that fails a local check uploads no query and submits nothing.""" + + def test_one_invalid_query_in_a_batch_uploads_none(self, models, models_session): + with pytest.raises(InvalidParameterError, match="no residues"): + models.poet2.generate(query=["AC", ":"]) + _nothing_sent(models_session) + + def test_a_non_protein_complex_in_a_batch_uploads_none( + self, models, models_session + ): + ligand = Complex({"A": Ligand(ccd="ATP")}) + with pytest.raises(InvalidParameterError, match="protein chains"): + models.poet2.generate(query=["AC", ligand]) + _nothing_sent(models_session) + + def test_a_valid_batch_uploads_every_query(self, models, models_session): + models.poet2.generate(query=["AC", "DE"]) + assert len(models_session.queries) == 2 + assert len(models_session.submitted[1]["query_id"]) == 2 + + def test_a_method_the_card_lacks_is_refused_before_the_query_upload( + self, models, models_session + ): + with pytest.raises(ValueError, match="has no attn"): + models.poet2.attn(["AC"], query="AC") + _nothing_sent(models_session) + + def test_an_inverse_folding_score_checks_its_method_first( + self, models, models_session + ): + _without(models_session, "proteinmpnn", "batch/loglikelihood") + with pytest.raises(ValueError, match="has no score"): + models.proteinmpnn.score(["AC"], query="AC") + _nothing_sent(models_session) + + def test_an_inverse_folding_embed_checks_its_method_first( + self, models, models_session + ): + _without(models_session, "proteinmpnn", "batch/embeddings") + with pytest.raises(ValueError, match="has no embed"): + models.proteinmpnn.embed(["AC"], query="AC") + _nothing_sent(models_session) + + def test_an_inverse_folding_embed_of_a_bare_sequence_uploads_no_query( + self, models, models_session + ): + with pytest.raises(TypeError, match="list of sequences"): + models.proteinmpnn.embed("AC", query="AC") + _nothing_sent(models_session) + + def test_an_inverse_folding_generate_checks_its_method_first( + self, models, models_session + ): + _without(models_session, "proteinmpnn", "generate/sequences") + with pytest.raises(ValueError, match="has no generate"): + models.proteinmpnn.generate(query="AC") + _nothing_sent(models_session) + + def test_a_bare_sequence_with_a_query_uploads_no_query( + self, models, models_session + ): + with pytest.raises(TypeError, match="list of sequences"): + models.poet2.score("AC", query="AC") + _nothing_sent(models_session) + + @pytest.mark.parametrize("fit", ["fit_svd", "fit_umap"]) + def test_a_poet2_fit_without_a_source_uploads_no_query( + self, models, models_session, fit + ): + with pytest.raises(ValueError, match="pass one of sequences or assay"): + getattr(models.poet2, fit)(query="AC") + _nothing_sent(models_session) + + @pytest.mark.parametrize("fit", ["fit_svd", "fit_umap"]) + def test_a_poet_fit_without_a_source_submits_nothing( + self, models, models_session, fit + ): + with pytest.raises(ValueError, match="pass one of sequences or assay"): + getattr(models.poet, fit)() + _nothing_sent(models_session) + + +class TestFitSvdSource: + """fit_svd takes exactly one of sequences or assay.""" + + @pytest.mark.parametrize( + "kwargs", + [{}, {"sequences": ["MKT"], "assay": "assay-1"}], + ids=["neither", "both"], + ) + @pytest.mark.parametrize("handle", ["esm2", "poet", "poet2"]) + def test_neither_or_both_raises_before_any_request( + self, models, models_session, handle, kwargs + ): + with pytest.raises(ValueError, match="pass one of sequences or assay"): + getattr(models, handle).fit_svd(**kwargs) + models_session.session.post.assert_not_called() diff --git a/tests/models/test_inputs.py b/tests/models/test_inputs.py new file mode 100644 index 0000000..bd88f64 --- /dev/null +++ b/tests/models/test_inputs.py @@ -0,0 +1,73 @@ +"""The model a fit takes, as an id, a handle or an SVD.""" + +from typing import Any + +import pytest + +from openprotein.models import ( + ModelsAPI, + gp, + svd, + umap, +) +from openprotein.models.svd import SVDModel + + +def _job(job_id: str, status: str = "PENDING") -> dict[str, Any]: + return { + "job_id": job_id, + "job_type": "/models", + "status": status, + "created_date": "2026-10-21T08:00:00Z", + } + + +@pytest.fixture +def models(models_session) -> ModelsAPI: + return ModelsAPI(models_session.session) + + +SEQUENCES = ["MKT", "AC", "DE", "FG"] + + +class TestModelArgument: + """Each fit takes its model as an id, a get_model handle or an SVD.""" + + @pytest.mark.parametrize( + "model, model_id", + [ + ("esm2", "esm2"), + (lambda m: m.get_model("esm2"), "esm2"), + (lambda m: SVDModel._from_record(m.session, {"id": "s-1"}), "svd/s-1"), + ], + ids=["id", "handle", "svd"], + ) + def test_umap_and_gp_fits_resolve_the_model( + self, models, models_session, model, model_id + ): + model = model(models) if callable(model) else model + models_session.post_routes["v1/models/umap"] = _job("fit-1") + models_session.post_routes["v1/models/gp"] = _job("p-1") + + umap._fit(models.session, model, SEQUENCES) + gp._fit(models.session, model, "assay-1", ["fitness"]) + + umap_body, gp_body = (body for _, body in models_session.submissions) + assert umap_body["model_id"] == gp_body["features"]["model_id"] == model_id + + @pytest.mark.parametrize( + "fit", + [ + lambda m: umap._fit(m.session, 3, assay="assay-1"), + lambda m: gp._fit(m.session, 3, "assay-1", ["fitness"]), + lambda m: svd._fit(m.session, 3, assay="assay-1"), + ], + ids=["umap", "gp", "svd"], + ) + def test_a_wrong_model_type_raises_before_any_request( + self, models, models_session, fit + ): + with pytest.raises(TypeError, match="model must be"): + fit(models) + models_session.session.get.assert_not_called() + models_session.session.post.assert_not_called() diff --git a/tests/models/test_kernels.py b/tests/models/test_kernels.py new file mode 100644 index 0000000..d9a7f1c --- /dev/null +++ b/tests/models/test_kernels.py @@ -0,0 +1,71 @@ +"""Trained GP kernels are defined in openprotein.models.""" + +import importlib +import warnings + +import pytest + +KERNELS = [ + "TrainedKernel", + "LinearKernel", + "RBFKernel", + "Matern12Kernel", + "Matern32Kernel", + "Matern52Kernel", + "PeriodicKernel", + "RationalQuadraticKernel", +] + + +@pytest.mark.parametrize("name", KERNELS) +def test_a_kernel_is_one_class_from_models_and_predictor(name): + from openprotein import models + from openprotein.models import kernels + + kernel = getattr(kernels, name) + assert kernel.__module__ == "openprotein.models.kernels" + assert getattr(models, name) is kernel + with warnings.catch_warnings(): + warnings.simplefilter("error") + predictor = importlib.import_module("openprotein.predictor") + assert getattr(predictor, name) is kernel + + +@pytest.mark.parametrize( + ("module", "name"), + [ + ("openprotein.predictor", "GPHyperparameters"), + ("openprotein.predictor.schemas", "GPHyperparameters"), + ("openprotein.predictor.schemas", "sole_hyperparameters"), + ("openprotein.predictor.schemas", "trained_kernel"), + ("openprotein.predictor.api", "predictor_get_hyperparameters"), + ("openprotein.models.kernels", "GPHyperparameters"), + ("openprotein.models.kernels", "sole_hyperparameters"), + ("openprotein.models.kernels", "trained_kernel"), + ("openprotein.models.gp", "GPHyperparameters"), + ("openprotein.models.gp", "sole_hyperparameters"), + ("openprotein.models.gp", "trained_kernel"), + ("openprotein.predictor.api", "GPHyperparameters"), + ("openprotein.predictor.models", "GPHyperparameters"), + ("openprotein.predictor.models", "sole_hyperparameters"), + ("openprotein.predictor.models", "trained_kernel"), + ], +) +def test_hyperparameter_helpers_are_private(module, name): + assert not hasattr(importlib.import_module(module), name) + + +def test_the_kernel_spec_types_stay_in_predictor(): + from openprotein.predictor import Kernel, KernelType, schemas + + assert KernelType is schemas.KernelType + assert Kernel is schemas.Kernel + assert KernelType.__module__ == Kernel.__module__ == "openprotein.predictor.schemas" + + +def test_a_trained_kernel_type_equals_its_kernel_type(): + from openprotein.models.kernels import PeriodicKernel, RBFKernel + from openprotein.predictor import KernelType + + assert RBFKernel.type == KernelType.RBF + assert PeriodicKernel.type == KernelType.PERIODIC diff --git a/tests/models/test_local_validation.py b/tests/models/test_local_validation.py new file mode 100644 index 0000000..0a43dd0 --- /dev/null +++ b/tests/models/test_local_validation.py @@ -0,0 +1,83 @@ +"""Sequences and queries are validated before any request is made.""" + +import pytest + +from openprotein.models import ModelsAPI +from tests.models.test_handles import QUERY_UUID + + +def _requests(models_session) -> int: + session = models_session.session + return ( + session.get.call_count + + session.post.call_count + + session.put.call_count + + session.delete.call_count + ) + + +CASES = { + "poet2.score": lambda m, bad: m.poet2.score([bad], query="AC"), + "poet2.logits": lambda m, bad: m.poet2.logits([bad], query="AC"), + "poet2.attn": lambda m, bad: m.poet2.attn([bad], query="AC"), + "poet2.embed": lambda m, bad: m.poet2.embed([bad], query="AC"), + "poet2.fit_svd": lambda m, bad: m.poet2.fit_svd([bad], query="AC"), + "poet2.fit_umap": lambda m, bad: m.poet2.fit_umap([bad], query="AC"), + "poet2.single_site": lambda m, bad: m.poet2.single_site(bad, query="AC"), + "poet.score": lambda m, bad: m.poet.score([bad]), + "poet.embed": lambda m, bad: m.poet.embed([bad]), + "poet.single_site": lambda m, bad: m.poet.single_site(bad), + "poet.indel": lambda m, bad: m.poet.indel(bad, insert="A"), + "proteinmpnn.score": lambda m, bad: m.proteinmpnn.score([bad], query=QUERY_UUID), + "proteinmpnn.embed": lambda m, bad: m.proteinmpnn.embed([bad], query=QUERY_UUID), + "proteinmpnn.single_site": lambda m, bad: m.proteinmpnn.single_site( + bad, query=QUERY_UUID + ), +} + +EMPTY_QUERY_CASES = { + "poet2.generate": lambda m: m.poet2.generate(query=[]), + "poet2.score": lambda m: m.poet2.score(["AC"], query=[]), + "poet2.embed": lambda m: m.poet2.embed(["AC"], query=[]), + "proteinmpnn.generate": lambda m: m.proteinmpnn.generate(query=[]), + "proteinmpnn.score": lambda m: m.proteinmpnn.score(["AC"], query=[]), +} + + +@pytest.mark.parametrize("verb", CASES) +def test_undecodable_bytes_are_refused_before_any_request(models_session, verb): + models = ModelsAPI(models_session.session) + + with pytest.raises(ValueError, match="not valid UTF-8") as raised: + CASES[verb](models, b"\xff") + + assert isinstance(raised.value.__cause__, UnicodeDecodeError) + assert _requests(models_session) == 0 + + +def test_undecodable_batch_entry_names_its_index(models_session): + models = ModelsAPI(models_session.session) + + with pytest.raises(ValueError, match=r"sequences\[1\]"): + models.poet2.score(["AC", b"\xff"], query="AC") + + assert _requests(models_session) == 0 + + +def test_a_non_text_batch_entry_names_its_index(models_session): + models = ModelsAPI(models_session.session) + + with pytest.raises(TypeError, match=r"sequences\[0\]"): + models.poet2.score([1], query="AC") + + assert _requests(models_session) == 0 + + +@pytest.mark.parametrize("verb", EMPTY_QUERY_CASES) +def test_empty_query_is_refused_before_any_request(models_session, verb): + models = ModelsAPI(models_session.session) + + with pytest.raises(ValueError, match="query has no entries; pass query=None"): + EMPTY_QUERY_CASES[verb](models) + + assert _requests(models_session) == 0 diff --git a/tests/models/test_model_taxonomy.py b/tests/models/test_model_taxonomy.py new file mode 100644 index 0000000..2d5c2e2 --- /dev/null +++ b/tests/models/test_model_taxonomy.py @@ -0,0 +1,60 @@ +import pytest + +from openprotein.models import ( + BoltzGen, + Model, + PoET, + PoET2, + ProteinLanguageModel, + RFdiffusion, + StructureEnsemblePredictionModel, + StructureGenerativeModel, + StructurePredictionModel, + ensemble, + folding, + foundational, + generative, +) +from openprotein.models.foundational._inverse_folding import _InverseFoldingModel + +BASES = [ + (foundational, (ProteinLanguageModel, _InverseFoldingModel)), + (folding, (StructurePredictionModel,)), + (ensemble, (StructureEnsemblePredictionModel,)), + (generative, (StructureGenerativeModel,)), +] + + +@pytest.mark.parametrize(("package", "bases"), BASES) +def test_each_model_class_extends_its_packages_base(package, bases): + classes = [ + value + for value in map(package.__dict__.get, package.__all__) + if isinstance(value, type) and issubclass(value, Model) + ] + assert classes + for cls in classes: + assert issubclass(cls, bases), cls + + +def test_the_model_bases_are_siblings(): + bases = [ + ProteinLanguageModel, + StructurePredictionModel, + StructureEnsemblePredictionModel, + StructureGenerativeModel, + ] + for base in bases: + assert base.__bases__ == (Model,) + + +def test_poet2_extends_poet(): + assert issubclass(PoET2, PoET) + assert PoET2.indel is PoET.indel + + +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 new file mode 100644 index 0000000..21e187b --- /dev/null +++ b/tests/models/test_models_api.py @@ -0,0 +1,659 @@ +"""The models API: discovery, method calls, and the job handle.""" + +import inspect +import json +import socket +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from typing import Any +from unittest.mock import MagicMock, patch +from uuid import UUID + +import pytest +import requests + +from openprotein.base import APISession +from openprotein.errors import APIError +from openprotein.jobs import Future, Job, JobStatus, _dispatch +from openprotein.jobs import futures as results +from openprotein.jobs.futures import SVDFitFuture, UMAPFitFuture +from openprotein.models import ( + MethodDescriptor, + Model, + ModelMetadata, + ModelsAPI, +) +from openprotein.models import _api as models_api + +MODEL_ID = "esm2_t33_650M_UR50D" + +METADATA: dict[str, Any] = { + "model_id": MODEL_ID, + "type": None, + "family_id": "esm", + "model": "ESM2", + "name": "ESM2 (650M)", + "variant": "650M", + "is_system": True, + "base": True, + "tags": None, + "input_types": ["protein"], + "description": { + "summary": "ESM-2 650M protein language model.", + "citation_title": None, + "doi": "10.1101/2022.07.20.500902", + }, + "dimension": 1280, + "query": None, + "multichain": None, + "methods": [ + { + "path": "batch/embeddings", + "outputs": ["embeddings"], + "default_output": "embeddings", + "description": "Per-residue embeddings.", + "name": None, + }, + { + "path": "batch/logits", + "outputs": ["logits"], + "default_output": "logits", + "description": None, + "name": None, + }, + ], + "max_sequence_length": 4094, +} + +PARAMS_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": {"sequences": {"type": "array", "items": {"type": "string"}}}, + "required": ["sequences"], +} + +JOB: dict[str, Any] = { + "job_id": "e0b1c3d4-0000-4000-8000-000000000001", + "job_type": f"/models/{MODEL_ID}/batch/embeddings", + "status": "PENDING", + "created_date": "2026-09-05T08:00:00Z", + "args": {"sequences": ["MKTAYIAK"]}, +} + + +NON_MODELS_JOB: dict[str, Any] = { + "job_id": "e0b1c3d4-0000-4000-8000-000000000009", + "job_type": "/embeddings/embed", + "status": "SUCCESS", + "created_date": "2026-09-05T08:00:00Z", +} + + +def _respond(mock: MagicMock, payload: object) -> None: + mock.return_value.status_code = 200 + mock.return_value.json.return_value = payload + + +@pytest.fixture +def fail_first_backend(): + """A server that drops the first POST's connection, then answers any later one. + + Yields a function taking the JSON body to answer the retried POST with, + returning the backend url and the list of ``(body, idempotency key)`` + pairs it received. + """ + received: list[tuple[bytes, str | None]] = [] + servers: list[ThreadingHTTPServer] = [] + threads: list[threading.Thread] = [] + + def start(response_payload: dict) -> tuple[str, list[tuple[bytes, str | None]]]: + class Handler(BaseHTTPRequestHandler): + def do_POST(self) -> None: + content_length = int(self.headers["Content-Length"]) + body = self.rfile.read(content_length) + received.append((body, self.headers.get("Idempotency-Key"))) + if len(received) == 1: + self.close_connection = True + try: + self.connection.shutdown(socket.SHUT_RDWR) + except OSError: + pass + self.connection.close() + return + + response_body = json.dumps(response_payload).encode("utf-8") + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(response_body))) + self.end_headers() + self.wfile.write(response_body) + + def log_message(self, format: str, *args: Any) -> None: + pass + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + server.daemon_threads = True + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + servers.append(server) + threads.append(thread) + return f"http://127.0.0.1:{server.server_port}/api/", received + + try: + yield start + finally: + for server, thread in zip(servers, threads): + server.shutdown() + server.server_close() + thread.join(timeout=5) + + +class TestDiscovery: + @pytest.fixture + def models_api(self, mock_session) -> ModelsAPI: + """The legacy per-model attributes fetch their metadata on construction.""" + _respond( + mock_session.get, + {"model_id": "legacy", "description": {"summary": "legacy model"}}, + ) + api = ModelsAPI(mock_session) + mock_session.get.reset_mock() + return api + + def test_list_models_returns_ids_by_default(self, models_api, mock_session): + _respond(mock_session.get, [MODEL_ID, "esm2_t6_8M_UR50D"]) + + ids = models_api.list_models() + + mock_session.get.assert_called_once_with( + "v1/models", params={"scope": "system", "limit": 1000, "offset": 0} + ) + assert ids == [MODEL_ID, "esm2_t6_8M_UR50D"] + + def test_list_models_reads_every_page(self, models_api, mock_session): + pages = [[f"m{i}" for i in range(1000)], ["last"]] + mock_session.get.return_value.json.side_effect = pages + + ids = models_api.list_models() + + assert ids == [*pages[0], "last"] + assert [ + c.kwargs["params"]["offset"] for c in mock_session.get.call_args_list + ] == [ + 0, + 1000, + ] + + def test_list_models_verbose_parses_metadata_and_forwards_path_filters( + self, models_api, mock_session + ): + _respond(mock_session.get, [METADATA]) + + models = models_api.list_models(verbose=True, path=["embeddings"]) + + mock_session.get.assert_called_once_with( + "v1/models", + params={ + "scope": "system", + "limit": 1000, + "verbose": "true", + "path": ["embeddings"], + "offset": 0, + }, + ) + assert isinstance(models[0], ModelMetadata) + assert models[0].model_id == MODEL_ID + + def test_list_models_keeps_only_method_path_filters(self): + assert list(inspect.signature(ModelsAPI.list_models).parameters) == [ + "self", + "verbose", + "path", + ] + assert list(inspect.signature(models_api.list_models).parameters) == [ + "session", + "verbose", + "path", + ] + + def test_get_model_reads_the_card_once(self, models_api, mock_session): + _respond(mock_session.get, METADATA) + + model = models_api.get_model(MODEL_ID) + + assert [m.path for m in model.methods] == ["batch/embeddings", "batch/logits"] + mock_session.get.assert_called_once_with( + f"v1/models/{MODEL_ID}", timeout=mock_session.timeout + ) + + def test_method_descriptor_default_output_is_the_first_name(self): + method = METADATA["methods"][0] | {"outputs": ["embeddings", "attention"]} + metadata = ModelMetadata.model_validate(METADATA | {"methods": [method]}) + + assert metadata.methods[0].outputs == ["embeddings", "attention"] + assert metadata.methods[0].default_output == "embeddings" + + def test_method_descriptor_accepts_a_typed_outputs_map(self): + method = METADATA["methods"][0] | { + "outputs": {"attention": "vector", "embeddings": "vector"}, + "default_output": "embeddings", + } + metadata = ModelMetadata.model_validate(METADATA | {"methods": [method]}) + + assert metadata.methods[0].outputs == ["embeddings", "attention"] + assert metadata.methods[0].default_output == "embeddings" + + def test_method_descriptor_takes_an_input_output_pair_as_its_path(self): + method = MethodDescriptor.model_validate( + {"input": "batch", "output": "embeddings", "outputs": ["embeddings"]} + ) + + assert method.path == "batch/embeddings" + + def test_model_metadata_reads_the_display_taxonomy(self): + metadata = ModelMetadata.model_validate(METADATA) + + assert ( + metadata.family_id, + metadata.model, + metadata.name, + metadata.variant, + ) == ("esm", "ESM2", "ESM2 (650M)", "650M") + assert metadata.type is None + + +class TestMethod: + def test_esm_alias_embed_submits_to_models_route(self, mock_session): + _respond(mock_session.get, METADATA) + _respond(mock_session.post, JOB) + esm = ModelsAPI(mock_session).esm2 + + future = esm.embed(sequences=[b"MKTAYIAK"]) + + assert isinstance(future, Future) + mock_session.get.assert_called_once_with( + f"v1/models/{MODEL_ID}", timeout=mock_session.timeout + ) + assert mock_session.post.call_args.args == ( + f"v1/models/{MODEL_ID}/batch/embeddings", + ) + assert mock_session.post.call_args.kwargs["json"] == { + "sequences": ["MKTAYIAK"], + "reduction": "MEAN", + } + + def test_esm_embed_preserves_explicit_unpooled_reduction(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 + + def test_esm_logits_and_attn_submit_to_model_methods(self, mock_session): + attn = { + "path": "batch/attn", + "outputs": {"attn": "vector"}, + "default_output": "attn", + "description": None, + } + _respond(mock_session.get, METADATA | {"methods": [*METADATA["methods"], attn]}) + _respond(mock_session.post, JOB) + esm = ModelsAPI(mock_session).esm2 + + esm.logits(sequences=[b"MKTAYIAK"]) + esm.attn(sequences=["MKTAYIAK"]) + + assert [call.args[0] for call in mock_session.post.call_args_list] == [ + f"v1/models/{MODEL_ID}/batch/logits", + f"v1/models/{MODEL_ID}/batch/attn", + ] + assert [call.kwargs["json"] for call in mock_session.post.call_args_list] == [ + {"sequences": ["MKTAYIAK"]}, + {"sequences": ["MKTAYIAK"]}, + ] + + def test_poet2_embed_submits_to_models_route(self, mock_session): + _respond(mock_session.get, METADATA | {"model_id": "poet-2"}) + _respond( + mock_session.post, JOB | {"job_type": "/models/poet-2/batch/embeddings"} + ) + + future = ModelsAPI(mock_session).poet2.embed( + sequences=["MKTAYIAK"], prompt_id="prompt-1" + ) + + assert isinstance(future, Future) + assert mock_session.post.call_args.args == ( + "v1/models/poet-2/batch/embeddings", + ) + assert mock_session.post.call_args.kwargs["json"] == { + "sequences": ["MKTAYIAK"], + "prompt_id": "prompt-1", + "reduction": "MEAN", + } + + def test_a_card_without_the_method_submits_nothing(self, mock_session): + _respond(mock_session.get, METADATA | {"model_id": "ablang2", "methods": []}) + + with pytest.raises(ValueError, match="has no embed; its methods: none"): + ModelsAPI(mock_session).ablang2.embed(sequences=["MKTAYIAK"]) + with pytest.raises(ValueError, match="has no generate"): + ModelsAPI(mock_session).rfdiffusion.generate(query_id="q") + + mock_session.post.assert_not_called() + + @pytest.fixture + def model(self, mock_session) -> Model: + return Model(mock_session, MODEL_ID, ModelMetadata.model_validate(METADATA)) + + def test_a_missing_verb_names_the_cards_methods(self, model, mock_session): + with pytest.raises( + ValueError, + match="has no single_site; its methods: batch/embeddings, batch/logits", + ): + model.single_site("MKTAYIAK") + mock_session.post.assert_not_called() + + @pytest.mark.parametrize( + "verb, args, route, body", + [ + ("embed", (["MKTAYIAK"],), "batch/embeddings", {"sequences": ["MKTAYIAK"]}), + ("logits", ([b"MKTAYIAK"],), "batch/logits", {"sequences": ["MKTAYIAK"]}), + ("attn", (["MKTAYIAK"],), "batch/attn", {"sequences": ["MKTAYIAK"]}), + ( + "score", + (["MKTAYIAK"],), + "batch/loglikelihood", + {"sequences": ["MKTAYIAK"]}, + ), + ( + "single_site", + (b"MKTAYIAK",), + "single-site/scores", + {"base_sequence": "MKTAYIAK"}, + ), + ( + "single_site", + ("MKTAYIAK",), + "single-site/predictions", + {"base_sequence": "MKTAYIAK"}, + ), + ("generate", (), "generate/structures", {"query_id": "q"}), + ("generate", (), "generate/sequences", {"query_id": "q"}), + ( + "fold", + ([["MKTAYIAK"]],), + "batch/structures", + {"complexes": [["MKTAYIAK"]]}, + ), + ( + "predict", + (["MKTAYIAK"],), + "batch/predictions", + {"sequences": ["MKTAYIAK"]}, + ), + ], + ) + def test_each_verb_submits_its_card_method( + self, mock_session, verb, args, route, body + ): + method = {"path": route, "outputs": ["out"]} + model = Model( + mock_session, + "m", + ModelMetadata.model_validate(METADATA | {"methods": [method]}), + ) + _respond(mock_session.post, JOB) + params = {"query_id": "q"} if verb == "generate" else {} + + future = getattr(model, verb)(*args, **params) + + assert mock_session.post.call_args.args == (f"v1/models/m/{route}",) + assert mock_session.post.call_args.kwargs["json"] == body + assert future._descriptor.path == route + + def test_run_is_not_public(self, model): + import openprotein.models + + assert not hasattr(model, "run") and not hasattr(model, "method") + assert not hasattr(openprotein.models, "Method") + + def test_a_verb_posts_params_as_the_body(self, model, mock_session): + _respond(mock_session.post, JOB) + + future = model.embed(["MKTAYIAK"]) + + call = mock_session.post.call_args + assert call.args == (f"v1/models/{MODEL_ID}/batch/embeddings",) + assert call.kwargs["json"] == {"sequences": ["MKTAYIAK"]} + assert UUID(call.kwargs["headers"]["Idempotency-Key"]) + assert isinstance(future, Future) + assert future.id == JOB["job_id"] + assert future._model_id == MODEL_ID + assert future._path == "batch/embeddings" + assert future.args == {"sequences": ["MKTAYIAK"]} + + def test_a_verb_hands_the_future_its_method(self, model, mock_session): + _respond(mock_session.post, JOB) + + future = model.logits(["MKTAYIAK"]) + + assert future._descriptor == model.methods[1] + mock_session.get.assert_not_called() + + def test_a_verb_forwards_prompt_id_from_a_stored_or_a_sampled_prompt( + self, mock_session + ): + from openprotein.data.prompts.prompts import Prompt + from openprotein.data.prompts.schemas import PromptSummary + + poet2 = Model( + mock_session, + "poet-2", + ModelMetadata.model_validate(METADATA | {"model_id": "poet-2"}), + ) + _respond( + mock_session.post, JOB | {"job_type": "/models/poet-2/batch/embeddings"} + ) + + stored_prompt = Prompt( + mock_session, + PromptSummary( + id="prompt-1", + owner="user", + created_at="2026-09-05T08:00:00Z", + ), + ) + sampled_prompt = Prompt( + mock_session, + PromptSummary(id="sample-job-1", status="PENDING", job_id="sample-job-1"), + ) + + poet2.embed(["MKTAYIAK"], prompt_id=stored_prompt.id) + poet2.embed(["MKTAYIAK"], prompt_id=sampled_prompt.id) + + calls = mock_session.post.call_args_list + assert calls[0].args == ("v1/models/poet-2/batch/embeddings",) + 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): + _respond(mock_session.post, JOB) + + model.embed(["MKTAYIAK"], seed=None) + + assert mock_session.post.call_args.kwargs["json"]["seed"] is None + + def test_a_verb_keeps_a_given_seed(self, model, mock_session): + _respond(mock_session.post, JOB) + + model.embed(["MKTAYIAK"], seed=7) + + assert mock_session.post.call_args.kwargs["json"]["seed"] == 7 + + def test_a_verb_retries_the_same_body_on_425( + self, model, mock_session, monkeypatch + ): + from openprotein.errors import HTTPError + + monkeypatch.setattr("openprotein.jobs._submission.time.sleep", lambda _: None) + pending = MagicMock() + pending.status_code = 425 + pending.headers = {"Retry-After": "0"} + mock_session.post.side_effect = [ + HTTPError(pending), + MagicMock(**{"json.return_value": JOB}), + ] + + future = model.embed(["MKTAYIAK"]) + + assert future.id == JOB["job_id"] + calls = mock_session.post.call_args_list + assert calls[0].kwargs["json"] == calls[1].kwargs["json"] + assert calls[0].kwargs["headers"] == calls[1].kwargs["headers"] + + def test_each_logical_submission_gets_a_new_admission_id(self, model, mock_session): + _respond(mock_session.post, JOB) + + with patch( + "openprotein.models._api.uuid4", side_effect=["admission-1", "admission-2"] + ): + model.embed(["MKTAYIAK"]) + model.embed(["MKTAYIAK"]) + + calls = mock_session.post.call_args_list + assert [call.kwargs["headers"]["Idempotency-Key"] for call in calls] == [ + "admission-1", + "admission-2", + ] + assert [call.kwargs["json"] for call in calls] == [ + {"sequences": ["MKTAYIAK"]}, + {"sequences": ["MKTAYIAK"]}, + ] + + def test_model_post_is_sent_once_when_the_connection_drops( + self, fail_first_backend + ): + backend, received = fail_first_backend(JOB) + with patch.object(APISession, "_init_auth"): + session = APISession("user", "password", backend=backend, timeout=2) + try: + with pytest.raises(requests.exceptions.ConnectionError): + models_api.run_method( + session, MODEL_ID, "batch/embeddings", {"sequences": ["MKTAYIAK"]} + ) + finally: + session.close() + + assert len(received) == 1 + + +class TestJobsOutsideTheModelsAPI: + """A job outside the models API is a handle with status, without outputs.""" + + @pytest.fixture + def future(self, mock_session): + _respond(mock_session.post, NON_MODELS_JOB) + model = Model(mock_session, MODEL_ID, ModelMetadata.model_validate(METADATA)) + return model.embed(["MKTAYIAK"]) + + def test_the_submit_parses_and_tracks_the_job(self, future, mock_session): + assert isinstance(future, Future) + assert future.id == NON_MODELS_JOB["job_id"] + assert future.status is JobStatus.SUCCESS + assert future._path == "batch/embeddings" + assert future._default_output == "embeddings" + mock_session.get.assert_not_called() + + @pytest.mark.parametrize( + "read", + [ + lambda f: f.get(), + lambda f: list(f.stream()), + lambda f: f.get_item(0), + lambda f: f.unit(0), + lambda f: f.units, + lambda f: f._model_id, + ], + ) + def test_reading_outputs_without_stored_outputs_raises( + self, future, mock_session, read + ): + with pytest.raises(APIError, match="has no stored outputs"): + read(future) + mock_session.get.assert_not_called() + + +class TestFuture: + def test_default_display_shows_id_status_and_compact_args(self, mock_session): + sequences = ["MKTAYIAK" * 10, "MEEPQSDPSV"] + job = Job.model_validate( + JOB | {"args": {"sequences": sequences, "reduction": "MEAN"}} + ) + future = Future(mock_session, job) + + assert repr(future) == ( + f"Future(job_id={JOB['job_id']!r}, status='PENDING', " + "args={'sequences': <2 items>, 'reduction': 'MEAN'})" + ) + assert str(future) == repr(future) + assert all(sequence not in repr(future) for sequence in sequences) + mock_session.get.assert_not_called() + + def test_display_elides_a_long_query(self, mock_session): + query = "MKTAYIAK" * 10 + future = Future( + mock_session, Job.model_validate(JOB | {"args": {"query": query}}) + ) + + assert query not in repr(future) + assert "" in repr(future) + + def test_display_does_not_fetch_missing_args(self, mock_session): + future = Future(mock_session, Job.model_validate(JOB | {"args": None})) + + assert "args=" in repr(future) + mock_session.get.assert_not_called() + + def test_a_models_job_loads_as_its_typed_result_future(self, mock_session): + future = Future.create(session=mock_session, response=JOB) + + assert type(future) is results.EmbeddingFuture + assert _dispatch.is_models_job(future.job) + assert future.job.job_type == JOB["job_type"] + + @pytest.mark.parametrize( + "family, future_class, outputs", + [ + ("svd", SVDFitFuture, ["sequences"]), + ("umap", UMAPFitFuture, ["sequences", "embeddings"]), + ], + ids=["svd", "umap"], + ) + def test_a_fit_job_loads_as_its_fit_future( + self, mock_session, family, future_class, outputs + ): + fit = JOB | { + "job_type": f"/models/{family}/fit", + "outputs": ["ignored"], + } + + future = Future.create(session=mock_session, response=fit) + + assert type(future) is future_class + assert (future.outputs, future._default_output) == (outputs, outputs[0]) + mock_session.get.assert_not_called() + + def test_wait_until_done_reaches_the_terminal_status( + self, mock_session, monkeypatch + ): + monkeypatch.setattr("openprotein.jobs.futures.time.sleep", lambda _: None) + _respond(mock_session.get, JOB | {"status": "SUCCESS"}) + future = Future(mock_session, Job.model_validate(JOB)) + + done = future.wait_until_done() + + mock_session.get.assert_called_with(f"v1/jobs/{JOB['job_id']}") + assert done + assert future.job.status is JobStatus.SUCCESS + assert future.job.model_dump()["args"] == JOB["args"] diff --git a/tests/models/test_models_gp.py b/tests/models/test_models_gp.py new file mode 100644 index 0000000..a01d1e5 --- /dev/null +++ b/tests/models/test_models_gp.py @@ -0,0 +1,315 @@ +"""GP fits, loads and lists on the models API.""" + +from typing import Any + +import numpy as np +import pytest + +from openprotein.data import AssayDataset +from openprotein.errors import InvalidParameterError +from openprotein.jobs.futures import ( + CrossvalidateFuture, + CrossvalidateResults, + GPFitFuture, +) +from openprotein.models import ( + GPModel, + LinearKernel, + ModelsAPI, + PeriodicKernel, + RBFKernel, +) +from openprotein.models.gp import _fit + + +def _job(job_id: str, status: str = "PENDING") -> dict[str, Any]: + return { + "job_id": job_id, + "job_type": "/models", + "status": status, + "created_date": "2026-10-21T08:00:00Z", + } + + +@pytest.fixture +def models(models_session) -> ModelsAPI: + return ModelsAPI(models_session.session) + + +SEQUENCES = ["MKT", "AC", "DE", "FG"] + + +class TestGPs: + def test_fit_submits_the_training(self, models, models_session): + models_session.post_routes["v1/models/gp"] = _job("p-1") + + future = _fit( + models.session, + "svd/s-1", + "assay-1", + ["fitness"], + kernel="periodic", + period=2.0, + name="gp", + ) + + assert isinstance(future, GPFitFuture) + assert models_session.submitted == ( + "v1/models/gp", + { + "features": {"model_id": "svd/s-1"}, + "kernel": {"type": "periodic", "period": 2.0}, + "training_dataset": {"assay_id": "assay-1", "properties": ["fitness"]}, + "name": "gp", + }, + ) + + def test_wait_reads_the_trained_gp(self, models, models_session, model_card): + models_session.post_routes["v1/models/gp"] = _job("p-1", "SUCCESS") + models_session.get_routes["v1/jobs/p-1"] = _job("p-1", "SUCCESS") + models_session.get_routes["v1/models/gp/p-1"] = model_card("gp/p-1") + + gp = _fit( + models.session, "esm2", "assay-1", ["fitness"], reduction="MEAN" + ).wait(interval=0) + + assert isinstance(gp, GPModel) + assert gp.id == "gp/p-1" + + def test_list_pages_and_delete(self, models, models_session, model_card): + models_session.get_routes["v1/models"] = [model_card("gp/p-1")] + + listed = models.GP.list(limit=2) + models.get_model("gp/p-1").delete() + + assert [type(p) for p in listed] == [GPModel] + models_session.session.get.assert_called_once_with( + "v1/models", + params={ + "scope": "mine", + "type": "gp", + "verbose": "true", + "limit": 2, + "offset": 0, + }, + ) + models_session.session.delete.assert_called_once_with("v1/models/gp/p-1") + + def test_predict_and_single_site_submit_predictions(self, models, models_session): + gp = models.get_model("gp/p-1") + + gp.predict(["MKT"]) + gp.single_site("MKT") + + assert models_session.submissions == [ + ("v1/models/gp/p-1/batch/predictions", {"sequences": ["MKT"]}), + ("v1/models/gp/p-1/single-site/predictions", {"base_sequence": "MKT"}), + ] + + def test_crossvalidate_reads_its_rows_as_cv_results(self, models, models_session): + gp = models.get_model("gp/p-1") + assert isinstance(gp, GPModel) + _serve_crossvalidation(models_session, folds=[1, -1]) + + future = gp.crossvalidate(n_splits=3) + + assert isinstance(future, CrossvalidateFuture) + assert models_session.submitted == ( + "v1/models/gp/p-1/crossvalidate", + {"n_splits": 3}, + ) + results = future.wait(interval=0) + assert isinstance(results, CrossvalidateResults) + assert results.row_index.tolist() == [0, 1] + assert results.sequence.tolist() == ["MKT", "AC"] + assert results.measurement_name.tolist() == ["fitness", "fitness"] + assert results.fold is not None and results.fold.tolist() == [1, -1] + assert results.y.tolist() == [1.0, 2.0] + assert results.y_mu[0] == 0.9 and np.isnan(results.y_mu[1]) + assert results.y_var[0] == 0.1 and np.isnan(results.y_var[1]) + + def test_a_run_without_folds_reports_none(self, models, models_session): + gp = models.get_model("gp/p-1") + assert isinstance(gp, GPModel) + _serve_crossvalidation(models_session, folds=[None, None]) + + assert gp.crossvalidate().wait(interval=0).fold is None + + def test_crossvalidate_sends_folds_checked_against_the_training_assay( + self, models, models_session, model_card, monkeypatch + ): + _serve_training_assay(models_session, model_card, monkeypatch, rows=4) + _serve_crossvalidation(models_session, folds=[0, 1]) + gp = models.get_model("gp/p-1") + assert isinstance(gp, GPModel) + + gp.crossvalidate(folds=np.array([0, 1, -1, 1])) + + assert models_session.submitted == ( + "v1/models/gp/p-1/crossvalidate", + {"folds": [0, 1, -1, 1]}, + ) + + @pytest.mark.parametrize( + ("kwargs", "message"), + [ + ({"n_splits": 3, "folds": [0, 1, 0, 1]}, "mutually exclusive"), + ({"folds": [0, 1, 0]}, r"\(4\), got 3"), + ({"folds": [0, 0, 0, 0]}, "between 2 and 10 folds"), + ], + ) + def test_crossvalidate_refuses_bad_folds_before_submitting( + self, models, models_session, model_card, monkeypatch, kwargs, message + ): + _serve_training_assay(models_session, model_card, monkeypatch, rows=4) + gp = models.get_model("gp/p-1") + assert isinstance(gp, GPModel) + + with pytest.raises(InvalidParameterError, match=message): + gp.crossvalidate(**kwargs) + models_session.session.post.assert_not_called() + + def test_reads_of_the_training_record(self, models, models_session): + gp = models.get_model("gp/p-1") + assert isinstance(gp, GPModel) + models_session.get_routes |= { + "v1/models/gp/p-1/evaluations": [{"job_id": "cv-1"}], + "v1/models/gp/p-1/training": [{"measurement_name": "fitness"}], + } + + assert gp.evaluations() == [{"job_id": "cv-1"}] + assert gp.training() == [{"measurement_name": "fitness"}] + + @pytest.mark.parametrize( + "kernel,served,expected", + [ + ("LINEAR", {"lengthscale": [None]}, LinearKernel(outputscale=2.0)), + ( + "PERIODIC", + {"lengthscale": [0.8], "period": [3.0]}, + PeriodicKernel(outputscale=2.0, lengthscale=0.8, period=3.0), + ), + ], + ) + def test_trained_hyperparameters( + self, models, models_session, model_card, kernel, served, expected + ): + _serve_trained(models_session, model_card, kernel, served) + models_session.session.timeout = 7 + gp = models.get_model("gp/p-1") + + assert gp.kernel == expected + assert type(gp.kernel) is type(expected) + assert (gp.mean, gp.noise) == (0.5, 0.1) + reads = [ + (c.args[0], c.kwargs.get("timeout")) + for c in models_session.session.get.call_args_list + ] + assert reads == [ + ("v1/models/gp/p-1/hyperparameters", 7), + ("v1/models/gp/p-1", 7), + ] + + @pytest.mark.parametrize("lengthscale", [[None], []]) + def test_a_rejected_kernel_is_read_again( + self, models, models_session, model_card, lengthscale + ): + _serve_trained(models_session, model_card, "RBF", {"lengthscale": lengthscale}) + gp = models.get_model("gp/p-1") + + assert gp.mean == 0.5 + with pytest.raises(ValueError): + _ = gp.kernel + _serve_trained(models_session, model_card, "RBF", {"lengthscale": [0.8]}) + + assert gp.kernel == RBFKernel(outputscale=2.0, lengthscale=0.8) + reads = [ + c + for c in models_session.session.get.call_args_list + if c.args[0] == "v1/models/gp/p-1/hyperparameters" + ] + assert len(reads) == 2 + + def test_ipython_completes_the_attributes_of_the_trained_kernel( + self, models, models_session, model_card + ): + pytest.importorskip("IPython") + from IPython.core.completer import provisionalcompleter + from IPython.core.interactiveshell import InteractiveShell + + _serve_trained( + models_session, + model_card, + "PERIODIC", + {"lengthscale": [0.8], "period": [3.0]}, + ) + shell = InteractiveShell.instance() + shell.user_ns["trained"] = models.get_model("gp/p-1") + text = "trained.kernel." + with provisionalcompleter(): + completions = { + c.text.rsplit(".", 1)[-1] + for c in shell.Completer.completions(text, len(text)) + } + + assert completions & {"lengthscale", "outputscale", "period", "alpha"} == { + "lengthscale", + "outputscale", + "period", + } + + +def _serve_trained(models_session, model_card, kernel: str, served: dict) -> None: + models_session.get_routes |= { + "v1/models/gp/p-1": model_card("gp/p-1") + | {"spec": {"kernel": {"type": kernel}}}, + "v1/models/gp/p-1/hyperparameters": { + "fitness": {"mean": 0.5, "noise": 0.1, "outputscale": [2.0], **served} + }, + } + + +def _serve_crossvalidation(models_session, folds: list[int | None]) -> None: + rows = [ + { + "row_index": 0, + "sequence": "MKT", + "property": "fitness", + "y": 1.0, + "mean": 0.9, + "variance": 0.1, + "fold": folds[0], + }, + { + "row_index": 1, + "sequence": "AC", + "property": "fitness", + "y": 2.0, + "mean": None, + "variance": None, + "fold": folds[1], + }, + ] + models_session.post_routes["v1/models/gp/p-1/crossvalidate"] = _job( + "cv-1", "SUCCESS" + ) + models_session.get_routes["v1/jobs/cv-1"] = _job("cv-1", "SUCCESS") + models_session.get_routes["v1/models/gp/p-1/evaluations/cv-1"] = { + "job_id": "cv-1", + "rows": rows, + } + + +def _serve_training_assay(models_session, model_card, monkeypatch, rows: int) -> None: + models_session.get_routes["v1/models/gp/p-1"] = model_card("gp/p-1") | { + "spec": { + "kernel": {"type": "rbf"}, + "training_dataset": {"assay_id": "assay-1", "properties": ["fitness"]}, + } + } + sizes = {"assay-1": rows} + monkeypatch.setattr( + AssayDataset, + "_for", + classmethod(lambda cls, session: lambda id: [None] * sizes[id]), + ) diff --git a/tests/models/test_models_svd.py b/tests/models/test_models_svd.py new file mode 100644 index 0000000..15cc0c5 --- /dev/null +++ b/tests/models/test_models_svd.py @@ -0,0 +1,422 @@ +"""SVD handles and their models API routes.""" + +import importlib +import inspect +from unittest.mock import MagicMock +from uuid import UUID + +import pytest + +from openprotein.base import APISession +from openprotein.data import AssayDataset, AssayMetadata +from openprotein.errors import HTTPError, JobFailedException +from openprotein.jobs import Job, _dispatch +from openprotein.jobs.futures import SVDFitFuture +from openprotein.models import ModelsAPI +from openprotein.models.model import Model +from openprotein.models.svd import ( + SVDModel, + _fit, + _SVDRecord, +) + + +@pytest.fixture +def session(): + session = MagicMock(spec=APISession) + session.timeout = 180 + session.headers = {"Authorization": "Bearer caller"} + return session + + +def response(body): + return MagicMock(json=lambda: body) + + +def error(status, body=None): + r = response(body or {}) + r.status_code = status + return HTTPError(r) + + +def card(record): + return { + "model_id": f"svd/{record['id']}", + "type": "svd", + "family_id": "svd", + "is_system": False, + "description": {"summary": "2-component SVD of esm2 embeddings"}, + "dimension": record.get("n_components", 2), + "max_sequence_length": 1024, + "methods": [{"path": "batch/embeddings", "outputs": ["embeddings"]}], + "svd": record, + } + + +@pytest.fixture +def row(): + return { + "id": "fit-1", + "owner": "alice", + "requested_n_components": 4, + "n_components": 2, + "embedding": { + "model_id": "esm2", + "version": "1", + "reduction": "MEAN", + "prompt_id": None, + }, + } + + +FIT_JOB = { + "job_id": "fit-1", + "job_type": "/models/svd/fit", + "status": "PENDING", + "created_date": "2026-09-28T00:00:00Z", + "metadata": {"svd": {"embedding": {"model_id": "esm2", "version": "1"}}}, +} + + +def jobs(session, routes): + session.get.side_effect = lambda path, **kwargs: response(routes[path]) + + +def test_svds_live_on_the_models_api(session): + from openprotein.data.data import DataAPI + + assert callable(ModelsAPI(session).SVD) + assert not hasattr(DataAPI(session), "svds") + with pytest.raises(ImportError): + importlib.import_module("openprotein.data.svds") + + +def test_fit_posts_the_request_and_returns_the_fit_future(session): + session.post.return_value = response(FIT_JOB) + future = _fit(session, "esm2", ["ACD"], n_components=2, seed=7) + session.post.assert_called_once() + call = session.post.call_args + assert call.args == ("v1/models/svd",) + assert call.kwargs["json"] == { + "model_id": "esm2", + "sequences": ["ACD"], + "n_components": 2, + "seed": 7, + "output": "embeddings", + } + assert UUID(call.kwargs["headers"]["Idempotency-Key"]) + assert (future.id, future.status.value) == ("fit-1", "PENDING") + assert session.headers == {"Authorization": "Bearer caller"} + + +def test_fit_with_sequences_uses_the_fit_request_body(session): + session.post.return_value = response(FIT_JOB) + _fit( + session, + sequences=["ACD"], + model="esm2", + prompt_id="prompt-1", + reduction="MEAN", + n_components=2, + seed=7, + ) + assert session.post.call_args.args == ("v1/models/svd",) + assert session.post.call_args.kwargs["json"] == { + "sequences": ["ACD"], + "model_id": "esm2", + "prompt_id": "prompt-1", + "reduction": "MEAN", + "output": "embeddings", + "n_components": 2, + "seed": 7, + } + + +def test_get_reads_the_card(session, row): + session.get.return_value = response(card(row)) + svd = ModelsAPI(session).SVD(id="fit-1") + session.get.assert_called_once_with("v1/models/svd/fit-1") + assert (svd.requested_n_components, svd.n_components) == (4, 2) + assert svd.embedding is not None + assert (svd.embedding.model_id, svd.embedding.reduction) == ("esm2", "MEAN") + assert session.headers == {"Authorization": "Bearer caller"} + + +def test_embed_projects_through_the_fitted_model(session, row): + session.get.return_value = response(card(row)) + session.post.return_value = response( + { + "job_id": "projection-2", + "job_type": "/models/svd/batch/embeddings", + "status": "PENDING", + "created_date": "2026-09-28T00:00:00Z", + } + ) + svd = SVDModel._from_record(session, row) + future = svd.embed(["ACD"]) + svd.embed(["EFG"]) + assert session.post.call_args_list[0].args[0] == ( + "v1/models/svd/fit-1/batch/embeddings" + ) + assert session.post.call_args_list[0].kwargs["json"] == {"sequences": ["ACD"]} + assert (future.id, future.outputs) == ("projection-2", ["embeddings"]) + session.get.assert_called_once_with("v1/models/svd/fit-1", timeout=180) + + +def test_list_reads_the_callers_svds(session, row): + session.get.return_value = response([card(row)]) + listed = ModelsAPI(session).SVD.list() + session.get.assert_called_once_with( + "v1/models", + params={ + "scope": "mine", + "type": "svd", + "verbose": "true", + "limit": 1000, + "offset": 0, + }, + ) + assert [svd.id for svd in listed] == ["svd/fit-1"] + + +def test_list_pages_with_limit_and_offset(session, row): + session.get.return_value = response([card(row)]) + ModelsAPI(session).SVD.list(limit=10, offset=20) + session.get.assert_called_once_with( + "v1/models", + params={ + "scope": "mine", + "type": "svd", + "verbose": "true", + "limit": 10, + "offset": 20, + }, + ) + + +def test_fit_takes_a_model_handle_and_leaves_n_components_to_the_server(session): + session.post.return_value = response(FIT_JOB) + _fit(session, Model(session, "esm2"), ["ACD"]) + assert session.post.call_args.kwargs["json"] == { + "sequences": ["ACD"], + "model_id": "esm2", + "output": "embeddings", + } + + +def test_fit_refuses_a_model_of_the_wrong_type_before_any_request(session): + with pytest.raises(TypeError, match="model must be"): + _fit(session, 3, ["ACD"]) + session.post.assert_not_called() + + +def test_fit_passes_poet2_embedding_params(session): + session.post.return_value = response(FIT_JOB) + _fit( + session, + sequences=["ACD"], + model="poet-2", + prompt_id="prompt-1", + query_id="query-1", + use_query_structure_in_decoder=False, + decoder_type="mlm", + n_components=2, + ) + body = session.post.call_args.kwargs["json"] + assert body["query_id"] == "query-1" + assert body["use_query_structure_in_decoder"] is False + assert body["decoder_type"] == "mlm" + + +@pytest.mark.parametrize("svd_id", ["fit-1", "svd/fit-1"]) +def test_get_and_delete_take_a_bare_or_prefixed_id(session, row, svd_id): + session.get.return_value = response(card(row)) + svd = ModelsAPI(session).SVD(id=svd_id) + SVDModel(session, svd_id).delete() + session.get.assert_called_once_with("v1/models/svd/fit-1") + session.delete.assert_called_once_with("v1/models/svd/fit-1") + assert (svd.id, svd._svd_record.id) == ("svd/fit-1", "fit-1") + + +def test_delete(session, row): + SVDModel._from_record(session, row).delete() + session.delete.assert_called_once_with("v1/models/svd/fit-1") + assert session.headers == {"Authorization": "Bearer caller"} + + +@pytest.mark.parametrize("status", [404, 410]) +def test_deleted_or_other_owner_svd_does_not_fall_back(session, status): + session.get.side_effect = error(status) + with pytest.raises(HTTPError) as raised: + ModelsAPI(session).SVD(id="fit-1") + assert raised.value.status_code == status + session.get.assert_called_once_with("v1/models/svd/fit-1") + + +@pytest.mark.parametrize("kind", ["id", "metadata", "dataset"]) +def test_fit_from_an_assay_sends_its_id(session, kind): + session.post.return_value = response(FIT_JOB) + metadata = MagicMock(spec=AssayMetadata, assay_id="assay-1") + assay = { + "id": "assay-1", + "metadata": metadata, + "dataset": AssayDataset(session, metadata), + }[kind] + _fit(session, "esm2", assay=assay, n_components=2) + assert session.post.call_args.kwargs["json"] == { + "assay_id": "assay-1", + "model_id": "esm2", + "output": "embeddings", + "n_components": 2, + } + + +@pytest.mark.parametrize("status", ["PENDING", "SUCCESS", "FAILURE"]) +def test_fit_returns_the_fit_future(session, status): + session.post.return_value = response(FIT_JOB | {"status": status}) + future = _fit(session, "esm2", ["ACD"], n_components=2) + assert isinstance(future, SVDFitFuture) + assert (future.id, future.status.value) == ("fit-1", status) + session.get.assert_not_called() + + +@pytest.mark.parametrize("status", ["PENDING", "SUCCESS", "FAILURE"]) +def test_fit_reads_the_fit_job_when_the_operation_names_only_its_id(session, status): + session.post.return_value = response({"id": "fit-1", "state": "pending"}) + session.get.return_value = response(FIT_JOB | {"status": status}) + future = _fit(session, "esm2", ["ACD"], n_components=2) + assert (future.id, future.status.value) == ("fit-1", status) + session.get.assert_called_once_with("v1/jobs/fit-1") + + +def test_wait_returns_the_svd_once_the_fit_succeeds(session, row): + jobs( + session, + { + "v1/jobs/fit-1": FIT_JOB | {"status": "SUCCESS"}, + "v1/models/svd/fit-1": card(row), + }, + ) + future = SVDFitFuture(session, Job.model_validate(FIT_JOB)) + svd = future.wait(interval=0) + assert isinstance(svd, SVDModel) and svd.n_components == 2 + + +@pytest.mark.parametrize("status", ["FAILURE", "CANCELED"]) +def test_wait_raises_naming_a_fit_that_did_not_succeed(session, row, status): + jobs(session, {"v1/jobs/fit-1": FIT_JOB | {"status": status}}) + with pytest.raises(JobFailedException) as raised: + SVDFitFuture(session, Job.model_validate(FIT_JOB)).wait(interval=0) + assert raised.value.job_id == "fit-1" + + +def test_a_fit_future_reads_its_emitted_embeddings_by_name(session): + rows = [[0.1, 0.2], [0.3, 0.4]] + jobs( + session, + { + "v1/data/results/fit-1/embeddings": { + "output": "embeddings", + "count": 2, + "complete": True, + "values": [ + {"position": i, "unit_id": "u", "value": {"inline": row}} + for i, row in enumerate(rows) + ], + "next_cursor": None, + } + }, + ) + future = SVDFitFuture(session, Job.model_validate(FIT_JOB)) + assert future.get(output="embeddings") == rows + + +def test_records_parse_without_exposing_job_fields(row): + record = _SVDRecord.model_validate( + row + | { + "state": "ready", + "job_id": "fit-1", + "transform_job_id": "transform-1", + "failure_summary": None, + } + ) + dumped = record.model_dump() + assert {"state", "job_id", "transform_job_id", "failure_summary"}.isdisjoint(dumped) + + +def test_svd_handles_carry_no_projections_or_job_state(session, row): + svd = SVDModel._from_record(session, row) + assert not any( + hasattr(svd, name) + for name in ("state", "job", "transform_job_id", "wait", "embeddings") + ) + + +@pytest.mark.parametrize("status", [404, 425]) +def test_get_raises_a_404_unless_the_svd_is_live(session, status): + session.get.side_effect = error(status) + with pytest.raises(HTTPError) as raised: + ModelsAPI(session).SVD(id="fit-1") + assert raised.value.status_code == 404 + session.get.assert_called_once_with("v1/models/svd/fit-1") + + +NON_MODELS_FIT = { + "job_id": "fit-1", + "job_type": "/svd/fit", + "status": "PENDING", + "created_date": "2026-09-28T00:00:00Z", +} + + +def test_fit_tracks_a_fit_job_outside_the_models_api(session): + session.post.return_value = response({"id": "fit-1", "state": "pending"}) + session.get.return_value = response(NON_MODELS_FIT) + future = _fit(session, "prot-seq", ["AA", "AC"], n_components=2) + assert isinstance(future, SVDFitFuture) + assert not _dispatch.is_models_job(future.job) + assert future.id == "fit-1" + + +def test_wait_returns_the_svd_of_a_fit_job_outside_the_models_api(session, row): + jobs( + session, + { + "v1/jobs/fit-1": NON_MODELS_FIT | {"status": "SUCCESS"}, + "v1/models/svd/fit-1": card(row), + }, + ) + future = SVDFitFuture(session, Job.create(NON_MODELS_FIT)) + svd = future.wait(interval=0) + assert isinstance(svd, SVDModel) and svd.id == "svd/fit-1" + assert [call.args[0] for call in session.get.call_args_list] == [ + "v1/jobs/fit-1", + "v1/models/svd/fit-1", + ] + + +@pytest.mark.parametrize("outputs", [["components", "embeddings"], None]) +def test_an_svd_fit_future_lists_its_fixed_outputs(session, outputs): + job = Job.model_validate( + { + "job_id": "fit-1", + "job_type": "/models/svd/fit", + "status": "SUCCESS", + "created_date": "2026-10-30T00:00:00Z", + "outputs": outputs, + } + ) + + future = SVDFitFuture(session, job) + + assert future.outputs == ["sequences"] + + +def test_public_constructor_takes_session_model_id_and_metadata(): + """The public constructor has no record parameter.""" + assert list(inspect.signature(SVDModel).parameters) == [ + "session", + "model_id", + "metadata", + ] diff --git a/tests/models/test_models_umap.py b/tests/models/test_models_umap.py new file mode 100644 index 0000000..a8d6456 --- /dev/null +++ b/tests/models/test_models_umap.py @@ -0,0 +1,140 @@ +"""UMAP fits, loads and lists on the models API.""" + +from typing import Any +from unittest.mock import MagicMock + +import pandas as pd +import pytest + +from openprotein.data import AssayDataset +from openprotein.errors import APIError, JobFailedException +from openprotein.jobs.futures import UMAPFitFuture +from openprotein.models import ( + ModelsAPI, + UMAPModel, +) +from openprotein.models.umap import _fit + + +def _job(job_id: str, status: str = "PENDING") -> dict[str, Any]: + return { + "job_id": job_id, + "job_type": "/models", + "status": status, + "created_date": "2026-10-21T08:00:00Z", + } + + +@pytest.fixture +def models(models_session) -> ModelsAPI: + return ModelsAPI(models_session.session) + + +SEQUENCES = ["MKT", "AC", "DE", "FG"] + + +class TestUmaps: + def test_fit_submits_the_fit_with_its_defaults(self, models, models_session): + models_session.post_routes["v1/models/umap"] = _job("fit-1") + + future = _fit( + models.session, + "svd/s-1", + sequences=["MKT", "AC", "DE", "FG", "HI"], + n_components=3, + ) + + assert isinstance(future, UMAPFitFuture) + assert future.id == "fit-1" + assert models_session.submitted == ( + "v1/models/umap", + { + "model_id": "svd/s-1", + "sequences": ["MKT", "AC", "DE", "FG", "HI"], + "n_components": 3, + }, + ) + + def test_fit_takes_sequences_or_an_assay(self, models, models_session): + with pytest.raises(ValueError, match="one of sequences or assay"): + _fit(models.session, "esm2", reduction="MEAN") + models_session.session.post.assert_not_called() + + def test_wait_reads_the_fitted_umap(self, models, models_session, model_card): + models_session.post_routes["v1/models/umap"] = _job("fit-1", "SUCCESS") + models_session.get_routes["v1/jobs/fit-1"] = _job("fit-1", "SUCCESS") + models_session.get_routes["v1/models/umap/fit-1"] = model_card("umap/fit-1") | { + "owner": "alice", + "spec": {"kind": "umap", "n_components": 2}, + } + future = _fit(models.session, "esm2", sequences=SEQUENCES, reduction="MEAN") + + umap = future.wait(interval=0) + + assert isinstance(umap, UMAPModel) + assert umap.id == "umap/fit-1" + assert umap.spec == {"kind": "umap", "n_components": 2} + + def test_a_failed_fit_raises_on_wait(self, models, models_session): + models_session.post_routes["v1/models/umap"] = _job("fit-1", "FAILURE") + models_session.get_routes["v1/jobs/fit-1"] = _job("fit-1", "FAILURE") + future = _fit(models.session, "esm2", sequences=SEQUENCES, reduction="MEAN") + + with pytest.raises(JobFailedException): + future.wait(interval=0) + + def test_get_list_and_delete(self, models, models_session, model_card): + models_session.get_routes["v1/models/umap/fit-1"] = model_card("umap/fit-1") + models_session.get_routes["v1/models"] = [model_card("umap/fit-1")] + + umap = models.UMAP(id="umap/fit-1") + listed = models.UMAP.list(limit=5, offset=10) + models.get_model("umap/fit-1").delete() + umap.delete() + + assert umap.id == "umap/fit-1" + assert [m.id for m in listed] == ["umap/fit-1"] + assert models_session.session.get.call_args_list[1].kwargs == { + "params": { + "scope": "mine", + "type": "umap", + "verbose": "true", + "limit": 5, + "offset": 10, + } + } + assert [c.args for c in models_session.session.delete.call_args_list] == [ + ("v1/models/umap/fit-1",), + ("v1/models/umap/fit-1",), + ] + + def test_embed_projects_through_the_umap(self, models, models_session): + models.get_model("umap/fit-1").embed(["MKT"]) + + assert models_session.submitted == ( + "v1/models/umap/fit-1/batch/embeddings", + {"sequences": ["MKT"]}, + ) + + +class TestUmapAssay: + def test_an_assay_is_read_page_by_page(self, models, models_session): + rows = pd.DataFrame({"sequence": SEQUENCES + ["HI"]}) + assay = MagicMock(spec=AssayDataset, page_size=2) + assay.get_slice.side_effect = lambda start, end: rows.iloc[start:end] + models_session.post_routes["v1/models/umap"] = _job("fit-1") + + _fit(models.session, "svd/s-1", assay=assay) + + assert models_session.submitted[1]["sequences"] == SEQUENCES + ["HI"] + + def test_a_page_that_fails_raises_before_the_fit(self, models, models_session): + assay = MagicMock(spec=AssayDataset, page_size=2) + assay.get_slice.side_effect = [ + pd.DataFrame({"sequence": SEQUENCES[:2]}), + APIError("page failed"), + ] + + with pytest.raises(APIError, match="page failed"): + _fit(models.session, "svd/s-1", assay=assay) + models_session.session.post.assert_not_called() diff --git a/tests/models/test_parity.py b/tests/models/test_parity.py new file mode 100644 index 0000000..485f6b5 --- /dev/null +++ b/tests/models/test_parity.py @@ -0,0 +1,1149 @@ +"""Each legacy submodule call has a ``session.models`` call submitting the same work. + +One case per call in the parity inventory. A submission case names the card +method and the request body, with the card's param names and defaults written +out; a read case names the route it reads. Cards and params schemas come from +``tests/data/models_params.json``, and ``ModelsSession`` checks every body +against its method's schema. + +Each reader family decodes a stored value of the shape the results routes +serve. +""" + +from collections.abc import Callable +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any +from unittest.mock import MagicMock, patch + +import numpy as np +import pandas as pd +import pytest +from jsonschema import ValidationError + +from openprotein.data.assaydataset import AssayDataset +from openprotein.jobs import Job +from openprotein.jobs.futures import ( + AttentionFuture, + EmbeddingFuture, + Future, + IndelScoreFuture, + LogitsFuture, + LogLikelihoodFuture, + PredictionFuture, + SequenceGenerationFuture, + SingleSitePredictionFuture, + SingleSiteScoreFuture, + StructureDesignFuture, + StructurePredictionFuture, + SVDFitFuture, + UMAPFitFuture, +) +from openprotein.models import ( + GPModel, + ModelsAPI, +) +from openprotein.models.schemas import MethodDescriptor +from openprotein.molecules import Complex, Ligand, Protein, Structure +from tests.models.support import SUBMITTED_JOB, Stored, check_body + +Q = "c0ffee00-0000-4000-8000-000000000001" +Q2 = "c0ffee00-0000-4000-8000-000000000002" +SEQ = ["MKT"] +PROTEIN = {"protein": {"id": "A", "sequence": "MKT"}} +PROTEIN_MSA = {"protein": {"id": "A", "sequence": "MKT", "msa_id": None}} +LIGAND = {"ligand": {"id": "L", "ccd": "ATP"}} + + +@dataclass +class Case: + """A legacy call and its replacement. + + ``posts`` are the expected ``(path, body)`` submissions, in order; + ``reads`` the ``(verb, path)`` other requests that must be made. + """ + + call: Callable[[ModelsAPI, Any], Any] + posts: list[tuple[str, dict[str, Any]]] = field(default_factory=list) + reads: list[tuple[str, str]] = field(default_factory=list) + + +def _ligand_complex() -> Complex: + complex = Complex({"A": Protein(sequence="MKT"), "L": Ligand(ccd="ATP")}) + complex.get_protein("A").msa = Protein.single_sequence_mode + return complex + + +def _assay() -> AssayDataset: + rows = pd.DataFrame({"sequence": ["MKT", "AC", "DE", "FG", "HI"]}) + assay = MagicMock(spec=AssayDataset, id="assay-1", page_size=2) + assay.get_slice.side_effect = lambda start, end: rows.iloc[start:end] + return assay + + +DESIGN_ID = "d0000000-0000-4000-8000-000000000001" + + +def _design(session) -> Future: + job = Job.model_validate( + { + "job_id": DESIGN_ID, + "job_type": "/models", + "status": "SUCCESS", + "created_date": "2026-10-21T08:00:00Z", + } + ) + future = Future(session, job) + future._resolved_descriptor = MethodDescriptor( + path="generate/structures", outputs=["structures"] + ) + return future + + +def _fit_future(session, job_id: str) -> Future: + job = Job.model_validate( + { + "job_id": job_id, + "job_type": "/models", + "status": "SUCCESS", + "created_date": "2026-10-21T08:00:00Z", + } + ) + return Future(session, job) + + +def _gp(models: ModelsAPI) -> GPModel: + predictor = models.get_model("gp/p-1") + assert isinstance(predictor, GPModel) + return predictor + + +def _embedded(model: str, reduction: Any = "MEAN", **params) -> tuple[str, dict]: + return ( + f"v1/models/{model}/batch/embeddings", + {"sequences": SEQ, "reduction": reduction, **params}, + ) + + +CASES: dict[str, Case] = { + # session.embedding + "embedding.list_models": Case( + lambda m, s: m.list_models(verbose=True), reads=[("GET", "v1/models")] + ), + "embedding.get_model.metadata": Case( + lambda m, s: m.get_model("poet-2").metadata, + reads=[("GET", "v1/models/poet-2")], + ), + "embedding.prot_seq.embed": Case( + lambda m, s: m.prot_seq.embed(SEQ), posts=[_embedded("prot-seq")] + ), + "embedding.rotaprot.embed(reduction=None)": Case( + lambda m, s: m.rotaprot_large_uniref50w.embed(SEQ, reduction=None), + posts=[_embedded("rotaprot-large-uniref50w", None)], + ), + "embedding.ablang2.embed": Case( + lambda m, s: m.ablang2.embed(SEQ), posts=[_embedded("ablang2")] + ), + "embedding.esm2.embed": Case( + lambda m, s: m.esm2.embed(SEQ), posts=[_embedded("esm2_t33_650M_UR50D")] + ), + "embedding.poet.embed(prompt)": Case( + lambda m, s: m.poet.embed(SEQ, prompt="prompt-1"), + posts=[_embedded("poet", prompt_id="prompt-1")], + ), + "embedding.poet2.embed(prompt, query, decoder)": Case( + lambda m, s: m.poet2.embed( + SEQ, + prompt="prompt-1", + query=Q, + use_query_structure_in_decoder=False, + decoder_type="mlm", + reduction=None, + ), + posts=[ + _embedded( + "poet-2", + None, + prompt_id="prompt-1", + query_id=Q, + use_query_structure_in_decoder=False, + decoder_type="mlm", + ) + ], + ), + "embedding.prot_seq.logits": Case( + lambda m, s: m.prot_seq.logits(SEQ), + posts=[("v1/models/prot-seq/batch/logits", {"sequences": SEQ})], + ), + "embedding.poet2.logits(prompt, query, decoder)": Case( + lambda m, s: m.poet2.logits( + SEQ, prompt="prompt-1", query=Q, decoder_type="clm" + ), + posts=[ + ( + "v1/models/poet-2/batch/logits", + { + "sequences": SEQ, + "prompt_id": "prompt-1", + "query_id": Q, + "decoder_type": "clm", + }, + ) + ], + ), + "embedding.prot_seq.attn": Case( + lambda m, s: m.prot_seq.attn(SEQ), + posts=[("v1/models/prot-seq/batch/attn", {"sequences": SEQ})], + ), + "embedding.poet.score(prompt)": Case( + lambda m, s: m.poet.score(SEQ, prompt="prompt-1"), + posts=[ + ( + "v1/models/poet/batch/loglikelihood", + {"sequences": SEQ, "prompt_id": "prompt-1"}, + ) + ], + ), + "embedding.poet2.score(prompt, query, decoder)": Case( + lambda m, s: m.poet2.score( + SEQ, + prompt="prompt-1", + query=Q, + use_query_structure_in_decoder=True, + decoder_type="clm", + ), + posts=[ + ( + "v1/models/poet-2/batch/loglikelihood", + { + "sequences": SEQ, + "prompt_id": "prompt-1", + "query_id": Q, + "use_query_structure_in_decoder": True, + "decoder_type": "clm", + }, + ) + ], + ), + "embedding.poet.indel(insert)": Case( + lambda m, s: m.poet.indel("MKT", insert="A", prompt="prompt-1"), + posts=[ + ( + "v1/models/poet/indel/scores", + {"base_sequence": "MKT", "insert": "A", "prompt_id": "prompt-1"}, + ) + ], + ), + "embedding.poet2.indel(delete, decoder)": Case( + lambda m, s: m.poet2.indel( + "MKT", delete=[1, 2], prompt="prompt-1", decoder_type="clm" + ), + posts=[ + ( + "v1/models/poet-2/indel/scores", + { + "base_sequence": "MKT", + "delete": [1, 2], + "prompt_id": "prompt-1", + "decoder_type": "clm", + }, + ) + ], + ), + "embedding.poet.single_site": Case( + lambda m, s: m.poet.single_site("MKT", prompt="prompt-1"), + posts=[ + ( + "v1/models/poet/single-site/scores", + {"base_sequence": "MKT", "prompt_id": "prompt-1"}, + ) + ], + ), + "embedding.poet2.single_site(query, decoder)": Case( + lambda m, s: m.poet2.single_site( + "MKT", + prompt="prompt-1", + query=Q, + use_query_structure_in_decoder=True, + decoder_type="clm", + ), + posts=[ + ( + "v1/models/poet-2/single-site/scores", + { + "base_sequence": "MKT", + "prompt_id": "prompt-1", + "query_id": Q, + "use_query_structure_in_decoder": True, + "decoder_type": "clm", + }, + ) + ], + ), + "embedding.esmc.single_site": Case( + lambda m, s: m.esmc_300m.single_site("MKT"), + posts=[("v1/models/esmc-300m/single-site/scores", {"base_sequence": "MKT"})], + ), + "embedding.poet.generate": Case( + lambda m, s: m.poet.generate( + prompt="prompt-1", + num_samples=100, + temperature=1.0, + top_k=20, + top_p=1.0, + max_length=1000, + random_seed=7, + ), + posts=[ + ( + "v1/models/poet/generate/sequences", + { + "prompt_id": "prompt-1", + "num_samples": 100, + "temperature": 1.0, + "top_k": 20, + "top_p": 1.0, + "max_length": 1000, + "random_seed": 7, + }, + ) + ], + ), + "embedding.poet2.generate(query list, ensemble)": Case( + lambda m, s: m.poet2.generate( + prompt="prompt-1", + query=[Q, Q2], + use_query_structure_in_decoder=True, + ensemble_weights=[1.0, 2.0], + ensemble_method="arithmetic", + num_samples=10, + random_seed=7, + ), + posts=[ + ( + "v1/models/poet-2/generate/sequences", + { + "prompt_id": "prompt-1", + "query_id": [Q, Q2], + "use_query_structure_in_decoder": True, + "ensemble_weights": [1.0, 2.0], + "ensemble_method": "arithmetic", + "num_samples": 10, + "random_seed": 7, + }, + ) + ], + ), + "embedding.poet2.generate(design)": Case( + lambda m, s: m.poet2.generate(design=_design(s), random_seed=7), + posts=[ + ( + "v1/models/poet-2/generate/sequences", + {"design_id": DESIGN_ID, "random_seed": 7}, + ) + ], + ), + "embedding.poet.fit_svd(prompt)": Case( + lambda m, s: m.poet.fit_svd(SEQ, prompt="prompt-1", reduction="MEAN"), + posts=[ + ( + "v1/models/svd", + { + "output": "embeddings", + "sequences": SEQ, + "model_id": "poet", + "prompt_id": "prompt-1", + "reduction": "MEAN", + }, + ) + ], + ), + "embedding.poet2.fit_svd(assay, query, decoder)": Case( + lambda m, s: m.poet2.fit_svd( + assay=_assay(), + n_components=2, + prompt="prompt-1", + query=Q, + use_query_structure_in_decoder=False, + decoder_type="mlm", + ), + posts=[ + ( + "v1/models/svd", + { + "n_components": 2, + "output": "embeddings", + "assay_id": "assay-1", + "model_id": "poet-2", + "prompt_id": "prompt-1", + "query_id": Q, + "use_query_structure_in_decoder": False, + "decoder_type": "mlm", + }, + ) + ], + ), + "embedding.esm2.fit_umap": Case( + lambda m, s: m.esm2.fit_umap(assay=_assay()), + posts=[ + ( + "v1/models/umap", + { + "model_id": "esm2_t33_650M_UR50D", + "sequences": ["MKT", "AC", "DE", "FG", "HI"], + "reduction": "MEAN", + }, + ) + ], + ), + "embedding.poet2.fit_gp(prompt, query)": Case( + lambda m, s: m.poet2.fit_gp( + "assay-1", + ["fitness"], + reduction="MEAN", + kernel="rational_quadratic", + alpha=0.5, + prompt="prompt-1", + query=Q, + ), + posts=[ + ( + "v1/models/gp", + { + "features": { + "model_id": "poet-2", + "reduction": "MEAN", + "prompt_id": "prompt-1", + "query_id": Q, + }, + "kernel": {"type": "rational_quadratic", "alpha": 0.5}, + "training_dataset": { + "assay_id": "assay-1", + "properties": ["fitness"], + }, + }, + ) + ], + ), + # session.fold + "fold.list_models": Case( + lambda m, s: m.list_models(path=["structures"]), + reads=[("GET", "v1/models")], + ), + "fold.get_model.metadata": Case( + lambda m, s: m.get_model("boltz-2").metadata, + reads=[("GET", "v1/models/boltz-2")], + ), + "fold.esmfold.fold": Case( + lambda m, s: m.esmfold.fold("MKT", num_recycles=4), + posts=[ + ( + "v1/models/esmfold/batch/structures", + {"complexes": [[PROTEIN]], "num_recycles": 4}, + ) + ], + ), + "fold.esmfold2.fold": Case( + lambda m, s: m.esmfold2.fold( + "MKT", num_samples=1, num_recycles=3, num_steps=100, random_seed=7 + ), + posts=[ + ( + "v1/models/esmfold2/batch/structures", + { + "complexes": [[PROTEIN_MSA]], + "num_samples": 1, + "num_recycles": 3, + "num_steps": 100, + "random_seed": 7, + }, + ) + ], + ), + "fold.esmfold2_fast.fold": Case( + lambda m, s: m.esmfold2_fast.fold( + "MKT", num_samples=1, num_recycles=3, num_steps=100, random_seed=7 + ), + posts=[ + ( + "v1/models/esmfold2-fast/batch/structures", + { + "complexes": [[PROTEIN]], + "num_samples": 1, + "num_recycles": 3, + "num_steps": 100, + "random_seed": 7, + }, + ) + ], + ), + "fold.minifold.fold": Case( + lambda m, s: m.minifold.fold("MKT", num_recycles=4), + posts=[ + ( + "v1/models/minifold/batch/structures", + {"complexes": [[PROTEIN]], "num_recycles": 4}, + ) + ], + ), + "fold.alphafold2.fold": Case( + lambda m, s: m.af2.fold("MKT", num_models=1, num_recycles=None, num_relax=0), + posts=[ + ( + "v1/models/alphafold2/batch/structures", + { + "complexes": [[PROTEIN_MSA]], + "num_models": 1, + "num_recycles": None, + "num_relax": 0, + }, + ) + ], + ), + "fold.boltz_1.fold(use_potentials)": Case( + lambda m, s: m.boltz1.fold( + "MKT", + num_samples=1, + num_recycles=3, + num_steps=200, + step_scale=1.638, + use_potentials=True, + random_seed=7, + ), + posts=[ + ( + "v1/models/boltz-1/batch/structures", + { + "complexes": [[PROTEIN_MSA]], + "num_samples": 1, + "num_recycles": 3, + "num_steps": 200, + "step_scale": 1.638, + "use_potentials": True, + "random_seed": 7, + }, + ) + ], + ), + "fold.boltz_1x.fold": Case( + lambda m, s: m.boltz1x.fold("MKT", num_samples=2, random_seed=7), + posts=[ + ( + "v1/models/boltz-1x/batch/structures", + {"complexes": [[PROTEIN_MSA]], "num_samples": 2, "random_seed": 7}, + ) + ], + ), + "fold.boltz_2.fold(constraints, properties, method)": Case( + lambda m, s: m.boltz2.fold( + _ligand_complex(), + constraints=[{"bond": {"atom1": ["A", 1, "N"], "atom2": ["L", 1, "C1"]}}], + properties=[{"affinity": {"binder": "L"}}], + method="X-RAY DIFFRACTION", + random_seed=7, + ), + posts=[ + ( + "v1/models/boltz-2/batch/structures", + { + "complexes": [[PROTEIN_MSA, LIGAND]], + "constraints": [ + {"bond": {"atom1": ["A", 1, "N"], "atom2": ["L", 1, "C1"]}} + ], + "properties": [{"affinity": {"binder": "L"}}], + "method": "X-RAY DIFFRACTION", + "random_seed": 7, + }, + ) + ], + ), + "fold.protenix.fold": Case( + lambda m, s: m.protenix.fold( + "MKT", num_samples=1, num_recycles=10, num_steps=200, random_seed=7 + ), + posts=[ + ( + "v1/models/protenix/batch/structures", + { + "complexes": [[PROTEIN_MSA]], + "num_samples": 1, + "num_recycles": 10, + "num_steps": 200, + "random_seed": 7, + }, + ) + ], + ), + "fold.protenix_v2.fold": Case( + lambda m, s: m.protenix_v2.fold("MKT", random_seed=7), + posts=[ + ( + "v1/models/protenix-v2/batch/structures", + {"complexes": [[PROTEIN_MSA]], "random_seed": 7}, + ) + ], + ), + "fold.rosettafold_3.fold": Case( + lambda m, s: m.rf3.fold( + "MKT", num_samples=1, num_recycles=10, num_steps=50, random_seed=7 + ), + posts=[ + ( + "v1/models/rosettafold-3/batch/structures", + { + "complexes": [[PROTEIN_MSA]], + "num_samples": 1, + "num_recycles": 10, + "num_steps": 50, + "random_seed": 7, + }, + ) + ], + ), + # 0.17.0 session.models handles + "models.rfdiffusion.generate": Case( + lambda m, s: m.rfdiffusion.generate(query=Q, num_samples=2, random_seed=7), + posts=[ + ( + "v1/models/rfdiffusion/generate/structures", + {"query_id": Q, "num_samples": 2, "random_seed": 7}, + ) + ], + ), + "models.proteinmpnn.embed": Case( + lambda m, s: m.proteinmpnn.embed(SEQ, query=Q), + posts=[ + ( + "v1/models/proteinmpnn/batch/embeddings", + {"sequences": SEQ, "reduction": "MEAN", "query_id": Q}, + ) + ], + ), + "models.proteinmpnn.score": Case( + lambda m, s: m.proteinmpnn.score( + SEQ, query=Q, decoding_orders=1, random_seed=1 + ), + posts=[ + ( + "v1/models/proteinmpnn/batch/loglikelihood", + { + "sequences": SEQ, + "query_id": Q, + "decoding_orders": 1, + "random_seed": 1, + }, + ) + ], + ), + "models.proteinmpnn.single_site": Case( + lambda m, s: m.proteinmpnn.single_site("MKT", query=Q, random_seed=1), + posts=[ + ( + "v1/models/proteinmpnn/single-site/scores", + {"base_sequence": "MKT", "query_id": Q, "random_seed": 1}, + ) + ], + ), + "models.proteinmpnn.generate(design)": Case( + lambda m, s: m.proteinmpnn.generate( + design=_design(s), + num_samples=100, + temperature=0.1, + random_seed=7, + ), + posts=[ + ( + "v1/models/proteinmpnn/generate/sequences", + { + "design_id": DESIGN_ID, + "num_samples": 100, + "temperature": 0.1, + "random_seed": 7, + }, + ) + ], + ), + "models.solublempnn.generate": Case( + lambda m, s: m.solublempnn.generate(query=Q, num_samples=10, random_seed=7), + posts=[ + ( + "v1/models/solublempnn/generate/sequences", + {"query_id": Q, "num_samples": 10, "random_seed": 7}, + ) + ], + ), + "models.esmif1.score": Case( + lambda m, s: m.esmif1.score(SEQ, query=Q), + posts=[ + ( + "v1/models/esm-if1/batch/loglikelihood", + {"sequences": SEQ, "query_id": Q}, + ) + ], + ), + "models.esmif1.single_site": Case( + lambda m, s: m.esmif1.single_site("MKT", query=Q), + posts=[ + ( + "v1/models/esm-if1/single-site/scores", + {"base_sequence": "MKT", "query_id": Q}, + ) + ], + ), + "models.esmif1.generate": Case( + lambda m, s: m.esmif1.generate( + query=Q, num_samples=100, temperature=1.0, random_seed=7 + ), + posts=[ + ( + "v1/models/esm-if1/generate/sequences", + { + "query_id": Q, + "num_samples": 100, + "temperature": 1.0, + "random_seed": 7, + }, + ) + ], + ), + "models.boltzgen.generate": Case( + lambda m, s: m.boltzgen.generate( + query=Q, + num_samples=1, + diffusion_batch_size=2, + step_scale=1.0, + noise_scale=1.0, + random_seed=7, + ), + posts=[ + ( + "v1/models/boltzgen/generate/structures", + { + "query_id": Q, + "num_samples": 1, + "diffusion_batch_size": 2, + "step_scale": 1.0, + "noise_scale": 1.0, + "random_seed": 7, + }, + ) + ], + ), + # session.svd + "svd.fit_svd(assay)": Case( + lambda m, s: m.prot_seq.fit_svd( + assay=_assay(), n_components=2, reduction="MEAN" + ), + posts=[ + ( + "v1/models/svd", + { + "n_components": 2, + "output": "embeddings", + "assay_id": "assay-1", + "model_id": "prot-seq", + "reduction": "MEAN", + }, + ) + ], + ), + "svd.get_svd": Case( + lambda m, s: m.SVD(id="s-1"), reads=[("GET", "v1/models/svd/s-1")] + ), + "svd.list_svd(limit, offset)": Case( + lambda m, s: m.SVD.list(limit=10, offset=5), + reads=[("GET", "v1/models")], + ), + "svd.delete_svd": Case( + lambda m, s: m.get_model("svd/s-1").delete(), + reads=[("DELETE", "v1/models/svd/s-1")], + ), + "svd.SVDModel.embed": Case( + lambda m, s: m.get_model("svd/s-1").embed(SEQ), + posts=[("v1/models/svd/s-1/batch/embeddings", {"sequences": SEQ})], + ), + "svd.SVDModel.get_inputs": Case( + lambda m, s: _fit_future(s, "s-1").get(output="sequences"), + reads=[("OUTPUT", "s-1/sequences")], + ), + "svd.SVDModel.fit_umap": Case( + lambda m, s: m.get_model("svd/s-1").fit_umap( + sequences=["MKT", "AC", "DE", "FG", "HI"] + ), + posts=[ + ( + "v1/models/umap", + { + "model_id": "svd/s-1", + "sequences": ["MKT", "AC", "DE", "FG", "HI"], + }, + ) + ], + ), + "svd.SVDModel.fit_gp": Case( + lambda m, s: m.get_model("svd/s-1").fit_gp("assay-1", ["fitness"]), + posts=[ + ( + "v1/models/gp", + { + "features": {"model_id": "svd/s-1"}, + "kernel": {"type": "rbf"}, + "training_dataset": { + "assay_id": "assay-1", + "properties": ["fitness"], + }, + }, + ) + ], + ), + # session.umap + "umap.fit_umap(PLM, assay)": Case( + lambda m, s: m.esm2_t33_650M_UR50D.fit_umap( + assay=_assay(), + reduction="MEAN", + n_components=3, + n_neighbors=10, + min_dist=0.2, + ), + posts=[ + ( + "v1/models/umap", + { + "model_id": "esm2_t33_650M_UR50D", + "sequences": ["MKT", "AC", "DE", "FG", "HI"], + "reduction": "MEAN", + "n_components": 3, + "n_neighbors": 10, + "min_dist": 0.2, + }, + ) + ], + ), + "umap.get_umap": Case( + lambda m, s: m.UMAP(id="u-1"), reads=[("GET", "v1/models/umap/u-1")] + ), + "umap.list_umap(limit, offset)": Case( + lambda m, s: m.UMAP.list(limit=10, offset=5), + reads=[("GET", "v1/models")], + ), + "umap.delete_umap": Case( + lambda m, s: m.get_model("umap/u-1").delete(), + reads=[("DELETE", "v1/models/umap/u-1")], + ), + "umap.UMAPModel.embed": Case( + lambda m, s: m.get_model("umap/u-1").embed(SEQ), + posts=[("v1/models/umap/u-1/batch/embeddings", {"sequences": SEQ})], + ), + "umap.UMAPModel.sequences": Case( + lambda m, s: _fit_future(s, "u-1").get(output="sequences"), + reads=[("OUTPUT", "u-1/sequences")], + ), + "umap.UMAPModel.embeddings": Case( + lambda m, s: _fit_future(s, "u-1").get(output="embeddings"), + reads=[("OUTPUT", "u-1/embeddings")], + ), + # session.predictor + "predictor.fit_gp": Case( + lambda m, s: m.esm2_t33_650M_UR50D.fit_gp( + "assay-1", + ["fitness"], + reduction="MEAN", + kernel="periodic", + period=3.0, + name="gp", + description="d", + ), + posts=[ + ( + "v1/models/gp", + { + "features": { + "model_id": "esm2_t33_650M_UR50D", + "reduction": "MEAN", + }, + "kernel": {"type": "periodic", "period": 3.0}, + "training_dataset": { + "assay_id": "assay-1", + "properties": ["fitness"], + }, + "name": "gp", + "description": "d", + }, + ) + ], + ), + "predictor.get_predictor": Case( + lambda m, s: m.GP(id="p-1"), reads=[("GET", "v1/models/gp/p-1")] + ), + "predictor.list_predictors(limit, offset)": Case( + lambda m, s: m.GP.list(limit=10, offset=5), + reads=[("GET", "v1/models")], + ), + "predictor.delete_predictor": Case( + lambda m, s: m.get_model("gp/p-1").delete(), + reads=[("DELETE", "v1/models/gp/p-1")], + ), + "predictor.PredictorModel.predict": Case( + lambda m, s: _gp(m).predict(SEQ), + posts=[("v1/models/gp/p-1/batch/predictions", {"sequences": SEQ})], + ), + "predictor.PredictorModel.single_site": Case( + lambda m, s: _gp(m).single_site("MKT"), + posts=[("v1/models/gp/p-1/single-site/predictions", {"base_sequence": "MKT"})], + ), + "predictor.PredictorModel.crossvalidate": Case( + lambda m, s: _gp(m).crossvalidate(n_splits=5), + posts=[("v1/models/gp/p-1/crossvalidate", {"n_splits": 5})], + ), + "predictor.CVResultFuture.get": Case( + lambda m, s: _gp(m).evaluations("cv-1"), + reads=[("GET", "v1/models/gp/p-1/evaluations/cv-1")], + ), + "predictor.PredictorModel.kernel": Case( + lambda m, s: _gp(m).kernel, + reads=[("GET", "v1/models/gp/p-1/hyperparameters")], + ), + "predictor.PredictorModel.traingraphs": Case( + lambda m, s: _gp(m).training(), + reads=[("GET", "v1/models/gp/p-1/training")], + ), + "predictor.get_predictor(include_stats)": Case( + lambda m, s: _gp(m).evaluations(), + reads=[("GET", "v1/models/gp/p-1/evaluations")], + ), +} + + +@pytest.mark.parametrize("case", CASES.values(), ids=CASES.keys()) +def test_the_replacement_submits_the_same_work(models_session, model_card, case): + for family in ("svd", "umap", "gp"): + models_session.get_routes[f"v1/models/{family}"] = [] + models_session.get_routes |= { + "v1/models": [], + "v1/models/svd/s-1": model_card("svd/s-1") | {"svd": {"id": "s-1"}}, + "v1/models/umap/u-1": model_card("umap/u-1"), + "v1/models/gp/p-1": model_card("gp/p-1") + | {"spec": {"kernel": {"type": "RBF"}}}, + "v1/models/gp/p-1/hyperparameters": { + "fitness": {"lengthscale": [0.8], "outputscale": [2.0]} + }, + } + models = ModelsAPI(models_session.session) + with patch("openprotein.jobs.jobs.JobsAPI") as jobs: + jobs.return_value._iter_job_outputs.return_value = iter([]) + case.call(models, models_session.session) + outputs = [ + ("OUTPUT", f"{call.args[0]}/{call.args[1]}") + for call in jobs.return_value._iter_job_outputs.call_args_list + ] + + assert models_session.submissions == case.posts + session = models_session.session + made = [ + *(("GET", call.args[0]) for call in session.get.call_args_list), + *(("DELETE", call.args[0]) for call in session.delete.call_args_list), + *outputs, + ] + for read in case.reads: + assert read in made + + +@pytest.mark.parametrize( + "path, body", + [ + ( + "v1/models/poet-2/batch/loglikelihood", + {"sequences": SEQ, "decoder_type": "mlm"}, + ), + ("v1/models/esm2_t6_8M_UR50D/batch/embeddings", {"sequences": SEQ, "x": 1}), + ("v1/models/poet/batch/logits", {"sequences": SEQ, "reduction": "MEAN"}), + ("v1/models/esm-if1/generate/sequences", {"query_id": "not-a-uuid"}), + ("v1/models/umap", {"model_id": "esm2", "sequences": ["M", "K", "T"]}), + ("v1/models/gp/p-1/crossvalidate", {"n_splits": 1}), + ("v1/models/prot-seq/single-site/scores", {"base_sequence": "MKT"}), + ], +) +def test_the_contract_check_refuses_a_body_main_refuses(path, body): + with pytest.raises((AssertionError, ValidationError)): + check_body(path, body) + + +@pytest.mark.parametrize( + "call", + [ + lambda m: m.prot_seq.single_site("MKT"), + lambda m: m.esm1b.single_site("MKT"), + lambda m: m.ablang2.attn(SEQ), + lambda m: m.proteinmpnn.indel("MKT", insert="A"), + lambda m: m.esmfold.generate(), + lambda m: m.get_model("svd/s-1").predict(SEQ), + ], +) +def test_a_verb_on_a_method_the_card_lacks_submits_nothing(models_session, call): + with pytest.raises(ValueError, match="has no"): + call(ModelsAPI(models_session.session)) + assert models_session.submissions == [] + + +CIF = (Path(__file__).parents[1] / "data" / "test_protein.cif").read_text() + + +@dataclass +class Read: + """A submission, the outputs its job stores, and a check of each decoded value.""" + + call: Callable[[ModelsAPI], Future] + future: type[Future] + stored: dict[str, list[Any]] + check: dict[str, Callable[[Any], Any]] + + +def _array(*shape: int) -> Stored: + return Stored( + "ndarray-v1", + np.arange(1, np.empty(shape).size + 1, dtype=np.float32).reshape(shape), + ) + + +def _is_array(*shape: int) -> Callable[[Any], bool]: + return lambda v: isinstance(v, np.ndarray) and v.shape == shape and v.any() + + +READS: dict[str, Read] = { + "embeddings": Read( + lambda m: m.prot_seq.embed(SEQ, reduction=None), + EmbeddingFuture, + {"embeddings": [_array(3, 4)]}, + {"embeddings": _is_array(3, 4)}, + ), + "logits": Read( + lambda m: m.esm2.logits(SEQ), + LogitsFuture, + {"logits": [_array(3, 20)]}, + {"logits": _is_array(3, 20)}, + ), + "attn": Read( + lambda m: m.prot_seq.attn(SEQ), + AttentionFuture, + {"attn": [_array(2, 3, 3)]}, + {"attn": _is_array(2, 3, 3)}, + ), + "fold": Read( + lambda m: m.boltz2.fold("MKT", random_seed=1), + StructurePredictionFuture, + { + "structures": [Stored("mmcif-utf8-v1", CIF)], + "plddt": [_array(1, 3)], + "pae": [_array(1, 3, 3)], + "ipae": [_array(1)], + "confidence": [Stored("json-utf8-v1", [{"ptm": 0.8, "iptm": 0.7}])], + "affinity": [Stored("json-utf8-v1", {"affinity_pred_value": 1.2})], + }, + { + "structures": lambda value: ( + isinstance(value, Structure) + and len(value) > 0 + and value[0].get_chains() + ), + "plddt": _is_array(1, 3), + "pae": _is_array(1, 3, 3), + "ipae": _is_array(1), + "confidence": lambda v: v == [{"ptm": 0.8, "iptm": 0.7}], + "affinity": lambda v: v == {"affinity_pred_value": 1.2}, + }, + ), + "rosettafold-3 score": Read( + lambda m: m.rf3.fold("MKT", random_seed=1), + StructurePredictionFuture, + {"score": [Stored(None, b"ptm,iptm\n0.8,0.7\n")]}, + {"score": lambda v: v.equals(pd.DataFrame({"ptm": [0.8], "iptm": [0.7]}))}, + ), + "loglikelihood": Read( + lambda m: m.poet.score(SEQ, prompt="prompt-1"), + LogLikelihoodFuture, + {"loglikelihood": [-12.5]}, + {"loglikelihood": lambda v: v == -12.5}, + ), + "replicate loglikelihood": Read( + lambda m: m.poet2.score(SEQ, prompt="prompt-1"), + LogLikelihoodFuture, + {"loglikelihood": [[-12.5, -11.0]]}, + {"loglikelihood": lambda v: v == [-12.5, -11.0]}, + ), + "single-site scores": Read( + lambda m: m.esmc_300m.single_site("MK"), + SingleSiteScoreFuture, + {"score": [0.1 * i for i in range(40)]}, + {"score": lambda v: isinstance(v, float)}, + ), + "indel scores": Read( + lambda m: m.poet.indel("MKT", delete=[1], prompt="prompt-1"), + IndelScoreFuture, + {"score": [-3.0, -2.0, -1.0, -4.0]}, + {"score": lambda v: isinstance(v, float)}, + ), + "generate": Read( + lambda m: m.proteinmpnn.generate(query=Q, num_samples=2, random_seed=1), + SequenceGenerationFuture, + {"sequences": ["MKT", "MRT"], "loglikelihood": [-3.5, -4.0]}, + { + "sequences": lambda v: isinstance(v, str) and v, + "loglikelihood": lambda v: isinstance(v, float), + }, + ), + "generate structures": Read( + lambda m: m.rfdiffusion.generate(query=Q, random_seed=1), + StructureDesignFuture, + {"structures": [Stored("mmcif-utf8-v1", CIF)]}, + {"structures": lambda value: isinstance(value, Complex) and value.get_chains()}, + ), + "gp predictions": Read( + lambda m: _gp(m).predict(SEQ), + PredictionFuture, + {"predictions": [{"fitness": {"mean": 0.5, "variance": 0.1}}]}, + {"predictions": lambda v: v == {"fitness": {"mean": 0.5, "variance": 0.1}}}, + ), + "svd projection": Read( + lambda m: m.get_model("svd/s-1").embed(SEQ), + EmbeddingFuture, + {"embeddings": [_array(8)]}, + {"embeddings": _is_array(8)}, + ), + "umap fit set": Read( + lambda m: m.get_model("svd/s-1").fit_umap(sequences=["MKT", "AC", "DE", "FG"]), + UMAPFitFuture, + { + "sequences": ["MKT", "AC", "DE", "FG"], + "embeddings": [_array(2), _array(2), _array(2), _array(2)], + }, + {"sequences": lambda v: isinstance(v, str) and v, "embeddings": _is_array(2)}, + ), + "svd fit set": Read( + lambda m: m.esm2.fit_svd(SEQ, n_components=2), + SVDFitFuture, + {"sequences": ["MKT"], "embeddings": [_array(2)]}, + {"sequences": lambda v: v == "MKT", "embeddings": _is_array(2)}, + ), + "gp single-site predictions": Read( + lambda m: _gp(m).single_site("MK"), + SingleSitePredictionFuture, + {"predictions": [{"fitness": {"mean": 0.5, "variance": 0.1}}]}, + {"predictions": lambda v: v == {"fitness": {"mean": 0.5, "variance": 0.1}}}, + ), +} + + +@pytest.mark.parametrize("read", READS.values(), ids=READS.keys()) +def test_each_reader_decodes_its_stored_values(models_session, read): + """Every output a job stores reads back decoded, one value per position.""" + job_id = SUBMITTED_JOB["job_id"] + for output, values in read.stored.items(): + models_session.outputs[(job_id, output)] = values + + future = read.call(ModelsAPI(models_session.session)) + assert type(future) is read.future + + for output, check in read.check.items(): + values = future.get(output=output) + assert len(values) == len(read.stored[output]) > 0 + assert all(check(value) for value in values), output diff --git a/tests/models/test_public_names.py b/tests/models/test_public_names.py new file mode 100644 index 0000000..3449e28 --- /dev/null +++ b/tests/models/test_public_names.py @@ -0,0 +1,51 @@ +import importlib + +import pytest + + +@pytest.mark.parametrize( + ("module_name", "helper_names"), + [ + ( + "generative.base", + ("check_inputs", "query_ids", "takes_list", "with_param"), + ), + ( + "foundational.poet", + ("check_inputs", "prompt_id", "query_ids", "takes_list", "with_param"), + ), + ( + "foundational.poet2", + ("check_inputs", "prompt_id", "query_ids", "takes_list", "with_param"), + ), + ("estimators", ("as_dataset", "assay_id", "model_id")), + ("model", ("assay_sequences",)), + ("svd", ("as_dataset", "assay_id", "model_id")), + ("gp", ("assay_id", "model_id")), + ("umap", ("assay_sequences", "model_id")), + ], +) +def test_input_helpers_are_not_public(module_name, helper_names): + module = importlib.import_module(f"openprotein.models.{module_name}") + for helper_name in helper_names: + assert not hasattr(module, helper_name), helper_name + + +def test_deprecation_shims_export_no_helper_names_from_the_models_package(): + import openprotein.models + + assert not {"import_module", "Any", "warn_deprecated"} & set( + openprotein.models.__all__ + ) + + +def test_download_workers_is_not_bound_in_the_jobs_module(): + import 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(): + import openprotein.data.prompts.prompts + + assert "get_prompt" not in vars(openprotein.data.prompts.prompts) diff --git a/tests/models/test_reference_docstrings.py b/tests/models/test_reference_docstrings.py new file mode 100644 index 0000000..a451e21 --- /dev/null +++ b/tests/models/test_reference_docstrings.py @@ -0,0 +1,109 @@ +import re +from inspect import cleandoc + +import pytest + +from openprotein import OpenProtein +from openprotein.jobs.futures import ( + Future, + FutureUnit, +) +from openprotein.models import ( + GPModel, + MethodDescriptor, + Model, + ModelDescription, + ModelMetadata, + ModelsAPI, + StructureGenerationJob, + SVDModel, + UMAPModel, +) +from openprotein.models.svd import SVDEmbeddingSource, _SVDRecord + + +def _own_doc(cls: type, name: str) -> str: + member = vars(cls)[name] + if isinstance(member, property): + member = member.fget + elif isinstance(member, (classmethod, staticmethod)): + member = member.__func__ + assert member is not None + return cleandoc(member.__doc__ or "") + + +def _attributes(cls: type) -> set[str]: + doc = cleandoc(vars(cls).get("__doc__") or "") + assert "Attributes\n----------" in doc + return set(re.findall(r"^([a-z][a-z0-9_]*)\s*:", doc, flags=re.MULTILINE)) + + +def test_model_identity_is_documented(): + assert "id" in _attributes(Model) + + +@pytest.mark.parametrize("name", ["metadata", "methods"]) +def test_model_discovery_properties_have_own_documentation(name): + assert _own_doc(Model, name) + + +def test_models_api_documents_the_session_entrypoint(): + assert "session.models" in cleandoc(ModelsAPI.__doc__ or "") + + +@pytest.mark.parametrize( + ("schema", "fields"), + [ + (ModelDescription, {"summary", "citation_title", "doi"}), + (MethodDescriptor, {"path", "outputs", "description", "name"}), + (ModelMetadata, set(ModelMetadata.model_fields)), + ], +) +def test_model_schema_fields_have_attribute_documentation(schema, fields): + assert fields <= _attributes(schema) + + +@pytest.mark.parametrize( + ("owner", "name"), + [ + (Future, "units"), + (FutureUnit, "job_id"), + (FutureUnit, "position"), + (FutureUnit, "output"), + (FutureUnit, "status"), + ], +) +def test_task_provenance_properties_have_own_documentation(owner, name): + assert _own_doc(owner, name) + + +def test_task_factory_is_private_in_the_reference(): + assert ":meta private:" in _own_doc(Future, "create") + + +@pytest.mark.parametrize( + ("owner", "name"), + [ + (SVDModel, "embedding"), + (SVDModel, "requested_n_components"), + (SVDModel, "delete"), + (GPModel, "delete"), + (UMAPModel, "delete"), + ], +) +def test_fitted_model_operations_have_own_documentation(owner, name): + assert _own_doc(owner, name) + + +@pytest.mark.parametrize("schema", [SVDEmbeddingSource, _SVDRecord]) +def test_svd_record_fields_have_attribute_documentation(schema): + assert set(schema.model_fields) == _attributes(schema) + + +def test_compatibility_design_job_documents_its_type(): + assert "job_type" in _attributes(StructureGenerationJob) + + +@pytest.mark.parametrize(("name", "label"), [("svd", "SVD"), ("umap", "UMAP")]) +def test_session_projection_properties_document_their_api(name, label): + assert label in _own_doc(OpenProtein, name) diff --git a/tests/models/test_reload_contracts.py b/tests/models/test_reload_contracts.py new file mode 100644 index 0000000..6b6b6d9 --- /dev/null +++ b/tests/models/test_reload_contracts.py @@ -0,0 +1,211 @@ +from types import SimpleNamespace +from unittest.mock import MagicMock + +import numpy as np +import pytest + +from openprotein.data.prompts import Prompt as StoredPrompt +from openprotein.errors import HTTPError +from openprotein.jobs import Future, Job, JobsAPI, JobStatus, _dispatch +from openprotein.jobs import api as job_api +from openprotein.jobs.futures import ( + CrossvalidateFuture, + CrossvalidateResults, + GPFitFuture, +) +from openprotein.models import gp as models_gp +from openprotein.models.gp import GPModel +from openprotein.molecules import Protein +from openprotein.predictor import api as predictor_api +from openprotein.predictor.models import PredictorModel +from openprotein.predictor.validate import CVResultFuture +from openprotein.prompt import api as prompt_api +from openprotein.prompt.models import Prompt +from openprotein.prompt.schemas import PromptMetadata +from tests.models.test_task_dispatch import CASES, task_job + + +@pytest.mark.parametrize(("path", "expected"), CASES) +def test_jobs_reconstruct_identified_typed_futures( + mock_session, monkeypatch, path, expected +): + job = task_job(path) + monkeypatch.setattr(job_api, "job_get", lambda session, job_id: job) + future = JobsAPI(mock_session).get(job.job_id) + assert type(future) is expected + + +def test_gp_training_keeps_compatibility_reconstruction(mock_session, monkeypatch): + payload = { + "job_id": "e0b1c3d4-0000-4000-8000-00000000000a", + "job_type": "/predictor/train", + "status": "SUCCESS", + "created_date": "2026-10-21T08:00:00Z", + } + job = Job.create(payload) + curves = [{"measurement_name": "fitness", "loss": [1.0]}] + metadata = SimpleNamespace(traingraphs=curves, is_done=lambda: True) + fitted = GPModel(mock_session, f"gp/{job.job_id}") + monkeypatch.setattr( + predictor_api, "predictor_get", lambda session, model_id: metadata + ) + monkeypatch.setattr(models_gp, "_load", lambda session, model_id: fitted) + + submitted = GPFitFuture(mock_session, job) + reloaded = Future.create(mock_session, job=job) + + assert submitted.get() is fitted + assert type(reloaded) is PredictorModel + assert reloaded.get() == curves + + +def test_crossvalidation_keeps_compatibility_reconstruction(mock_session, monkeypatch): + payload = { + "job_id": "e0b1c3d4-0000-4000-8000-00000000000a", + "job_type": "/predictor/crossvalidate", + "status": "SUCCESS", + "created_date": "2026-10-21T08:00:00Z", + } + job = Job.create(payload) + evaluation = { + "job_id": job.job_id, + "rows": [ + { + "row_index": 0, + "sequence": "MKT", + "property": "activity", + "y": 1.0, + "mean": 0.9, + "variance": 0.1, + "fold": None, + } + ], + } + scores = (np.array([1.0]), np.array([0.9]), np.array([0.1])) + monkeypatch.setattr( + GPModel, "evaluations", lambda self, evaluation_id=None: evaluation + ) + monkeypatch.setattr( + predictor_api, + "predictor_crossvalidate_get", + lambda session, job_id: b"result", + ) + monkeypatch.setattr(predictor_api, "decode_crossvalidate", lambda data: scores) + + submitted = CrossvalidateFuture(mock_session, job, GPModel(mock_session, "gp/p-1")) + reloaded = Future.create(mock_session, job=job) + + results = submitted.get() + assert isinstance(results, CrossvalidateResults) + assert (results.row_index.tolist(), results.measurement_name.tolist()) == ( + [0], + ["activity"], + ) + assert results.fold is None + assert type(reloaded) is CVResultFuture + assert reloaded.get() is scores + + +def test_an_align_prompt_job_keeps_compatibility_reconstruction( + mock_session, monkeypatch +): + payload = { + "job_id": "e0b1c3d4-0000-4000-8000-00000000000a", + "job_type": "/align/prompt", + "status": "SUCCESS", + "created_date": "2026-10-21T08:00:00Z", + } + job = Job.create(payload) + contexts = [[Protein(sequence="MKT")]] + metadata = PromptMetadata( + id=job.job_id, + job_id=job.job_id, + name="sample", + description=None, + created_date=job.created_date, + num_replicates=1, + status=job.status, + ) + mock_session.jobs = JobsAPI(mock_session) + monkeypatch.setattr(job_api, "job_get", lambda session, job_id: job) + monkeypatch.setattr( + prompt_api, "get_prompt_metadata", lambda session, prompt_id: metadata + ) + monkeypatch.setattr(prompt_api, "get_prompt", lambda session, prompt_id: contexts) + + reloaded = Future.create(mock_session, job=job) + assert type(reloaded) is Prompt + assert reloaded.get() == contexts + + +SAMPLING_JOB = { + "job_id": "e0b1c3d4-0000-4000-8000-00000000000a", + "job_type": "/prompt/sample_msa", + "status": "RUNNING", + "created_date": "2026-10-21T08:00:00Z", +} + + +def test_a_sampling_job_reloads_as_the_stored_prompt_it_samples(mock_session): + stored = { + "id": SAMPLING_JOB["job_id"], + "status": "SUCCESS", + "job_id": SAMPLING_JOB["job_id"], + "name": "sampled", + } + mock_session.get.return_value.json.return_value = stored + + reloaded = Future.create(mock_session, job=Job.create(SAMPLING_JOB)) + + assert isinstance(reloaded, StoredPrompt) + assert (reloaded.id, reloaded.name) == (SAMPLING_JOB["job_id"], "sampled") + assert reloaded.status is JobStatus.SUCCESS + mock_session.get.assert_called_once_with( + f"v1/data/prompts/{SAMPLING_JOB['job_id']}" + ) + + +def test_a_sampling_job_whose_prompt_is_not_stored_yet_reports_the_job( + mock_session, +): + response = MagicMock(status_code=404) + mock_session.get.side_effect = HTTPError(response) + + reloaded = Future.create(mock_session, job=Job.create(SAMPLING_JOB)) + + assert isinstance(reloaded, StoredPrompt) + assert (reloaded.id, reloaded.job_id) == (SAMPLING_JOB["job_id"],) * 2 + assert reloaded.status is JobStatus.RUNNING + mock_session.get.assert_called_once_with( + f"v1/data/prompts/{SAMPLING_JOB['job_id']}" + ) + + +def test_fitted_encoded_identity_preserves_the_instance_id(mock_session): + job = Job.create( + { + "job_id": "e0b1c3d4-0000-4000-8000-00000000000a", + "job_type": "/models/gp/p-1/crossvalidate", + "status": "PENDING", + "created_date": "2026-10-21T08:00:00Z", + } + ) + + assert _dispatch.identity(job) == ("gp/p-1", "crossvalidate") + assert type(Future.create(mock_session, job=job)) is Future + mock_session.get.assert_not_called() + + +def test_models_records_without_identity_remain_trackable(mock_session): + job = Job.create( + { + "job_id": "e0b1c3d4-0000-4000-8000-00000000000a", + "job_type": "/models", + "status": "PENDING", + "created_date": "2026-10-21T08:00:00Z", + } + ) + future = Future.create(mock_session, job=job) + assert type(future) is Future + assert future.id == job.job_id + mock_session.get.assert_not_called() diff --git a/tests/models/test_static_accessors.py b/tests/models/test_static_accessors.py new file mode 100644 index 0000000..d34cf1f --- /dev/null +++ b/tests/models/test_static_accessors.py @@ -0,0 +1,251 @@ +"""Static model accessors submit through the models API.""" + +from unittest.mock import MagicMock + +import pytest + +from openprotein.errors import HTTPError +from openprotein.models import ( + ESM1, + ESM2, + ESMC, + ESMIF1, + AbLang2, + AlphaFlow, + AlphaFold2, + BioEmu, + Boltz1, + Boltz2, + BoltzGen, + ESMFlow, + ESMFold, + ESMFold2, + GPModel, + MiniFold, + Model, + ModelsAPI, + OpenDDE, + PoET, + PoET2, + ProteinMPNN, + Protenix, + ProtenixV2, + ProtSeq, + ProtT5, + RFdiffusion, + RosettaFold3, + RotaProt, + SVDModel, + UMAPModel, +) + +HANDLES: dict[str, type[Model]] = { + "rfdiffusion": RFdiffusion, + "proteinmpnn": ProteinMPNN, + "solublempnn": ProteinMPNN, + "boltzgen": BoltzGen, + "esm-if1": ESMIF1, + "poet-2": PoET2, + "poet": PoET, + "prot-seq": ProtSeq, + "rotaprot-large-uniref50w": RotaProt, + "rotaprot-large-uniref90-ft": RotaProt, + "ablang2": AbLang2, + "esm1b_t33_650M_UR50S": ESM1, + **{f"esm1v_t33_650M_UR90S_{i}": ESM1 for i in range(1, 6)}, + "esm2_t12_35M_UR50D": ESM2, + "esm2_t30_150M_UR50D": ESM2, + "esm2_t33_650M_UR50D": ESM2, + "esm2_t36_3B_UR50D": ESM2, + "esm2_t6_8M_UR50D": ESM2, + "esmc-300m": ESMC, + "esmc-600m": ESMC, + "esmc-6b": ESMC, + "prott5-xl": ProtT5, + "alphafold2": AlphaFold2, + "boltz-1": Boltz1, + "boltz-1x": Boltz1, + "boltz-2": Boltz2, + "esmfold": ESMFold, + "esmfold2": ESMFold2, + "esmfold2-fast": ESMFold2, + "minifold": MiniFold, + "opendde": OpenDDE, + "opendde-abag": OpenDDE, + "protenix": Protenix, + "protenix-v2": ProtenixV2, + "rosettafold-3": RosettaFold3, + "bioemu-v1-1": BioEmu, + "alphaflow-md-base-v1": AlphaFlow, + "alphaflow-md-distilled-v1": AlphaFlow, + "esmflow-md-base-v1": ESMFlow, + "esmflow-md-distilled-v1": ESMFlow, +} + +MODEL_ACCESSORS = [ + ("rfdiffusion", "rfdiffusion"), + ("proteinmpnn", "proteinmpnn"), + ("solublempnn", "solublempnn"), + ("boltzgen", "boltzgen"), + ("esmif1", "esm-if1"), + ("poet2", "poet-2"), + ("poet", "poet"), + ("prot_seq", "prot-seq"), + ("rotaprot_large_uniref50w", "rotaprot-large-uniref50w"), + ("rotaprot_large_uniref90_ft", "rotaprot-large-uniref90-ft"), + ("ablang2", "ablang2"), + ("esm1b_t33_650M_UR50S", "esm1b_t33_650M_UR50S"), + ("esm1v_t33_650M_UR90S_1", "esm1v_t33_650M_UR90S_1"), + ("esm1v_t33_650M_UR90S_2", "esm1v_t33_650M_UR90S_2"), + ("esm1v_t33_650M_UR90S_3", "esm1v_t33_650M_UR90S_3"), + ("esm1v_t33_650M_UR90S_4", "esm1v_t33_650M_UR90S_4"), + ("esm1v_t33_650M_UR90S_5", "esm1v_t33_650M_UR90S_5"), + ("esm2_t12_35M_UR50D", "esm2_t12_35M_UR50D"), + ("esm2_t30_150M_UR50D", "esm2_t30_150M_UR50D"), + ("esm2_t33_650M_UR50D", "esm2_t33_650M_UR50D"), + ("esm2_t36_3B_UR50D", "esm2_t36_3B_UR50D"), + ("esm2_t6_8M_UR50D", "esm2_t6_8M_UR50D"), + ("esmc_300m", "esmc-300m"), + ("esmc_600m", "esmc-600m"), + ("esmc_6b", "esmc-6b"), + ("prott5_xl", "prott5-xl"), + ("alphafold2", "alphafold2"), + ("boltz_1", "boltz-1"), + ("boltz_1x", "boltz-1x"), + ("boltz_2", "boltz-2"), + ("esmfold", "esmfold"), + ("esmfold2", "esmfold2"), + ("esmfold2_fast", "esmfold2-fast"), + ("minifold", "minifold"), + ("opendde", "opendde"), + ("opendde_abag", "opendde-abag"), + ("protenix", "protenix"), + ("protenix_v2", "protenix-v2"), + ("rosettafold_3", "rosettafold-3"), + ("bioemu_v1_1", "bioemu-v1-1"), + ("alphaflow_md_base_v1", "alphaflow-md-base-v1"), + ("alphaflow_md_distilled_v1", "alphaflow-md-distilled-v1"), + ("esmflow_md_base_v1", "esmflow-md-base-v1"), + ("esmflow_md_distilled_v1", "esmflow-md-distilled-v1"), +] + + +@pytest.mark.parametrize("attr,model_id", MODEL_ACCESSORS) +def test_static_accessor_is_a_lazy_handle(mock_session, attr, model_id): + api = ModelsAPI(mock_session) + + handle = getattr(api, attr) + + assert type(handle) is HANDLES[model_id] + assert handle.id == model_id + mock_session.get.assert_not_called() + + +def test_every_accessor_has_a_model_class(): + assert {model_id for _, model_id in MODEL_ACCESSORS} == HANDLES.keys() + + +@pytest.mark.parametrize("handle", sorted(set(HANDLES.values()), key=str)) +def test_a_model_class_defaults_to_one_of_its_checkpoints(mock_session, handle): + assert HANDLES[handle(mock_session).id] is handle + + +def test_a_model_without_a_default_needs_an_id(mock_session): + with pytest.raises(TypeError, match="Model needs a model_id"): + Model(mock_session) + + +ALIASES = { + "poet_2": "poet2", + "esm_if1": "esmif1", + "esm1b": "esm1b_t33_650M_UR50S", + "esm1v": "esm1v_t33_650M_UR90S_1", + "esm2": "esm2_t33_650M_UR50D", + "af2": "alphafold2", + "rf3": "rosettafold_3", + "boltz1": "boltz_1", + "boltz1x": "boltz_1x", + "boltz2": "boltz_2", + "bioemu": "bioemu_v1_1", + "alphaflow": "alphaflow_md_base_v1", + "esmflow": "esmflow_md_base_v1", +} + + +def test_every_property_is_a_listed_accessor_or_alias(): + properties = { + name for name, value in vars(ModelsAPI).items() if isinstance(value, property) + } + assert properties == {attr for attr, _ in MODEL_ACCESSORS} | ALIASES.keys() + + +def _not_found(session): + session.get.side_effect = HTTPError( + MagicMock(status_code=404, text="Model not found.") + ) + + +@pytest.mark.parametrize("attr,model_id", MODEL_ACCESSORS) +def test_get_model_returns_the_accessors_handle(models_session, attr, model_id): + api = ModelsAPI(models_session.session) + + assert api.get_model(model_id) is getattr(api, attr) + + +def test_a_listed_id_without_an_accessor_is_a_plain_model(models_session): + handle = ModelsAPI(models_session.session).get_model("other-model") + + assert (type(handle), handle.id) == (Model, "other-model") + + +@pytest.mark.parametrize("model_id", ["not-a-model", "esm2"]) +def test_get_model_refuses_an_unlisted_id(mock_session, model_id): + _not_found(mock_session) + + with pytest.raises(ValueError, match=f"model '{model_id}' not found"): + ModelsAPI(mock_session).get_model(model_id) + + +def test_get_model_passes_on_other_card_errors(mock_session): + mock_session.get.side_effect = HTTPError(MagicMock(status_code=500, text="down")) + + with pytest.raises(HTTPError): + ModelsAPI(mock_session).get_model("esmfold") + + +@pytest.mark.parametrize( + ("model_id", "handle"), + [("gp/fit-1", GPModel), ("svd/fit-1", SVDModel), ("umap/fit-1", UMAPModel)], +) +def test_a_fitted_id_is_checked_on_first_use(mock_session, model_id, handle): + _not_found(mock_session) + + assert type(ModelsAPI(mock_session).get_model(model_id)) is handle + mock_session.get.assert_not_called() + + +def test_aliases_resolve_to_canonical_handles(mock_session): + api = ModelsAPI(mock_session) + + for alias, canonical in ALIASES.items(): + assert getattr(api, alias) is getattr(api, canonical) + assert "esm2" in dir(api) + + +def test_an_esm_id_without_an_accessor_is_a_plain_model(models_session): + handle = ModelsAPI(models_session.session).get_model("esm2_t48_15B_UR50D") + + assert type(handle) is Model + + +def test_the_package_exports_no_embeddings_or_fold_classes(): + import openprotein.models + + modules = { + getattr(openprotein.models, name).__module__ + for name in openprotein.models.__all__ + } + assert not any( + module.startswith(("openprotein.embeddings", "openprotein.fold")) + for module in modules + ) diff --git a/tests/models/test_structure_generation.py b/tests/models/test_structure_generation.py new file mode 100644 index 0000000..6b6e0ae --- /dev/null +++ b/tests/models/test_structure_generation.py @@ -0,0 +1,100 @@ +"""Tests for shared structure-generation futures.""" + +from unittest.mock import MagicMock, patch + +import pytest + +from openprotein.jobs import JobStatus +from openprotein.models.structure_generation import ( + BoltzGenFuture, + RFdiffusionFuture, + StructureGenerationFuture, + StructureGenerationJob, +) + + +def _make_job() -> StructureGenerationJob: + return StructureGenerationJob( + job_id="design-job-1", + job_type="/models/design", + status=JobStatus.SUCCESS, + created_date="2026-01-01T00:00:00", + ) + + +def test_structure_generation_future_get_item_uses_result_format(): + """The shared future fetches a replicate and parses it with configured format.""" + session = MagicMock() + session.get.return_value.text = "MOCK_STRUCTURE_TEXT" + future = StructureGenerationFuture( + session=session, job=_make_job(), N=1, result_format="cif" + ) + + with patch( + "openprotein.models.structure_generation.Complex.from_string", + return_value=MagicMock(), + ) as mock_from_string: + future.get_item(0) + + session.get.assert_called_once_with( + "v1/design/design-job-1/results", params={"replicate": 0} + ) + mock_from_string.assert_called_once_with("MOCK_STRUCTURE_TEXT", format="cif") + + +@pytest.mark.parametrize( + ("future_class", "method"), + [(RFdiffusionFuture, "rfdiffusion"), (BoltzGenFuture, "boltzgen")], +) +def test_deprecated_future_aliases_warn_on_construction(future_class, method): + name = future_class.__name__ + with pytest.warns(FutureWarning) as record: + future_class(session=MagicMock(), job=_make_job(), N=1, result_format="pdb") + expected = ( + f"`openprotein.models.{name}` is deprecated since 0.18.0 and will be " + f"removed in 0.19.0. Use `session.models.{method}.generate(...)` " + "(returns `openprotein.jobs.StructureDesignFuture`)." + ) + assert [str(w.message) for w in record] == [expected] + assert record[0].filename == __file__ + + +@pytest.mark.parametrize("model", ["rfdiffusion", "boltzgen"]) +def test_a_design_query_with_a_length_range_is_refused_before_any_upload( + models_session, model +): + """A design query needs a fixed length, so a length range is refused up front.""" + from openprotein.models import ModelsAPI + from openprotein.molecules import Protein + + models = ModelsAPI(models_session.session) + + with pytest.raises(ValueError, match=r"length range.*Protein\.from_expr\(15\)"): + getattr(models, model).generate(Protein.from_expr("10..20")) + + assert models_session.queries == [] + assert models_session.submissions == [] + + +def test_a_model_without_generate_is_refused_with_its_missing_method(models_session): + """A model whose card lacks `generate` raises the missing-method error.""" + from openprotein.models import ModelsAPI + from openprotein.molecules import Protein + from tests.models.support import card + + listing = card("rfdiffusion") + listing["methods"] = [ + m for m in listing["methods"] if m["path"] != "generate/structures" + ] + models_session.get_routes["v1/models/rfdiffusion"] = listing + models = ModelsAPI(models_session.session) + + with pytest.raises(ValueError, match="has no generate"): + models.rfdiffusion.generate(Protein.from_expr(15)) + + assert models_session.queries == [] + assert models_session.submissions == [] + assert not any( + call.args[0].endswith("/params") + for call in models_session.session.get.call_args_list + ) diff --git a/tests/models/test_structure_prediction_model.py b/tests/models/test_structure_prediction_model.py new file mode 100644 index 0000000..5a822bc --- /dev/null +++ b/tests/models/test_structure_prediction_model.py @@ -0,0 +1,449 @@ +"""Structure prediction handles shape inputs into complexes and run each model's checks.""" + +from datetime import datetime, timezone +from unittest.mock import MagicMock, patch + +import numpy as np +import pytest + +from openprotein.align import AlignAPI, MSAFuture +from openprotein.data.msa import MSA, MSAMetadata +from openprotein.models import ModelsAPI, OpenDDE, StructurePredictionModel +from openprotein.molecules import DNA, Complex, Ligand, Protein, Template +from tests.models.support import PARAMS, card, created_query + +FOLD_IDS = [ + "esmfold", + "minifold", + "alphafold2", + "rosettafold-3", + "boltz-1", + "boltz-1x", + "boltz-2", + "protenix", + "protenix-v2", + "esmfold2", + "esmfold2-fast", + "opendde", + "opendde-abag", +] +PROTEIN = {"protein": {"id": "A", "sequence": "MKT"}} +PROTEIN_NULL_MSA = {"protein": {"id": "A", "sequence": "MKT", "msa_id": None}} + + +@pytest.fixture +def models(models_session) -> ModelsAPI: + return ModelsAPI(models_session.session) + + +def _ligand_complex() -> Complex: + return Complex({"A": Protein(sequence="MKT"), "L": Ligand(ccd="ATP")}) + + +@pytest.mark.parametrize("alias", ["af2", "rf3", "boltz1", "boltz1x", "boltz2"]) +def test_short_aliases_resolve_to_fold_handles(models, alias): + handle = getattr(models, alias) + + assert isinstance(handle, StructurePredictionModel) + assert handle.id in FOLD_IDS + + +def test_every_fold_id_resolves_to_a_structure_prediction_handle(models): + for model_id in FOLD_IDS: + assert isinstance(models.get_model(model_id), StructurePredictionModel) + + +@pytest.mark.parametrize( + "model_id, chain", + [ + ("esmfold", PROTEIN), + ("minifold", PROTEIN), + ("esmfold2-fast", PROTEIN), + ("alphafold2", PROTEIN_NULL_MSA), + ("boltz-2", PROTEIN_NULL_MSA), + ("esmfold2", PROTEIN_NULL_MSA), + ], +) +def test_a_sequence_folds_as_one_complex(models, models_session, model_id, chain): + models.get_model(model_id).fold("MKT") + + path, body = models_session.submitted + assert path == f"v1/models/{model_id}/batch/structures" + assert body["complexes"] == [[chain]] + + +def test_a_later_complex_with_a_chain_the_first_lacks_folds(models, models_session): + models.boltz_2.fold(["MKT", "MKT:AC"]) + + _, body = models_session.submitted + assert [len(complex) for complex in body["complexes"]] == [1, 2] + + +def test_folding_an_msa_future_reads_its_seed_once(models, models_session, monkeypatch): + align = AlignAPI(models_session.session) + get_seed = MagicMock(return_value="MKT:AC") + monkeypatch.setattr(align, "get_seed", get_seed) + models_session.session.align = align + msa = MagicMock(spec=MSAFuture) + msa.job = MagicMock(job_id=MSA_ID) + msa.id = MSA_ID + + models.boltz_2.fold(msa) + + get_seed.assert_called_once_with(job_id=MSA_ID) + _, body = models_session.submitted + assert len(body["complexes"][0]) == 2 + assert all(chain["protein"]["msa_id"] == MSA_ID for chain in body["complexes"][0]) + + +def test_serialized_complexes_pass_through(models, models_session): + complexes = [[PROTEIN]] + + models.esmfold.fold(complexes, num_recycles=2) + + assert models_session.submitted[1] == {"complexes": complexes, "num_recycles": 2} + + +def test_an_msa_future_folds_its_seed_as_one_complex(models, models_session): + msa = MagicMock(spec=MSAFuture) + complex = Complex({"A": Protein(sequence="MKT"), "B": Protein(sequence="AC")}) + serialized = [[PROTEIN_NULL_MSA]] + + with ( + patch( + "openprotein.models.folding.base.msa_future_to_complex", + return_value=complex, + ) as to_complex, + patch( + "openprotein.models.folding.base.serialize_input", + return_value=serialized, + ) as serialize, + ): + models.esmfold2.fold(msa, random_seed=1) + + to_complex.assert_called_once_with(models_session.session, msa) + serialize.assert_called_once_with(models_session.session, [complex], True) + assert models_session.submitted[1]["complexes"] == serialized + + +@pytest.mark.parametrize("complexes", [3, [3], [{"protein": {}}], None]) +def test_a_wrong_input_type_raises_before_any_request( + models, models_session, complexes +): + with pytest.raises(TypeError, match="complexes must be"): + models.esmfold.fold(complexes) + models_session.session.post.assert_not_called() + models_session.session.get.assert_not_called() + + +def test_no_complexes_raise_before_any_request(models, models_session): + with pytest.raises(ValueError, match="at least one complex"): + models.esmfold.fold([]) + models_session.session.get.assert_not_called() + + +@pytest.mark.parametrize( + "model_id, kept", + [("esmfold", ["A"]), ("alphafold2", ["A"]), ("rosettafold-3", ["A", "L"])], +) +def test_unsupported_chains_are_left_out_with_a_warning( + models, models_session, model_id, kept +): + complex = Complex( + { + "A": Protein(sequence="MKT"), + "D": DNA(sequence="ACGT"), + "L": Ligand(ccd="ATP"), + } + ) + complex.get_protein("A").msa = Protein.single_sequence_mode + + with pytest.warns(UserWarning, match="left out"): + models.get_model(model_id).fold(complex) + + chains = models_session.submitted[1]["complexes"][0] + assert [next(iter(c.values()))["id"] for c in chains] == kept + assert list(complex.get_chains()) == ["A", "D", "L"] + + +@pytest.mark.parametrize( + "complex, match", + [ + (Complex({"A": Protein(sequence="M"), "B": Protein(sequence="K")}), "monomers"), + (_ligand_complex(), "only supports proteins"), + ], +) +def test_minifold_folds_protein_monomers_only(models, models_session, complex, match): + with pytest.raises(ValueError, match=match): + models.minifold.fold(complex) + models_session.session.post.assert_not_called() + + +def test_esmfold2_fast_refuses_an_msa(models, models_session): + protein = Protein(sequence="MKT") + protein.msa = "msa-1" + + with pytest.raises(ValueError, match="single-sequence"): + models.esmfold2_fast.fold(protein) + models_session.session.post.assert_not_called() + + +def _single_sequence_ligand_complex() -> Complex: + complex = _ligand_complex() + complex.get_protein("A").msa = Protein.single_sequence_mode + return complex + + +@pytest.mark.parametrize("alias", ["boltz1", "boltz1x"]) +def test_boltz_constraints_are_sent_as_given(models, models_session, alias): + constraints = [ + {"contact": {"token1": ["A", 1], "token2": ["A", 2], "max_distance": 5}} + ] + + getattr(models, alias).fold( + _single_sequence_ligand_complex(), constraints=constraints + ) + + assert models_session.submitted[1]["constraints"] == constraints + + +def test_boltz2_properties_are_sent_as_given(models, models_session): + properties = [{"affinity": {"binder": "A"}}] + + models.boltz2.fold(_single_sequence_ligand_complex(), properties=properties) + + assert models_session.submitted[1]["properties"] == properties + + +def test_boltz2_templates_become_template_queries(models, models_session): + protein = Protein(sequence="ARNDCQ") + protein.msa = Protein.single_sequence_mode + template = Protein(sequence="ARNDCQ") + template = template._set_coordinates( + np.zeros(template.coordinates.shape, dtype=np.float32) + ) + + models.boltz2.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"] + + +def test_shared_template_targets_are_checked_before_upload_or_submission( + models, models_session +): + template = Protein("ARNDCQ") + template = template._set_coordinates( + np.zeros(template.coordinates.shape, dtype=np.float32) + ) + first = Protein("ARNDCQ").set_msa(Protein.single_sequence_mode) + first.templates = [template] + later = Protein("MKT").set_msa(Protein.single_sequence_mode) + + with pytest.raises(ValueError, match="Template maps.*does not exist"): + models.boltz2.fold([Complex({"A": first}), Complex({"B": later})]) + + assert models_session.queries == [] + models_session.session.post.assert_not_called() + + +def test_a_template_mapped_to_chain_a_folds_a_lone_protein(models, models_session): + template = Protein("ARNDCQ") + template = template._set_coordinates( + np.zeros(template.coordinates.shape, dtype=np.float32) + ) + protein = Protein("ARNDCQ").set_msa(Protein.single_sequence_mode) + + models.boltz2.fold(protein, templates=[Template(template, mapping="A")]) + + assert models_session.submitted[1]["templates"] == [ + {"query_id": created_query(1), "chain_id": "A"} + ] + + +@pytest.mark.parametrize("msa", [None, "not-a-uuid"]) +def test_a_refused_fold_uploads_no_template(models, models_session, msa): + template = Protein("ARNDCQ") + template = template._set_coordinates( + np.zeros(template.coordinates.shape, dtype=np.float32) + ) + protein = Protein("ARNDCQ") + protein.msa = msa + + with pytest.raises(ValueError): + models.boltz2.fold(protein, templates=[template]) + + assert models_session.queries == [] + models_session.session.post.assert_not_called() + + +def test_a_model_without_templates_refuses_them(models, models_session): + with pytest.raises(ValueError, match="takes no templates"): + models.esmfold.fold("MKT", templates=[Protein(sequence="MKT")]) + models_session.session.post.assert_not_called() + + +@pytest.mark.parametrize("model_id", FOLD_IDS) +def test_a_fold_sends_no_random_seed_unless_given(models, models_session, model_id): + protein = Protein(sequence="MKT") + protein.msa = Protein.single_sequence_mode + + models.get_model(model_id).fold(protein) + + assert "random_seed" not in models_session.submitted[1] + + +def test_a_fold_leaves_out_chains_its_card_does_not_take(models, models_session): + models_session.get_routes["v1/models/rosettafold-3"] = card("rosettafold-3") | { + "input_types": ["protein"] + } + + with pytest.warns(UserWarning, match="left out"): + models.rf3.fold(_single_sequence_ligand_complex()) + + chains = models_session.submitted[1]["complexes"][0] + assert [next(iter(c.values()))["id"] for c in chains] == ["A"] + + +def test_a_card_that_is_not_multichain_folds_one_protein(models, models_session): + models_session.get_routes["v1/models/esmfold"] = card("esmfold") | { + "multichain": False + } + complex = Complex({"A": Protein(sequence="M"), "B": Protein(sequence="K")}) + + with pytest.raises(ValueError, match="monomers"): + models.esmfold.fold(complex) + models_session.session.post.assert_not_called() + + +def test_a_model_whose_params_name_no_msa_refuses_one(models, models_session): + models_session.get_routes["v1/models/alphafold2/batch/structures/params"] = PARAMS[ + "methods" + ]["esmfold/batch/structures"]["params"] + protein = Protein(sequence="MKT") + protein.msa = "msa-1" + + with pytest.raises(ValueError, match="single-sequence"): + models.alphafold2.fold(protein) + models_session.session.post.assert_not_called() + + models.alphafold2.fold("MKT") + + assert models_session.submitted[1]["complexes"] == [[PROTEIN]] + + +def test_a_model_whose_params_have_no_templates_refuses_them(models, models_session): + models_session.get_routes["v1/models/boltz-2/batch/structures/params"] = PARAMS[ + "methods" + ]["boltz-1/batch/structures"]["params"] + + with pytest.raises(ValueError, match="takes no templates"): + models.boltz2.fold("MKT", templates=[Protein(sequence="MKT")]) + models_session.session.post.assert_not_called() + + +def test_a_handle_reads_its_card_and_params_once(models, models_session): + models.esmfold.fold("MKT") + models.esmfold.fold("MKV") + + reads = sorted(call.args[0] for call in models_session.session.get.call_args_list) + assert reads == [ + "v1/models/esmfold", + "v1/models/esmfold/batch/structures/params", + ] + + +MSA_ID = "e0b1c3d4-0000-4000-8000-000000000001" +OPENDDE = [("opendde", "opendde"), ("opendde_abag", "opendde-abag")] + + +@pytest.mark.parametrize(("attr", "model_id"), OPENDDE) +def test_opendde_accessors_are_annotated_opendde_handles(attr, model_id): + prop = vars(ModelsAPI)[attr] + assert isinstance(prop, property) + assert prop.fget.__annotations__["return"] in (OpenDDE, "OpenDDE") + + +@pytest.mark.parametrize(("attr", "model_id"), OPENDDE) +@pytest.mark.parametrize("kind", ["sequence", "ligand", "msa"]) +def test_opendde_folds_send_bodies_its_params_accept( + models, models_session, monkeypatch, attr, model_id, kind +): + complexes = "MKT" + if kind == "ligand": + complexes = _ligand_complex() + complexes.get_protein("A").msa = Protein.single_sequence_mode + elif kind == "msa": + align = AlignAPI(models_session.session) + monkeypatch.setattr(align, "get_seed", lambda job_id: "MKT") + models_session.session.align = align + complexes = Protein(sequence="MKT") + complexes.msa = MSA_ID + + getattr(models, attr).fold(complexes) + + path, body = models_session.submitted + assert path == f"v1/models/{model_id}/batch/structures" + if kind == "ligand": + assert body["complexes"][0][1]["ligand"]["ccd"] == "ATP" + elif kind == "msa": + assert body["complexes"][0][0]["protein"]["msa_id"] == MSA_ID + + +def _stored_msa(session) -> MSA: + now = datetime.now(timezone.utc) + return MSA(session, MSAMetadata(msa_id=MSA_ID, created_at=now, updated_at=now)) + + +@pytest.mark.parametrize("model_id", ["boltz-2", "protenix", "protenix-v2"]) +def test_a_colon_string_folds_as_one_multichain_complex_on_a_template_model( + models, models_session, model_id +): + models.get_model(model_id).fold("MKT:AC") + + _, body = models_session.submitted + assert [ + [(chain["protein"]["id"], chain["protein"]["sequence"]) for chain in complex] + for complex in body["complexes"] + ] == [[("A", "MKT"), ("B", "AC")]] + + +def test_an_attached_stored_msa_sends_its_id(models, models_session, monkeypatch): + align = AlignAPI(models_session.session) + monkeypatch.setattr(align, "get_seed", lambda job_id: "MKT") + models_session.session.align = align + protein = Protein(sequence="MKT") + protein.msa = _stored_msa(models_session.session) + + models.boltz2.fold(protein) + + assert models_session.submitted[1]["complexes"] == [ + [{"protein": {"id": "A", "sequence": "MKT", "msa_id": MSA_ID}}] + ] + + +def test_a_single_sequence_model_refuses_an_attached_stored_msa(models, models_session): + protein = Protein(sequence="MKT") + protein.msa = _stored_msa(models_session.session) + + with pytest.raises(ValueError, match="single-sequence"): + models.esmfold.fold(protein) + models_session.session.post.assert_not_called() + + +def test_an_msa_of_another_type_is_refused(models, models_session): + protein = Protein(sequence="MKT") + protein.msa = 42 # ty: ignore[invalid-assignment] + + with pytest.raises(TypeError, match="`.msa` must be"): + models.boltz2.fold(protein) + models_session.session.post.assert_not_called() + + +def test_a_complex_with_no_chain_the_model_folds_is_refused(models, models_session): + with ( + pytest.warns(UserWarning, match="left out"), + pytest.raises(ValueError, match="complex 0 has no chain esmfold can fold"), + ): + models.esmfold.fold(Complex({"L": Ligand(ccd="ATP")})) + models_session.session.post.assert_not_called() diff --git a/tests/models/test_task_dispatch.py b/tests/models/test_task_dispatch.py new file mode 100644 index 0000000..d78b031 --- /dev/null +++ b/tests/models/test_task_dispatch.py @@ -0,0 +1,281 @@ +import logging +from typing import Literal + +import pytest + +from openprotein.embeddings.future import EmbeddingsResultFuture +from openprotein.embeddings.schemas import EmbeddingsJob +from openprotein.jobs import Future, Job, JobStatus, _dispatch +from openprotein.jobs import futures as results +from openprotein.jobs.futures import ( + GPFitFuture, + SVDFitFuture, + UMAPFitFuture, +) +from openprotein.models import _api +from openprotein.models.model import Model +from openprotein.models.schemas import ModelMetadata +from tests.models.support import PARAMS + +CASES = [ + ("batch/embeddings", results.EmbeddingFuture), + ("batch/logits", results.LogitsFuture), + ("batch/attn", results.AttentionFuture), + ("batch/loglikelihood", results.LogLikelihoodFuture), + ("single-site/scores", results.SingleSiteScoreFuture), + ("indel/scores", results.IndelScoreFuture), + ("generate/sequences", results.SequenceGenerationFuture), + ("generate/structures", results.StructureDesignFuture), + ("batch/structures", results.StructurePredictionFuture), + ("batch/predictions", results.PredictionFuture), + ("single-site/predictions", results.SingleSitePredictionFuture), +] + + +def task_job(path, *, provider="esm2", status="PENDING"): + return Job.model_validate( + { + "job_id": "e0b1c3d4-0000-4000-8000-00000000000a", + "job_type": f"/models/{provider}/{path}", + "status": status, + "created_date": "2026-10-21T08:00:00Z", + } + ) + + +def test_catalogued_methods_have_specialised_primary_outputs(mock_session): + for key, method in PARAMS["methods"].items(): + _, first, last = key.rsplit("/", 2) + path = f"{first}/{last}" + future = Future.create(mock_session, job=task_job(path)) + + assert type(future) is not Future, key + assert future._primary_output == method["outputs"][0], key + + +@pytest.mark.parametrize(("path", "expected"), CASES) +@pytest.mark.parametrize("status", ["PENDING", "RUNNING", "SUCCESS"]) +def test_identified_tasks_select_their_future(mock_session, path, expected, status): + future = Future.create(mock_session, job=task_job(path, status=status)) + assert type(future) is expected + mock_session.get.assert_not_called() + + +def test_selection_uses_the_method(mock_session): + future = Future.create( + mock_session, + job=task_job("batch/logits", provider="rfdiffusion"), + ) + assert type(future) is results.LogitsFuture + + +def test_unknown_models_methods_keep_generic_access(mock_session): + future = Future.create(mock_session, job=task_job("batch/new-output")) + assert type(future) is Future + assert future.status is JobStatus.PENDING + + +def test_unidentified_records_keep_tracking(mock_session): + job = Job.create( + { + "job_id": "e0b1c3d4-0000-4000-8000-00000000000a", + "job_type": "/future/new-task", + "status": "PENDING", + "created_date": "2026-10-21T08:00:00Z", + } + ) + future = Future.create(mock_session, job=job) + assert type(future).__name__ == "UnknownJobFuture" + with pytest.raises(NotImplementedError): + future.get() + + +def test_typed_embedding_records_keep_their_compatibility_future(mock_session): + job = EmbeddingsJob( + job_id="e0b1c3d4-0000-4000-8000-00000000000a", + status="PENDING", + created_date="2026-10-21T08:00:00Z", + ) + + future = EmbeddingsResultFuture.create(mock_session, job=job, sequences=["MKT"]) + + assert type(future) is EmbeddingsResultFuture + assert future.sequences == [b"MKT"] + mock_session.get.assert_not_called() + + +def test_undeclared_subclasses_do_not_claim_the_parent_schema(mock_session): + class DerivedEmbeddingFuture(EmbeddingsResultFuture): + pass + + assert DerivedEmbeddingFuture.__annotations__.get("job") is None + job = EmbeddingsJob( + job_id="e0b1c3d4-0000-4000-8000-00000000000a", + status="PENDING", + created_date="2026-10-21T08:00:00Z", + ) + future = Future.create(mock_session, job=job, sequences=["MKT"]) + assert type(future) is EmbeddingsResultFuture + + +def test_search_records_load_as_plain_futures(mock_session): + job = Job.create( + { + "job_id": "e0b1c3d4-0000-4000-8000-00000000000a", + "job_type": "/search/mmseqs2", + "status": "PENDING", + "created_date": "2026-10-21T08:00:00Z", + } + ) + assert type(job) is Job + assert type(Future.create(mock_session, job=job)) is Future + mock_session.get.assert_not_called() + + +def test_job_type_alone_identifies_the_model_and_method(mock_session): + job = task_job("batch/embeddings") + assert type(job) is Job + + future = Future.create(mock_session, job=job) + + assert isinstance(future, results.EmbeddingFuture) + future._require_outputs() + assert (future._model_id, future._path) == ("esm2", "batch/embeddings") + mock_session.get.assert_not_called() + + +def test_a_job_payload_naming_a_provider_does_not_identify_the_method(mock_session): + job = Job.model_validate( + { + "job_id": "e0b1c3d4-0000-4000-8000-00000000000a", + "job_type": "/models", + "status": "SUCCESS", + "created_date": "2026-10-21T08:00:00Z", + "provider_id": "esm2", + "path": "/batch/embeddings", + } + ) + + assert _dispatch.identity(job) == (None, None) + assert not _dispatch.recognizes(job) + assert type(Future.create(mock_session, job=job)) is Future + + +def test_plain_job_encoded_only_in_job_type_loads_its_specialised_future( + mock_session, +): + job = Job( + job_id="e0b1c3d4-0000-4000-8000-00000000000a", + job_type="/models/gp/p-1/batch/predictions", + status=JobStatus.SUCCESS, + created_date="2026-10-21T08:00:00Z", + ) + assert type(job) is Job + + future = Future.create(mock_session, job=job) + + assert type(future) is results.PredictionFuture + assert future._model_id == "gp/p-1" + assert future._path == "batch/predictions" + future._require_outputs() + mock_session.get.assert_not_called() + mock_session.post.assert_not_called() + + +def test_duplicate_future_owners_select_the_first_in_name_order(mock_session, caplog): + class DuplicateOwnerJob(Job): + job_type: Literal["/test/duplicate-owner"] # type: ignore[assignment] + + class BOwner(Future): + job: DuplicateOwnerJob + + def _get(self, verbose=False, **kwargs): + return None + + class AOwner(Future): + job: DuplicateOwnerJob + + def _get(self, verbose=False, **kwargs): + return None + + with caplog.at_level(logging.WARNING, logger="openprotein.jobs.futures"): + future = Future.create( + mock_session, + job={ + "job_id": "e0b1c3d4-0000-4000-8000-00000000000a", + "job_type": "/test/duplicate-owner", + "status": "PENDING", + "created_date": "2026-10-21T08:00:00Z", + }, + ) + + assert type(future) is AOwner + assert any( + "multiple future owners" in record.getMessage() + and "BOwner" in record.getMessage() + for record in caplog.records + ) + + +@pytest.mark.parametrize(("path", "expected"), CASES) +def test_model_submission_uses_task_dispatch(mock_session, monkeypatch, path, expected): + metadata = ModelMetadata.model_validate( + { + "model_id": "example", + "description": {"summary": "Example"}, + "dimension": 1, + "max_sequence_length": 100, + "methods": [{"path": path, "outputs": [expected._primary_output]}], + } + ) + monkeypatch.setattr( + _api, + "run_method", + lambda session, model_id, method, params: task_job(method, provider=model_id), + ) + + future = Model(mock_session, "example", metadata)._run("run", path) + + assert type(future) is expected + assert future._submission.model_id == "example" + assert future._submission.path == path + + +@pytest.mark.parametrize( + ("family", "future_type"), + [ + ("gp", GPFitFuture), + ("svd", SVDFitFuture), + ("umap", UMAPFitFuture), + ], +) +def test_identified_fit_jobs_keep_their_fit_future(mock_session, family, future_type): + future = Future.create(mock_session, job=task_job("fit", provider=family)) + assert type(future) is future_type + + +@pytest.mark.parametrize( + ("future_type", "family"), [(SVDFitFuture, "svd"), (UMAPFitFuture, "umap")] +) +def test_pending_fit_projection_is_an_embedding_future( + mock_session, monkeypatch, future_type, family +): + fit = future_type(mock_session, task_job("fit", provider=family)) + sent = [] + + def run(session, model_id, path, params): + sent.append((model_id, path, params)) + return task_job(path, provider=family) + + monkeypatch.setattr(_api, "run_method", run) + + transformed = fit.transform(["MKT"]) + embedded = fit.embed(["MKT"]) + + assert type(transformed) is results.EmbeddingFuture + assert type(embedded) is results.EmbeddingFuture + assert sent == [ + (f"{family}/{fit.id}", "batch/embeddings", {"sequences": ["MKT"]}), + (f"{family}/{fit.id}", "batch/embeddings", {"sequences": ["MKT"]}), + ] + assert fit.status is JobStatus.PENDING diff --git a/tests/models/test_task_futures.py b/tests/models/test_task_futures.py new file mode 100644 index 0000000..58fa93d --- /dev/null +++ b/tests/models/test_task_futures.py @@ -0,0 +1,405 @@ +import math +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest + +from openprotein.errors import APIError +from openprotein.jobs import futures as results +from openprotein.jobs.futures import _ResultFuture +from openprotein.models import _inputs +from openprotein.models.structure_generation import ( + BoltzGenFuture, + RFdiffusionFuture, + StructureGenerationFuture, + StructureGenerationJob, +) +from openprotein.molecules import Complex, Structure + + +class _TaggedFuture(_ResultFuture): + _primary_output = "structures" + + def _convert_output(self, output, position, value): + return output, position, value + + +_READERS = [ + lambda f: f.get()[0], + lambda f: f.wait(interval=0)[0], + lambda f: f.get_item(0), + lambda f: f[0], + lambda f: next(f.stream()), + lambda f: next(iter(f)), + lambda f: f.unit(0).get(), +] + + +@pytest.mark.parametrize("read", _READERS) +def test_positional_readers_apply_the_result_conversion(task_outputs, read): + future, _ = task_outputs(_TaggedFuture, values={"structures": ["value"]}) + assert read(future) == ("structures", 0, "value") + + +def test_task_repr_names_the_concrete_type(task_outputs): + future, _ = task_outputs(_TaggedFuture) + assert repr(future).startswith("_TaggedFuture(") + + +@pytest.mark.parametrize( + ("future_type", "path", "output"), + [ + (results.EmbeddingFuture, "batch/embeddings", "embeddings"), + (results.LogitsFuture, "batch/logits", "logits"), + (results.AttentionFuture, "batch/attn", "attn"), + ], +) +def test_array_tasks_read_their_primary_output(task_outputs, future_type, path, output): + array = np.ones((2, 3)) + future, _ = task_outputs( + future_type, + path=path, + provider="esm2", + values={"auxiliary": ["other"], output: [array]}, + ) + + assert future.get_item(0) is array + assert future.get()[0] is array + assert future.get(output="auxiliary") == ["other"] + + +_DATA = Path(__file__).parents[1] / "data" + + +@pytest.mark.parametrize("read", _READERS) +@pytest.mark.parametrize( + ("structure_file", "chains"), + [ + ("test_protein.cif", ["A"]), + ("boltzgen_entity_one_letter_missing_residues.cif", ["A", "B"]), + ], +) +def test_design_accessors_return_complexes(task_outputs, read, structure_file, chains): + future, _ = task_outputs( + results.StructureDesignFuture, + values={"structures": [(_DATA / structure_file).read_text()]}, + ) + value = read(future) + assert isinstance(value, Complex) + assert sorted(value.get_chains()) == chains + + +def test_design_returns_decoded_complexes_as_is(task_outputs): + _, values = task_outputs(results.StructureDesignFuture) + decoded = Complex.from_string(values["structures"][0], format="cif", verbose=False) + future, _ = task_outputs( + results.StructureDesignFuture, values={"structures": [decoded]} + ) + assert future.get_item(0) is decoded + + +def test_design_rejects_a_complex_without_chains(task_outputs): + future, _ = task_outputs( + results.StructureDesignFuture, values={"structures": [Complex({})]} + ) + with pytest.raises( + ValueError, + match=f"job {future.id} position 0: .*contains no molecular chains", + ): + future.get_item(0) + + +def test_prediction_returns_decoded_structures_as_is(task_outputs): + _, values = task_outputs(results.StructureDesignFuture) + decoded = Structure( + [Complex.from_string(values["structures"][0], format="cif", verbose=False)] + ) + future, _ = task_outputs( + results.StructurePredictionFuture, + path="batch/structures", + provider="boltz-2", + values={"structures": [decoded]}, + ) + assert future.get_item(0) is decoded + + +def test_structure_auxiliary_outputs_keep_their_values(task_outputs): + confidence = np.ones((2, 2)) + score = b"ptm,iptm\n0.8,0.7\n" + structure = (Path(__file__).parents[1] / "data" / "test_protein.cif").read_text() + future, _ = task_outputs( + results.StructureDesignFuture, + values={ + "structures": [structure], + "confidence": [confidence], + "score": [score], + }, + ) + + assert future.get_item(0, output="confidence") is confidence + assert future.unit(0, output="confidence").get() is confidence + assert list(future.stream("score")) == [score] + + +def test_prediction_preserves_every_model(task_outputs): + _, values = task_outputs(results.StructureDesignFuture) + first = Complex.from_string(values["structures"][0], format="cif", verbose=False) + text = Structure([first, first.copy()]).to_string(format="cif") + future, _ = task_outputs( + results.StructurePredictionFuture, + path="batch/structures", + provider="boltz-2", + values={"structures": [text]}, + ) + + value = future.get_item(0) + + assert isinstance(value, Structure) + assert len(value) == 2 + assert all(isinstance(value[i], Complex) for i in range(2)) + + +def test_design_rejects_multiple_models_in_one_position(task_outputs): + future, values = task_outputs(results.StructureDesignFuture) + first = Complex.from_string(values["structures"][0], format="cif", verbose=False) + values["structures"][0] = Structure([first, first.copy()]).to_string(format="cif") + + with pytest.raises(ValueError, match=f"job {future.id} position 0: .*one complex"): + future.get_item(0) + + +def test_structure_type_errors_are_not_returned_as_results(task_outputs): + future, _ = task_outputs( + results.StructureDesignFuture, + values={"structures": [{"unexpected": "value"}]}, + ) + + with pytest.raises( + TypeError, match=f"job {future.id} position 0: structure output" + ): + future.get_item(0) + with pytest.raises(APIError) as error: + future.get() + assert isinstance(error.value.__cause__, TypeError) + + +def test_malformed_structures_report_the_parser_failure(task_outputs): + future, _ = task_outputs( + results.StructureDesignFuture, + values={"structures": ["not a cif document"]}, + ) + + with pytest.raises( + (ValueError, RuntimeError), match=f"job {future.id} position 0: " + ): + future.get_item(0) + with pytest.raises(APIError) as error: + future.get() + assert isinstance(error.value.__cause__, (ValueError, RuntimeError)) + + +def test_design_type_error_names_the_specialised_future(): + with pytest.raises(TypeError, match="StructureDesignFuture"): + _inputs._check_design("job-id") + + +def test_equal_unit_identities_keep_distinct_positions(task_outputs): + future, _ = task_outputs( + results.SequenceGenerationFuture, + path="generate/sequences", + values={"sequences": ["MKT", "MKT"]}, + ) + + assert future.get() == ["MKT", "MKT"] + assert [unit.position for unit in future.units] == [0, 1] + assert [unit.get() for unit in future.units] == ["MKT", "MKT"] + + +@pytest.mark.parametrize( + ("future_type", "method"), + [ + (RFdiffusionFuture, "session.models.rfdiffusion.generate"), + (BoltzGenFuture, "session.models.boltzgen.generate"), + ], +) +def test_design_aliases_name_the_current_submission_method( + mock_session, future_type, method +): + job = StructureGenerationJob( + job_id="design-1", + job_type="/models/design", + status="SUCCESS", + created_date="2026-10-21T08:00:00Z", + ) + mock_session.get.return_value.text = ( + Path(__file__).parents[1] / "data" / "test_protein.cif" + ).read_text() + + with pytest.warns(FutureWarning) as warnings: + future = future_type(mock_session, job, N=1, result_format="cif", max_workers=0) + + message = str(warnings[0].message) + assert method in message + assert "StructureDesignFuture" in message + assert "0.18.0" in message + assert "0.19.0" in message + assert isinstance(future, StructureGenerationFuture) + assert not isinstance(future, results.StructureDesignFuture) + assert isinstance(future.get_item(0), Complex) + mock_session.get.assert_called_once_with( + "v1/design/design-1/results", params={"replicate": 0} + ) + + +def test_result_futures_iterate_through_their_stream(task_outputs, monkeypatch): + sentinel = iter(["streamed"]) + monkeypatch.setattr( + results.EmbeddingFuture, "stream", lambda self, *args, **kwargs: sentinel + ) + future, _ = task_outputs(results.EmbeddingFuture) + + assert iter(future) is sentinel + + +def test_prediction_conversion_errors_name_the_job_and_position(task_outputs): + future, _ = task_outputs( + results.StructurePredictionFuture, + path="batch/structures", + provider="boltz-2", + values={"structures": [{"unexpected": "value"}]}, + ) + + with pytest.raises( + TypeError, match=f"job {future.id} position 0: structure output" + ): + future.get_item(0) + + +@pytest.mark.parametrize("output", ["score", "metrics"]) +@pytest.mark.parametrize("stored", [bytes, str]) +def test_prediction_reads_csv_outputs_as_one_table_per_position( + task_outputs, output, stored +): + text = "example_id,ptm,batch_idx\nbatch_0,0.8,0\nbatch_0,0.7,1\n" + value = text.encode() if stored is bytes else text + future, _ = task_outputs( + results.StructurePredictionFuture, + path="batch/structures", + provider="rosettafold-3", + values={"structures": ["unused"], output: [value]}, + ) + expected = pd.DataFrame( + {"example_id": ["batch_0", "batch_0"], "ptm": [0.8, 0.7], "batch_idx": [0, 1]} + ) + + for table in ( + future.get_item(0, output=output), + future.get(output=output)[0], + future.unit(0, output=output).get(), + next(future.stream(output)), + ): + pd.testing.assert_frame_equal(table, expected) + + +def test_prediction_keeps_decoded_table_outputs(task_outputs): + decoded = {"ptm": [0.8, 0.7]} + future, _ = task_outputs( + results.StructurePredictionFuture, + path="batch/structures", + provider="rosettafold-3", + values={"structures": ["unused"], "metrics": [decoded]}, + ) + + assert future.get_item(0, output="metrics") is decoded + + +def test_prediction_table_errors_name_the_job_and_position(task_outputs): + future, _ = task_outputs( + results.StructurePredictionFuture, + path="batch/structures", + provider="rosettafold-3", + values={"structures": ["unused"], "score": [b""]}, + ) + + with pytest.raises(ValueError, match=f"job {future.id} position 0: "): + future.get_item(0, output="score") + + +NAN = float("nan") + + +@pytest.mark.parametrize( + "future_type, path, output, values, expected", + [ + ( + results.LogLikelihoodFuture, + "batch/loglikelihood", + None, + {"loglikelihood": ["-inf", 1.5]}, + [-math.inf, 1.5], + ), + ( + results.SingleSiteScoreFuture, + "single-site/scores", + None, + {"score": ["nan", ["inf", 0.5]]}, + [NAN, [math.inf, 0.5]], + ), + ( + results.IndelScoreFuture, + "indel/scores", + None, + {"score": [0.0, "-inf"]}, + [0.0, -math.inf], + ), + ( + results.SequenceGenerationFuture, + "generate/sequences", + "loglikelihood", + {"sequences": ["MKT", "MKV"], "loglikelihood": ["-inf", -2.0]}, + [-math.inf, -2.0], + ), + ( + results.PredictionFuture, + "predict", + None, + {"predictions": [{"y": {"mean": "nan", "variance": 1.0}}]}, + [{"y": {"mean": NAN, "variance": 1.0}}], + ), + ( + results.SingleSitePredictionFuture, + "single-site/predict", + None, + {"predictions": [{"y": {"mean": 0.1, "variance": "inf"}}]}, + [{"y": {"mean": 0.1, "variance": math.inf}}], + ), + ], + ids=[ + "loglikelihood", + "single site", + "indel", + "generation", + "prediction", + "single-site prediction", + ], +) +def test_spelt_out_non_finite_numbers_read_as_floats( + task_outputs, future_type, path, output, values, expected +): + future, _ = task_outputs(future_type, path=path, provider="m", values=values) + + # repr tells the float nan from the string 'nan' + assert repr(future.get(output=output)) == repr(expected) + assert repr(future.get_item(0, output=output)) == repr(expected[0]) + + +def test_a_generation_keeps_its_sequences_as_strings(task_outputs): + future, _ = task_outputs( + results.SequenceGenerationFuture, + path="generate/sequences", + provider="m", + values={"sequences": ["nan", "MKT"], "loglikelihood": [1.0, 2.0]}, + ) + + assert future.get() == ["nan", "MKT"] diff --git a/tests/models/test_typecheck_coverage.py b/tests/models/test_typecheck_coverage.py new file mode 100644 index 0000000..e7f03b6 --- /dev/null +++ b/tests/models/test_typecheck_coverage.py @@ -0,0 +1,190 @@ +"""Future-returning handle methods have an executed static type assertion.""" + +import ast +import importlib +import inspect +from pathlib import Path + +import pytest + +from openprotein import models + +HANDLE_TYPES = (models.Model, models.GP, models.SVD, models.UMAP) + +CONTRACTS = { + ("GP", "fit"): "GPFitFuture", + ("SVD", "fit"): "SVDFitFuture", + ("SVD", "fit_transform"): "SVDFitFuture", + ("UMAP", "fit"): "UMAPFitFuture", + ("UMAP", "fit_transform"): "UMAPFitFuture", + ("GPModel", "crossvalidate"): "CrossvalidateFuture", + ("GPModel", "single_site"): "SingleSitePredictionFuture", + ("AlphaFlow", "sample"): "StructurePredictionFuture", + ("BioEmu", "sample"): "StructurePredictionFuture", + ("ESMFlow", "sample"): "StructurePredictionFuture", + ("Model", "attn"): "AttentionFuture", + ("Model", "embed"): "EmbeddingFuture", + ("Model", "fold"): "StructurePredictionFuture", + ( + "Model", + "generate", + ): "SequenceGenerationFuture | StructureDesignFuture | Future", + ("Model", "indel"): "IndelScoreFuture", + ("Model", "logits"): "LogitsFuture", + ("Model", "predict"): "PredictionFuture", + ("Model", "score"): "LogLikelihoodFuture", + ( + "Model", + "single_site", + ): "SingleSitePredictionFuture | SingleSiteScoreFuture | Future", + ("PoET", "embed"): "EmbeddingFuture", + ("PoET", "fit_gp"): "GPFitFuture", + ("PoET", "fit_svd"): "SVDFitFuture", + ("PoET", "fit_umap"): "UMAPFitFuture", + ("PoET", "generate"): "SequenceGenerationFuture", + ("PoET", "indel"): "IndelScoreFuture", + ("PoET", "logits"): "LogitsFuture", + ("PoET", "score"): "LogLikelihoodFuture", + ("PoET", "single_site"): "SingleSiteScoreFuture", + ("PoET2", "attn"): "AttentionFuture", + ("PoET2", "embed"): "EmbeddingFuture", + ("PoET2", "fit_gp"): "GPFitFuture", + ("PoET2", "fit_svd"): "SVDFitFuture", + ("PoET2", "fit_umap"): "UMAPFitFuture", + ("PoET2", "generate"): "SequenceGenerationFuture", + ("PoET2", "logits"): "LogitsFuture", + ("PoET2", "score"): "LogLikelihoodFuture", + ("PoET2", "single_site"): "SingleSiteScoreFuture", + ("ProteinLanguageModel", "embed"): "EmbeddingFuture", + ("ProteinLanguageModel", "fit_gp"): "GPFitFuture", + ("ProteinLanguageModel", "fit_svd"): "SVDFitFuture", + ("ProteinLanguageModel", "fit_umap"): "UMAPFitFuture", + ("ProteinLanguageModel", "single_site"): "SingleSiteScoreFuture", + ("ProteinMPNN", "embed"): "EmbeddingFuture", + ("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", +} + + +def _type_names(annotation: ast.expr) -> frozenset[str]: + return frozenset(n.id for n in ast.walk(annotation) if isinstance(n, ast.Name)) + + +def _checked_methods(source: str) -> dict[tuple[str, str], frozenset[str]]: + tree = ast.parse(source) + classes = {} + for node in tree.body: + if isinstance(node, ast.ImportFrom) and node.module: + module = importlib.import_module(node.module) + for alias in node.names: + cls = getattr(module, alias.name) + if inspect.isclass(cls) and issubclass(cls, HANDLE_TYPES): + classes[alias.asname or alias.name] = cls + checked = {} + for function in tree.body: + if not isinstance(function, ast.FunctionDef): + continue + handles = { + arg.arg: classes[arg.annotation.id] + for arg in function.args.args + if isinstance(arg.annotation, ast.Name) and arg.annotation.id in classes + } + for node in ast.walk(function): + if not ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) + and node.func.id == "assert_type" + and len(node.args) == 2 + ): + continue + call, expected = node.args + if not ( + isinstance(call, ast.Call) + and isinstance(call.func, ast.Attribute) + and isinstance(call.func.value, ast.Name) + and call.func.value.id in handles + ): + continue + method = getattr(handles[call.func.value.id], call.func.attr) + owner, name = method.__qualname__.rsplit(".", 1) + checked[owner, name] = _type_names(expected) + return checked + + +def test_every_future_returning_handle_method_is_type_checked(): + source = Path(__file__).with_name("typecheck_task_futures.py").read_text() + checked = _checked_methods(source) + expected = { + key: _type_names(ast.parse(value, mode="eval").body) + for key, value in CONTRACTS.items() + } + assert {key: checked.get(key) for key in expected} == expected + + +def test_exported_handles_keep_their_inherited_method_contracts(): + for name in models.__all__: + cls = getattr(models, name) + if not inspect.isclass(cls) or not issubclass(cls, HANDLE_TYPES): + continue + for method in {method for _, method in CONTRACTS}: + owner = next( + ( + base.__name__ + for base in cls.__mro__ + if (base.__name__, method) in CONTRACTS + ), + None, + ) + if owner is not None: + assert getattr(cls, method).__qualname__ == f"{owner}.{method}" + + +@pytest.mark.parametrize( + ("body", "expected"), + [ + ("pass", {}), + ("pass # Model.embed", {}), + ( + "assert_type(model.embed(['MKT']), EmbeddingFuture)", + {("Model", "embed"): frozenset({"EmbeddingFuture"})}, + ), + ( + "assert_type(model.embed(['MKT']), Future)", + {("Model", "embed"): frozenset({"Future"})}, + ), + ], +) +def test_typecheck_coverage_reads_assertions_and_their_expected_types(body, expected): + source = ( + f"from openprotein.models import Model\ndef check(model: Model):\n {body}\n" + ) + assert _checked_methods(source) == expected + + +@pytest.mark.parametrize( + ("body", "expected"), + [ + ("pass", {}), + ("pass # SVD.fit", {}), + ( + "assert_type(estimator.fit(), SVDFitFuture)", + {("SVD", "fit"): frozenset({"SVDFitFuture"})}, + ), + ( + "assert_type(estimator.fit(), Future)", + {("SVD", "fit"): frozenset({"Future"})}, + ), + ], +) +def test_estimator_coverage_reads_assertions_and_their_expected_types(body, expected): + source = ( + f"from openprotein.models import SVD\ndef check(estimator: SVD):\n {body}\n" + ) + assert _checked_methods(source) == expected diff --git a/tests/models/test_units_record.py b/tests/models/test_units_record.py new file mode 100644 index 0000000..9d8c874 --- /dev/null +++ b/tests/models/test_units_record.py @@ -0,0 +1,81 @@ +import pytest +from pydantic import ValidationError + +from openprotein.jobs import JobStatus +from openprotein.jobs.schemas import _UnitRecord + + +@pytest.mark.parametrize( + ("state", "status"), + [ + ("PENDING", JobStatus.PENDING), + ("READY", JobStatus.PENDING), + ("RUNNING", JobStatus.RUNNING), + ("SUCCESS", JobStatus.SUCCESS), + ("FAILED", JobStatus.FAILURE), + ("CANCELED", JobStatus.CANCELED), + ], +) +def test_a_record_reads_its_state_as_a_job_status(state, status): + record = _UnitRecord.model_validate( + {"position": 0, "unit_id": "a" * 64, "state": state} + ) + + assert record.status is status + + +def test_a_record_with_a_status_key_reads_it_before_state(): + record = _UnitRecord.model_validate( + {"position": 0, "unit_id": "u", "status": "FAILURE", "state": "SUCCESS"} + ) + + assert record.status is JobStatus.FAILURE + + +def test_a_record_holds_position_unit_id_status_and_error_only(): + record = _UnitRecord.model_validate( + { + "position": 3, + "unit_id": "a" * 64, + "state": "RUNNING", + "retries": 1, + "chunk_id": "c1", + "cached": True, + "error": {"message": "boom"}, + } + ) + + assert record.model_dump() == { + "position": 3, + "unit_id": "a" * 64, + "status": JobStatus.RUNNING, + "error": {"message": "boom"}, + } + + +def test_a_record_without_an_error_has_none(): + record = _UnitRecord.model_validate( + {"position": 0, "unit_id": "u", "state": "SUCCESS"} + ) + + assert record.error is None + + +@pytest.mark.parametrize( + "record", + [ + {"position": 0, "unit_id": "u"}, + {"position": 0, "unit_id": "u", "state": "UNKNOWN"}, + ], +) +def test_a_record_needs_a_known_status(record): + with pytest.raises(ValidationError): + _UnitRecord.model_validate(record) + + +def test_a_null_status_reads_the_state_key(): + record = _UnitRecord.model_validate( + {"position": 0, "unit_id": "u", "status": None, "state": "RUNNING"} + ) + + assert record.status is JobStatus.RUNNING diff --git a/tests/models/typecheck_ensemble_models.py b/tests/models/typecheck_ensemble_models.py new file mode 100644 index 0000000..ef3150a --- /dev/null +++ b/tests/models/typecheck_ensemble_models.py @@ -0,0 +1,50 @@ +from typing_extensions import assert_type + +from openprotein.jobs.futures import ( + StructureDesignFuture, + StructurePredictionFuture, +) +from openprotein.models import ( + ESM2, + AlphaFlow, + AlphaFlowInput, + BioEmu, + BioEmuInput, + ESMFlow, + ESMFlowInput, + ESMFold, + ModelsAPI, + StructureGenerativeModel, +) +from openprotein.molecules import Protein, Structure + + +def accessor_types(models: ModelsAPI) -> None: + assert_type(models.esm2, ESM2) + assert_type(models.esmfold, ESMFold) + assert_type(models.bioemu_v1_1, BioEmu) + assert_type(models.bioemu, BioEmu) + assert_type(models.alphaflow, AlphaFlow) + assert_type(models.esmflow, ESMFlow) + assert_type(models.alphaflow_md_base_v1, AlphaFlow) + assert_type(models.alphaflow_md_distilled_v1, AlphaFlow) + assert_type(models.esmflow_md_base_v1, ESMFlow) + assert_type(models.esmflow_md_distilled_v1, ESMFlow) + + +def input_types(bioemu: BioEmu, alphaflow: AlphaFlow, esmflow: ESMFlow) -> None: + assert_type(bioemu.Input, type[BioEmuInput]) + assert_type(alphaflow.Input, type[AlphaFlowInput]) + assert_type(esmflow.Input, type[ESMFlowInput]) + + +def prediction_types(esmflow: ESMFlow, reference: Protein) -> None: + assert_type( + esmflow.sample([ESMFlowInput("MKT", reference_structure=reference)]), + StructurePredictionFuture, + ) + assert_type(esmflow.sample([ESMFlowInput("MKT")]).get(), list[Structure]) + + +def generative_types(model: StructureGenerativeModel) -> None: + assert_type(model.generate(), StructureDesignFuture) diff --git a/tests/models/typecheck_task_futures.py b/tests/models/typecheck_task_futures.py new file mode 100644 index 0000000..9678017 --- /dev/null +++ b/tests/models/typecheck_task_futures.py @@ -0,0 +1,194 @@ +from collections.abc import Iterator +from typing import Any + +import numpy as np +from typing_extensions import assert_type + +from openprotein.data.prompts import Prompt +from openprotein.jobs import ( + AttentionFuture, + CrossvalidateFuture, + CrossvalidateResults, + EmbeddingFuture, + Future, + FutureUnit, + GPFitFuture, + IndelScoreFuture, + JobStatus, + LogitsFuture, + LogLikelihoodFuture, + PredictionFuture, + SequenceGenerationFuture, + SingleSitePredictionFuture, + SingleSiteScoreFuture, + StructureDesignFuture, + StructurePredictionFuture, + SVDFitFuture, + UMAPFitFuture, +) +from openprotein.models import ( + ESMIF1, + GP, + SVD, + UMAP, + AlphaFlow, + BioEmu, + ESMFlow, + GPModel, + Model, + PoET, + PoET2, + ProteinLanguageModel, + ProteinMPNN, + RFdiffusion, + StructureGenerativeModel, + StructurePredictionModel, + SVDModel, + UMAPModel, +) +from openprotein.molecules import Complex + + +def task_result_types( + embedding: EmbeddingFuture, design: StructureDesignFuture +) -> None: + assert_type(embedding.get(), list[np.ndarray]) + assert_type(embedding.get_item(0), np.ndarray) + assert_type(design.get(), list[Complex]) + assert_type(design.wait(), list[Complex]) + assert_type(design[0], Complex) + assert_type(design.stream(), Iterator[Complex]) + assert_type(design.unit(0), FutureUnit[Complex]) + assert_type(design.units, list[FutureUnit[Complex]]) + assert_type(design.units[0].status, JobStatus) + assert_type(design.unit(0).get(), Complex) + assert_type(design.get(output="confidence"), list[Any]) + + +def fitted_result_types( + gp: GPFitFuture, svd: SVDFitFuture, umap: UMAPFitFuture +) -> None: + assert_type(gp.get(), GPModel) + assert_type(gp.wait(), GPModel) + assert_type(svd.get(), SVDModel) + assert_type(svd.wait(), SVDModel) + assert_type(svd.get(output="embeddings"), list[Any]) + assert_type(svd.wait(output="embeddings"), list[Any]) + assert_type(umap.get(), UMAPModel) + assert_type(umap.wait(), UMAPModel) + assert_type(svd.transform(["MKT"]), EmbeddingFuture) + assert_type(umap.embed(["MKT"]), EmbeddingFuture) + + +def prompt_result_types(prompt: Prompt) -> None: + assert_type(prompt.wait(), Prompt) + assert_type(prompt[0], list[str]) + assert_type(list(prompt), list[list[str]]) + + +def crossvalidation_result_types(future: CrossvalidateFuture) -> None: + assert_type(future.get(), CrossvalidateResults) + assert_type(future.wait(), CrossvalidateResults) + + +def submission_types( + plm: ProteinLanguageModel, + rfdiffusion: RFdiffusion, + predictor: StructurePredictionModel, + gp: GPModel, +) -> None: + assert_type(plm.embed(["MKT"]), EmbeddingFuture) + assert_type(rfdiffusion.generate(), StructureDesignFuture) + assert_type(predictor.fold("MKT"), StructurePredictionFuture) + assert_type(plm.single_site("MKT"), SingleSiteScoreFuture) + assert_type(gp.single_site("MKT"), SingleSitePredictionFuture) + + +def estimator_types(svd: SVD, umap: UMAP, gp: GP) -> None: + assert_type(svd.fit(), SVDFitFuture) + assert_type(svd.fit_transform(), SVDFitFuture) + assert_type(umap.fit(), UMAPFitFuture) + assert_type(umap.fit_transform(), UMAPFitFuture) + assert_type(gp.fit(), GPFitFuture) + + +def generic_model_types(model: Model) -> None: + assert_type(model.attn(["MKT"]), AttentionFuture) + assert_type(model.embed(["MKT"]), EmbeddingFuture) + assert_type(model.fold(["MKT"]), StructurePredictionFuture) + assert_type( + model.generate(), SequenceGenerationFuture | StructureDesignFuture | Future + ) + assert_type(model.indel("MKT"), IndelScoreFuture) + assert_type(model.logits(["MKT"]), LogitsFuture) + assert_type(model.predict(["MKT"]), PredictionFuture) + assert_type(model.score(["MKT"]), LogLikelihoodFuture) + assert_type( + model.single_site("MKT"), + SingleSiteScoreFuture | SingleSitePredictionFuture | Future, + ) + + +def protein_language_model_types(plm: ProteinLanguageModel) -> None: + assert_type(plm.fit_gp("assay-id", ["fitness"], reduction="MEAN"), GPFitFuture) + assert_type(plm.fit_svd(["MKT"]), SVDFitFuture) + assert_type(plm.fit_umap(["MKT"]), UMAPFitFuture) + + +def poet_types(poet: PoET) -> None: + assert_type(poet.embed(["MKT"]), EmbeddingFuture) + assert_type(poet.fit_gp("assay-id", ["fitness"], reduction="MEAN"), GPFitFuture) + assert_type(poet.fit_svd(["MKT"]), SVDFitFuture) + assert_type(poet.fit_umap(["MKT"]), UMAPFitFuture) + assert_type(poet.generate(), SequenceGenerationFuture) + assert_type(poet.indel("MKT"), IndelScoreFuture) + assert_type(poet.logits(["MKT"]), LogitsFuture) + assert_type(poet.score(["MKT"]), LogLikelihoodFuture) + assert_type(poet.single_site("MKT"), SingleSiteScoreFuture) + + +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.fit_gp("assay-id", ["fitness"], reduction="MEAN", query="MKT"), + GPFitFuture, + ) + assert_type(poet2.fit_svd(["MKT"], query="MKT"), SVDFitFuture) + assert_type(poet2.fit_umap(["MKT"], query="MKT"), UMAPFitFuture) + assert_type(poet2.generate(query="MKT"), SequenceGenerationFuture) + assert_type(poet2.logits(["MKT"], query="MKT"), LogitsFuture) + assert_type(poet2.score(["MKT"], query="MKT"), LogLikelihoodFuture) + assert_type(poet2.single_site("MKT", query="MKT"), SingleSiteScoreFuture) + + +def inverse_folding_types(inverse: ESMIF1, proteinmpnn: ProteinMPNN) -> None: + assert_type(inverse.generate(), SequenceGenerationFuture) + assert_type(inverse.score(["MKT"]), LogLikelihoodFuture) + assert_type(inverse.single_site("MKT"), SingleSiteScoreFuture) + assert_type(proteinmpnn.embed(["MKT"]), EmbeddingFuture) + + +def structure_model_types( + bioemu: BioEmu, + alphaflow: AlphaFlow, + esmflow: ESMFlow, + generative: StructureGenerativeModel, +) -> None: + assert_type( + bioemu.sample([bioemu.Input("MKT", msa=None)]), StructurePredictionFuture + ) + assert_type( + alphaflow.sample([alphaflow.Input("MKT", msa="msa-id")]), + StructurePredictionFuture, + ) + assert_type(esmflow.sample([esmflow.Input("MKT")]), StructurePredictionFuture) + assert_type(generative.generate(), StructureDesignFuture) + + +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) + assert_type(svd.fit_umap(["MKT"]), UMAPFitFuture) + assert_type(svd.transform(["MKT"]), EmbeddingFuture) + assert_type(umap.transform(["MKT"]), EmbeddingFuture) diff --git a/tests/molecules/test_complex_mapping.py b/tests/molecules/test_complex_mapping.py index 9f5f784..4f0c15f 100644 --- a/tests/molecules/test_complex_mapping.py +++ b/tests/molecules/test_complex_mapping.py @@ -56,9 +56,7 @@ def test_update_rejects_overlapping_chain_ids(): def test_clear_drops_chains_and_templates(): - complex = Complex({"A": Protein.from_expr(6)}).set_templates( - [Protein.from_expr(8)] - ) + complex = Complex({"A": Protein.from_expr(6)}).set_templates([Protein.from_expr(8)]) complex.clear() assert len(complex) == 0 assert complex.templates == () @@ -99,7 +97,5 @@ def test_protein_operators_build_a_two_chain_complex(): reason="Complex.copy() returns a Complex with no templates, so combining drops them" ) def test_templates_survive_combining(): - complex = Complex({"A": Protein.from_expr(6)}).set_templates( - [Protein.from_expr(8)] - ) + complex = Complex({"A": Protein.from_expr(6)}).set_templates([Protein.from_expr(8)]) assert len((complex | Protein.from_expr(7)).templates) == 1 diff --git a/tests/molecules/test_model_numbering.py b/tests/molecules/test_model_numbering.py new file mode 100644 index 0000000..6caad9e --- /dev/null +++ b/tests/molecules/test_model_numbering.py @@ -0,0 +1,138 @@ +import re + +import gemmi +import numpy as np +import pytest + +from openprotein.molecules import Complex, Protein, Structure + +MODEL_NUM_TAG = "_atom_site.pdbx_PDB_model_num" + + +@pytest.fixture(scope="module") +def complex_() -> Complex: + return Complex(Complex.from_filepath("tests/data/1A3N.cif").get_proteins()) + + +def _cif_model_nums(cif: str) -> list[str]: + block = gemmi.cif.read_string(cif).sole_block() + return list(block.find_values(MODEL_NUM_TAG)) + + +def _pdb_model_nums(pdb: str) -> list[int]: + return [int(m) for m in re.findall(r"^MODEL\s+(\d+)", pdb, flags=re.MULTILINE)] + + +def _with_zero_based_cif_model_nums(cif: str) -> str: + doc = gemmi.cif.read_string(cif) + column = doc.sole_block().find_values(MODEL_NUM_TAG) + for i, num in enumerate(column): + column[i] = str(int(num) - 1) + return doc.as_string() + + +def _two_model_structure(complex_: Complex) -> Structure: + return Structure([complex_.copy(), complex_.copy().transform(t=np.ones(3))]) + + +def test_complex_cif_atoms_all_model_one(complex_): + nums = _cif_model_nums(complex_.to_string("cif")) + assert len(nums) > 0 + assert set(nums) == {"1"} + + +def test_single_complex_structure_cif_atoms_all_model_one(complex_): + nums = _cif_model_nums(Structure([complex_]).to_string("cif")) + assert len(nums) > 0 + assert set(nums) == {"1"} + + +def test_protein_cif_atoms_all_model_one(complex_): + protein = complex_.get_protein("A") + nums = _cif_model_nums(protein.to_string("cif")) + assert len(nums) > 0 + assert set(nums) == {"1"} + + +@pytest.mark.parametrize("n_models", (2, 3)) +def test_multi_model_cif_is_numbered_one_to_n(complex_, n_models): + structure = Structure( + [complex_.copy().transform(t=np.full(3, float(i))) for i in range(n_models)] + ) + nums = _cif_model_nums(structure.to_string("cif")) + assert set(nums) == {str(i) for i in range(1, n_models + 1)} + assert nums == sorted(nums) + + +def test_single_model_pdb_is_model_one(complex_): + pdb = complex_.to_string("pdb") + assert _pdb_model_nums(pdb) in ([], [1]) + assert [m.num for m in gemmi.read_pdb_string(pdb)] == [1] + + +def test_multi_model_pdb_is_numbered_one_to_n(complex_): + structure = _two_model_structure(complex_) + pdb = structure.to_string("pdb") + assert _pdb_model_nums(pdb) == [1, 2] + + +@pytest.mark.parametrize("format", ("cif", "pdb")) +def test_complex_round_trip(complex_, format): + new = Complex.from_string(complex_.to_string(format), format=format) + assert np.allclose( + new.get_protein("A").coordinates, + complex_.get_protein("A").coordinates, + atol=1e-2, + equal_nan=True, + ) + + +@pytest.mark.parametrize("format", ("cif", "pdb")) +def test_multi_model_round_trip(complex_, format): + structure = _two_model_structure(complex_) + new = Structure.from_string(structure.to_string(format), format=format) + assert len(new) == 2 + for i in range(2): + assert np.allclose( + new[i].get_protein("A").coordinates, + structure[i].get_protein("A").coordinates, + atol=1e-2, + equal_nan=True, + ) + + +def test_reads_single_model_zero_numbered_cif(complex_): + cif = _with_zero_based_cif_model_nums(complex_.to_string("cif")) + assert set(_cif_model_nums(cif)) == {"0"} + new = Complex.from_string(cif, format="cif", model_idx=0) + assert np.allclose( + new.get_protein("A").coordinates, + complex_.get_protein("A").coordinates, + equal_nan=True, + ) + protein = Protein.from_string(cif, format="cif", chain_id="A", model_idx=0) + assert np.allclose( + protein.coordinates, complex_.get_protein("A").coordinates, equal_nan=True + ) + + +def test_reads_multi_model_zero_numbered_cif(complex_): + structure = _two_model_structure(complex_) + cif = _with_zero_based_cif_model_nums(structure.to_string("cif")) + assert set(_cif_model_nums(cif)) == {"0", "1"} + new = Structure.from_string(cif, format="cif") + assert len(new) == 2 + for i in range(2): + assert np.allclose( + new[i].get_protein("A").coordinates, + structure[i].get_protein("A").coordinates, + atol=1e-2, + equal_nan=True, + ) + second = Complex.from_string(cif, format="cif", model_idx=1) + assert np.allclose( + second.get_protein("A").coordinates, + structure[1].get_protein("A").coordinates, + atol=1e-2, + equal_nan=True, + ) diff --git a/tests/molecules/test_protein.py b/tests/molecules/test_protein.py index 3e96c06..7e0de7b 100644 --- a/tests/molecules/test_protein.py +++ b/tests/molecules/test_protein.py @@ -9,7 +9,7 @@ import gemmi -import openprotein.common.residue_contants as RC +import openprotein.common.residue_constants as RC from openprotein.molecules import Protein, Binding from openprotein.molecules.protein import _ATOM_TYPES, _SIDE_CHAIN_ATOM_IDXS @@ -219,9 +219,9 @@ def test_can_parse_boltzgen_entity_one_letter_missing_residues(): "tests/data/boltzgen_entity_one_letter_missing_residues.cif", chain_id="B" ) assert len(protein_b) == 127 - 1 # last label_seq is 127, missing residue 1 - assert ( - b"X" not in protein_b.sequence - ), "missing residues in _atom_site should be inferred form _entity_poly_seq" + assert b"X" not in protein_b.sequence, ( + "missing residues in _atom_site should be inferred form _entity_poly_seq" + ) def test_can_parse_9bkq_assembly2(): @@ -273,18 +273,14 @@ def assert_proteins_equal(x: Protein, y: Protein): def test_partially_masked_sequence(structure_path: str): protein = Protein.from_filepath(structure_path, chain_id="A") protein.sequence = "AXXMX" - new_protein = Protein.from_string( - protein.make_cif_string(), format="cif", chain_id="A" - ) + new_protein = Protein.from_string(protein.to_string(), format="cif", chain_id="A") assert_proteins_equal(protein, new_protein) def test_fully_masked_sequence(structure_path: str): protein = Protein.from_filepath(structure_path, chain_id="A") protein.sequence = "X" * len(protein.sequence) - new_protein = Protein.from_string( - protein.make_cif_string(), format="cif", chain_id="A" - ) + new_protein = Protein.from_string(protein.to_string(), format="cif", chain_id="A") assert_proteins_equal(protein, new_protein) @@ -293,18 +289,14 @@ def test_partially_masked_plddt(structure_path: str): _plddt = protein.plddt.copy() _plddt[[0, 1]] = np.nan protein._plddt = _plddt.copy() - new_protein = Protein.from_string( - protein.make_cif_string(), format="cif", chain_id="A" - ) + new_protein = Protein.from_string(protein.to_string(), format="cif", chain_id="A") assert_proteins_equal(protein, new_protein) def test_fully_masked_plddt(structure_path: str): protein = Protein.from_filepath(structure_path, chain_id="A") protein._plddt = np.full_like(protein.plddt, np.nan) - new_protein = Protein.from_string( - protein.make_cif_string(), format="cif", chain_id="A" - ) + new_protein = Protein.from_string(protein.to_string(), format="cif", chain_id="A") assert_proteins_equal(protein, new_protein) @@ -315,9 +307,7 @@ def test_partially_masked_coordinates(structure_path: str): _coordinates[[0, 2, 3]], _plddt[[0, 2, 3]] = np.nan, np.nan protein = protein._set_coordinates(_coordinates) protein._plddt = _plddt.copy() - new_protein = Protein.from_string( - protein.make_cif_string(), format="cif", chain_id="A" - ) + new_protein = Protein.from_string(protein.to_string(), format="cif", chain_id="A") assert_proteins_equal(protein, new_protein) @@ -327,9 +317,7 @@ def test_partially_masked_coordinates_non_ca_atom_only(structure_path: str): _coordinates = protein.coordinates.copy() _coordinates[[1, 4], 0] = np.nan protein = protein._set_coordinates(_coordinates) - new_protein = Protein.from_string( - protein.make_cif_string(), format="cif", chain_id="A" - ) + new_protein = Protein.from_string(protein.to_string(), format="cif", chain_id="A") assert_proteins_equal(protein, new_protein) @@ -340,7 +328,7 @@ def test_partially_masked_coordinates_ca_atom_only(structure_path: str): _coordinates[[1, 4], 1] = np.nan protein = protein._set_coordinates(_coordinates) with pytest.raises(AssertionError): - protein.make_cif_string() + protein.to_string() def test_mixed_partial_masking(structure_path: str): @@ -351,12 +339,30 @@ def test_mixed_partial_masking(structure_path: str): _coordinates[[1, 4], 0], _plddt[[0, 1]] = np.nan, np.nan protein = protein._set_coordinates(_coordinates) protein._plddt = _plddt.copy() - new_protein = Protein.from_string( - protein.make_cif_string(), format="cif", chain_id="A" - ) + new_protein = Protein.from_string(protein.to_string(), format="cif", chain_id="A") assert_proteins_equal(protein, new_protein) +def _random_protein(rng: np.random.Generator) -> Protein: + coordinates = rng.normal(scale=10.0, size=(5, 37, 3)).astype(np.float32) + return Protein(sequence=TEST_SEQUENCE)._set_coordinates(coordinates) + + +def test_rmsd_to_itself_is_zero(): + protein = _random_protein(np.random.default_rng(0)) + assert protein.rmsd(protein.copy()) == pytest.approx(0.0, abs=1e-5) + + +def test_rmsd_ignores_rigid_motion(): + rng = np.random.default_rng(0) + protein = _random_protein(rng) + rotation, _ = np.linalg.qr(rng.normal(size=(3, 3))) + if np.linalg.det(rotation) < 0: + rotation[:, 0] *= -1 + moved = protein.copy().transform(R=rotation, t=np.array([5.0, -3.0, 2.0])) + assert protein.rmsd(moved) == pytest.approx(0.0, abs=1e-4) + + def main(): protein = Protein(name="test", sequence=TEST_SEQUENCE)._set_coordinates( TEST_COORDINATES diff --git a/tests/molecules/test_structure.py b/tests/molecules/test_structure.py index 3f0df54..c12ebf6 100644 --- a/tests/molecules/test_structure.py +++ b/tests/molecules/test_structure.py @@ -194,9 +194,9 @@ def test_serde_multiple_models(): != structure[0].get_protein(chain_id="A").coordinates ).all(), "coordinates of first and second complex should be different" new_structure = Structure.from_string(structure.to_string(), format="cif") - assert len(new_structure) == len( - structure - ), "new structure should have same number of complexes" + assert len(new_structure) == len(structure), ( + "new structure should have same number of complexes" + ) assert ( new_structure[1].get_protein(chain_id="A").coordinates != new_structure[0].get_protein(chain_id="A").coordinates diff --git a/tests/predictor/test_predictor.py b/tests/predictor/test_predictor.py index a51d9e8..c43f0e4 100644 --- a/tests/predictor/test_predictor.py +++ b/tests/predictor/test_predictor.py @@ -1,25 +1,20 @@ """L2 integration tests for the predictor domain.""" -from datetime import datetime from unittest.mock import MagicMock, patch import pytest -from openprotein import OpenProtein -from openprotein.base import APISession from openprotein.common import FeatureType from openprotein.data.data import DataAPI from openprotein.errors import InvalidParameterError -from openprotein.jobs import JobStatus, JobType +from openprotein.jobs import JobType from openprotein.predictor.predictor import PredictorAPI from openprotein.svd.models import SVDModel -from openprotein.svd.schemas import SVDMetadata from openprotein.svd.svd import SVDAPI @pytest.fixture def predictor_api(mock_session: MagicMock): - """Fixture to create a PredictorAPI instance with a mocked session.""" return PredictorAPI(mock_session) @@ -27,10 +22,6 @@ def predictor_api(mock_session: MagicMock): def test_fit_gp_with_svd_model( mock_fit_gp_post: MagicMock, predictor_api: PredictorAPI, mock_session: MagicMock ): - """ - Test the integration of fit_gp when using an SVD model. - """ - # 1. Setup # The final call in the chain is predictor_fit_gp_post mock_session.post.return_value.json.return_value = { "job_id": "job-123", @@ -56,16 +47,14 @@ def test_fit_gp_with_svd_model( predictor_api.session.svd = MagicMock(spec=SVDAPI) predictor_api.session.svd.get_svd.return_value = mock_svd_model predictor_api.session.data = MagicMock(spec=DataAPI) - predictor_api.session.data.get.return_value.measurement_names = ["p1"] + predictor_api.session.data.Assay.return_value.measurement_names = ["p1"] - # 2. Execution predictor_api.fit_gp( assay="assay-1", properties=["p1"], model="svd-1", feature_type=FeatureType.SVD, ) - # 3. Verification predictor_api.session.svd.get_svd.assert_called_once_with("svd-1") mock_fit_gp_post.assert_called_once() @@ -73,14 +62,16 @@ def test_fit_gp_with_svd_model( def test_fit_gp_kernel_validation(predictor_api: PredictorAPI, mock_session: MagicMock): """Client-side fail-fast validation of kernel hyperparameters.""" predictor_api.session.data = MagicMock(spec=DataAPI) - predictor_api.session.data.get.return_value.measurement_names = ["p1"] + predictor_api.session.data.Assay.return_value.measurement_names = ["p1"] bad = [ - dict(kernel="rbf", period=2.0), # period on non-periodic - dict(kernel="periodic", alpha=2.0), # alpha on non-rq - dict(kernel="periodic", period=0), # period must be > 0 + dict(kernel="rbf", period=2.0), # period on non-periodic + dict(kernel="periodic", alpha=2.0), # alpha on non-rq + dict(kernel="periodic", period=0), # period must be > 0 dict(kernel="rational_quadratic", alpha=-1), # alpha must be > 0 - dict(kernel="bogus"), # unknown kernel + dict(kernel="bogus"), # unknown kernel ] for kw in bad: with pytest.raises(InvalidParameterError): - predictor_api.fit_gp("assay-1", ["p1"], "m1", feature_type="PLM", reduction="MEAN", **kw) + predictor_api.fit_gp( + "assay-1", ["p1"], "m1", feature_type="PLM", reduction="MEAN", **kw + ) diff --git a/tests/predictor/test_predictor_api.py b/tests/predictor/test_predictor_api.py index 8ba910a..14f8170 100644 --- a/tests/predictor/test_predictor_api.py +++ b/tests/predictor/test_predictor_api.py @@ -1,16 +1,12 @@ """Test the api for the predictor domain.""" -from unittest.mock import MagicMock -import pytest +from unittest.mock import MagicMock -from openprotein.common import FeatureType from openprotein.jobs import JobType from openprotein.predictor import api -from openprotein.predictor.schemas import PredictorMetadata def test_predictor_list(mock_session: MagicMock): - """Test predictor_list.""" mock_session.get.return_value.json.return_value = [] api.predictor_list(mock_session, limit=50, offset=5) mock_session.get.assert_called_once_with( @@ -20,7 +16,6 @@ def test_predictor_list(mock_session: MagicMock): def test_predictor_get(mock_session: MagicMock): - """Test predictor_get.""" mock_session.get.return_value.json.return_value = { "id": "p1", "name": "p1", @@ -35,8 +30,30 @@ def test_predictor_get(mock_session: MagicMock): ) +def test_predictor_get_hyperparameters(mock_session: MagicMock): + mock_session.timeout = 7 + mock_session.get.return_value.json.return_value = { + "p1": { + "mean": 0.5, + "noise": 0.1, + "lengthscale": [0.8], + "outputscale": [2.0], + "period": [None], + "alpha": [None], + } + } + out = api._predictor_get_hyperparameters(mock_session, "p1") + mock_session.get.assert_called_once_with( + "v1/predictor/p1/hyperparameters", timeout=7 + ) + assert out["p1"].mean == 0.5 + assert out["p1"].noise == 0.1 + assert out["p1"].lengthscale == [0.8] + assert out["p1"].outputscale == [2.0] + assert out["p1"].period == [None] + + def test_predictor_fit_gp_post(mock_session: MagicMock): - """Test predictor_fit_gp_post.""" mock_session.post.return_value.json.return_value = { "job_id": "job1", "status": "SUCCESS", @@ -69,6 +86,14 @@ def test_predictor_fit_gp_post_kernel(mock_session: MagicMock): api.predictor_fit_gp_post(mock_session, **common) assert mock_session.post.call_args.kwargs["json"]["kernel"] == {"type": "rbf"} api.predictor_fit_gp_post(mock_session, kernel="periodic", period=2.0, **common) - assert mock_session.post.call_args.kwargs["json"]["kernel"] == {"type": "periodic", "period": 2.0} - api.predictor_fit_gp_post(mock_session, kernel="rational_quadratic", alpha=3.0, **common) - assert mock_session.post.call_args.kwargs["json"]["kernel"] == {"type": "rational_quadratic", "alpha": 3.0} + assert mock_session.post.call_args.kwargs["json"]["kernel"] == { + "type": "periodic", + "period": 2.0, + } + api.predictor_fit_gp_post( + mock_session, kernel="rational_quadratic", alpha=3.0, **common + ) + assert mock_session.post.call_args.kwargs["json"]["kernel"] == { + "type": "rational_quadratic", + "alpha": 3.0, + } diff --git a/tests/predictor/test_predictor_futures.py b/tests/predictor/test_predictor_futures.py index eda5628..8d2dd7d 100644 --- a/tests/predictor/test_predictor_futures.py +++ b/tests/predictor/test_predictor_futures.py @@ -1,4 +1,5 @@ """Test the Future classes for the predictor domain.""" + from unittest.mock import MagicMock, patch import numpy as np @@ -13,11 +14,14 @@ def test_prediction_result_future_get(mock_session: MagicMock): mock_job.job_id = "job-123" future = PredictionResultFuture(session=mock_session, job=mock_job) - with patch( - "openprotein.predictor.api.predictor_predict_get_batched_result" - ) as mock_get_result, patch( - "openprotein.predictor.api.decode_predict", return_value=(1, 2) - ) as mock_decode: + with ( + patch( + "openprotein.predictor.api.predictor_predict_get_batched_result" + ) as mock_get_result, + patch( + "openprotein.predictor.api.decode_predict", return_value=(1, 2) + ) as mock_decode, + ): mu, var = future.get() mock_get_result.assert_called_once_with(mock_session, "job-123") mock_decode.assert_called_once() @@ -31,14 +35,30 @@ def test_cv_result_future_get(mock_session: MagicMock): mock_job.job_id = "job-456" future = CVResultFuture(session=mock_session, job=mock_job) - with patch( - "openprotein.predictor.api.predictor_crossvalidate_get" - ) as mock_get_cv, patch( - "openprotein.predictor.api.decode_crossvalidate", return_value=(1, 2, 3) - ) as mock_decode_cv: + with ( + patch("openprotein.predictor.api.predictor_crossvalidate_get") as mock_get_cv, + patch( + "openprotein.predictor.api.decode_crossvalidate", return_value=(1, 2, 3) + ) as mock_decode_cv, + ): y, mu, var = future.get() mock_get_cv.assert_called_once_with(mock_session, "job-456") mock_decode_cv.assert_called_once() assert y == 1 assert mu == 2 assert var == 3 + + +def test_decode_crossvalidate_reads_y_and_predictions_by_position(): + """The trailing columns of a crossvalidation result are ignored.""" + from openprotein.predictor import api + + csv_bytes = ( + b"row_index,sequence,measurement_name,y,y_mu,y_var,fold\n" + b"0,AAAA,p1,1.0,1.1,0.1,0\n" + b"1,CCCC,p1,2.0,2.1,0.2,1\n" + ) + y, mu, var = api.decode_crossvalidate(csv_bytes) + np.testing.assert_array_equal(y.astype(float), [1.0, 2.0]) + np.testing.assert_array_equal(mu.astype(float), [1.1, 2.1]) + np.testing.assert_array_equal(var.astype(float), [0.1, 0.2]) diff --git a/tests/predictor/test_predictor_models.py b/tests/predictor/test_predictor_models.py index d573d99..2d4ba3e 100644 --- a/tests/predictor/test_predictor_models.py +++ b/tests/predictor/test_predictor_models.py @@ -7,10 +7,17 @@ from openprotein.common import FeatureType from openprotein.jobs import JobsAPI, JobStatus, JobType +from openprotein.models.kernels import ( + LinearKernel, + PeriodicKernel, + RationalQuadraticKernel, + RBFKernel, +) from openprotein.predictor.models import PredictorModel, PredictorModelGroup from openprotein.predictor.schemas import ( Dataset, Features, + Kernel, ModelSpec, PredictorMetadata, PredictorTrainJob, @@ -20,7 +27,6 @@ @pytest.fixture def mock_predictor_metadata(): - """Fixture for a valid PredictorMetadata instance.""" return PredictorMetadata( id="p1", name="p1", @@ -36,7 +42,6 @@ def mock_predictor_metadata(): @pytest.fixture def mock_predictor_train_job(): - """Fixture for a valid PredictorTrainJob instance.""" return PredictorTrainJob( job_id="p1", status=JobStatus.SUCCESS, @@ -48,7 +53,6 @@ def mock_predictor_train_job(): def test_predictor_model_init( mock_session, mock_predictor_metadata, mock_predictor_train_job ): - """Test PredictorModel initialization with metadata.""" # The constructor expects session.jobs to be a JobsAPI instance mock_session.jobs = MagicMock(spec=JobsAPI) mock_session.jobs.get_job.return_value = mock_predictor_train_job @@ -56,10 +60,27 @@ def test_predictor_model_init( assert model.id == "p1" +def test_predictor_model_name_from_metadata( + mock_session, mock_predictor_metadata, mock_predictor_train_job +): + """PredictorModel.name and .description come from the predictor's own metadata, not the job.""" + mock_session.jobs = MagicMock(spec=JobsAPI) + job = mock_predictor_train_job.model_copy( + update={"name": "renamed-job", "description": "job note"} + ) + mock_session.jobs.get_job.return_value = job + metadata = mock_predictor_metadata.model_copy( + update={"name": "predictor-name", "description": "predictor note"} + ) + model = PredictorModel(session=mock_session, metadata=metadata) + + assert model.name == "predictor-name" + assert model.description == "predictor note" + + def test_predictor_model_predict( mock_session, mock_predictor_metadata, mock_predictor_train_job ): - """Test the predict method of PredictorModel.""" mock_session.jobs = MagicMock(spec=JobsAPI) mock_session.jobs.get_job.return_value = mock_predictor_train_job model = PredictorModel(session=mock_session, metadata=mock_predictor_metadata) @@ -73,7 +94,6 @@ def test_predictor_model_predict( def test_predictor_model_group( mock_session, mock_predictor_metadata, mock_predictor_train_job ): - """Test the PredictorModelGroup logic.""" mock_session.jobs = MagicMock(spec=JobsAPI) mock_session.jobs.get_job.return_value = mock_predictor_train_job model1 = PredictorModel(session=mock_session, metadata=mock_predictor_metadata) @@ -94,3 +114,189 @@ def test_predictor_model_group( mock_predict_multi.assert_called_once() call_args, call_kwargs = mock_predict_multi.call_args assert call_kwargs["predictor_ids"] == ["p1", "p2"] + + +def test_predictor_model_does_not_rename( + mock_session, mock_predictor_metadata, mock_predictor_train_job +): + mock_session.jobs = MagicMock(spec=JobsAPI) + mock_session.jobs.get_job.return_value = mock_predictor_train_job + model = PredictorModel(session=mock_session, metadata=mock_predictor_metadata) + + with pytest.raises(NotImplementedError, match="set when it is trained"): + model.rename(name="other") + mock_session.put.assert_not_called() + + +def _hyperparameters(lengthscale, period=None, alpha=None) -> dict: + return { + "p1": { + "mean": 0.5, + "noise": 0.1, + "lengthscale": [lengthscale], + "outputscale": [2.0], + "period": [period], + "alpha": [alpha], + } + } + + +def _gp(mock_session, metadata, train_job, kernel: str, hyperparameters: dict): + mock_session.jobs = MagicMock(spec=JobsAPI) + mock_session.jobs.get_job.return_value = train_job + mock_session.get.return_value.json.return_value = hyperparameters + spec = metadata.model_spec.model_copy( + update={"kernel": Kernel(type=kernel.upper())} + ) + return PredictorModel( + session=mock_session, metadata=metadata.model_copy(update={"model_spec": spec}) + ) + + +@pytest.mark.parametrize( + "kernel,hyperparameters,expected", + [ + ("linear", _hyperparameters(None), LinearKernel(outputscale=2.0)), + ("rbf", _hyperparameters(0.8), RBFKernel(outputscale=2.0, lengthscale=0.8)), + ( + "periodic", + _hyperparameters(0.8, period=3.0), + PeriodicKernel(outputscale=2.0, lengthscale=0.8, period=3.0), + ), + ( + "rational_quadratic", + _hyperparameters(0.8, alpha=1.5), + RationalQuadraticKernel(outputscale=2.0, lengthscale=0.8, alpha=1.5), + ), + ], +) +def test_predictor_kernel_has_its_type_hyperparameters( + mock_session, + mock_predictor_metadata, + mock_predictor_train_job, + kernel, + hyperparameters, + expected, +): + model = _gp( + mock_session, + mock_predictor_metadata, + mock_predictor_train_job, + kernel, + hyperparameters, + ) + + assert model.kernel == expected + assert type(model.kernel) is type(expected) + assert model.kernel.type == kernel + assert (model.mean, model.noise) == (0.5, 0.1) + + +def test_rbf_kernel_has_no_period( + mock_session, mock_predictor_metadata, mock_predictor_train_job +): + model = _gp( + mock_session, + mock_predictor_metadata, + mock_predictor_train_job, + "rbf", + _hyperparameters(0.8), + ) + + assert not hasattr(model.kernel, "period") + assert not hasattr(model.kernel, "alpha") + + +def test_predictor_hyperparameters_are_fetched_once( + mock_session, mock_predictor_metadata, mock_predictor_train_job +): + model = _gp( + mock_session, + mock_predictor_metadata, + mock_predictor_train_job, + "rbf", + _hyperparameters(0.8), + ) + + for _ in range(2): + _ = (model.kernel, model.mean, model.noise) + + hyperparameter_reads = [ + c + for c in mock_session.get.call_args_list + if c.args[0].endswith("/hyperparameters") + ] + assert len(hyperparameter_reads) == 1 + + +@pytest.mark.parametrize("lengthscale", [[None], []]) +def test_a_rejected_kernel_is_read_again( + mock_session, mock_predictor_metadata, mock_predictor_train_job, lengthscale +): + rejected = _hyperparameters(0.8) + rejected["p1"]["lengthscale"] = lengthscale + model = _gp( + mock_session, + mock_predictor_metadata, + mock_predictor_train_job, + "rbf", + rejected, + ) + + assert model.mean == 0.5 + with pytest.raises(ValueError): + _ = model.kernel + mock_session.get.return_value.json.return_value = _hyperparameters(0.8) + + assert model.kernel == RBFKernel(outputscale=2.0, lengthscale=0.8) + hyperparameter_reads = [ + c + for c in mock_session.get.call_args_list + if c.args[0].endswith("/hyperparameters") + ] + assert len(hyperparameter_reads) == 2 + + +@pytest.mark.parametrize( + "kernel,hyperparameters,expected", + [ + ("rbf", _hyperparameters(0.8), ["lengthscale", "outputscale", "type"]), + ( + "periodic", + _hyperparameters(0.8, period=3.0), + ["lengthscale", "outputscale", "period", "type"], + ), + ], +) +def test_ipython_completes_the_attributes_of_the_trained_kernel( + mock_session, + mock_predictor_metadata, + mock_predictor_train_job, + kernel, + hyperparameters, + expected, +): + pytest.importorskip("IPython") + from IPython.core.completer import provisionalcompleter + from IPython.core.interactiveshell import InteractiveShell + + model = _gp( + mock_session, + mock_predictor_metadata, + mock_predictor_train_job, + kernel, + hyperparameters, + ) + shell = InteractiveShell.instance() + shell.user_ns["predictor"] = model + text = "predictor.kernel." + with provisionalcompleter(): + completions = { + c.text.rsplit(".", 1)[-1] + for c in shell.Completer.completions(text, len(text)) + } + + assert ( + sorted(completions & {"lengthscale", "outputscale", "period", "alpha", "type"}) + == expected + ) diff --git a/tests/predictor/test_predictor_schemas.py b/tests/predictor/test_predictor_schemas.py index 6830cf2..0ea34ea 100644 --- a/tests/predictor/test_predictor_schemas.py +++ b/tests/predictor/test_predictor_schemas.py @@ -6,6 +6,11 @@ from openprotein.common import FeatureType from openprotein.jobs import JobStatus, JobType +from openprotein.models.kernels import ( + LinearKernel, + _GPHyperparameters, + _trained_kernel, +) from openprotein.predictor.schemas import ( Dataset, Features, @@ -19,8 +24,34 @@ ) +@pytest.mark.parametrize( + "kernel,served", + [ + ("linear", {"outputscale": [2.0, 3.0]}), + ("linear", {"lengthscale": [None, 0.8]}), + ("linear", {"alpha": [None, 1.2]}), + ("rbf", {"lengthscale": [0.8], "period": [2.0, 3.0]}), + ("rbf", {"lengthscale": [0.8, 0.9]}), + ("rbf", {"lengthscale": []}), + ], +) +def test_trained_kernel_takes_exactly_one_kernel(kernel, served): + hyperparameters = _GPHyperparameters(**({"outputscale": [2.0]} | served)) + + with pytest.raises(ValueError, match="expected one"): + _trained_kernel(kernel, hyperparameters) + + +@pytest.mark.parametrize( + "served", [{}, {"lengthscale": [None], "period": [None], "alpha": [None]}] +) +def test_inapplicable_hyperparameters_may_be_empty_or_null(served): + hyperparameters = _GPHyperparameters(outputscale=[2.0], **served) + + assert _trained_kernel("linear", hyperparameters) == LinearKernel(outputscale=2.0) + + def test_predictor_metadata_is_done(): - """Test the is_done() method on PredictorMetadata.""" spec = ModelSpec(type=PredictorType.GP) dataset = Dataset(assay_id="a1", properties=["p1"]) metadata_done = PredictorMetadata( @@ -46,7 +77,6 @@ def test_predictor_metadata_is_done(): ], ) def test_job_schemas_job_type(job_class, expected_job_type): - """Test that each job schema has the correct job_type.""" job_data = { "job_id": "job-123", "status": JobStatus.SUCCESS, @@ -58,7 +88,6 @@ def test_job_schemas_job_type(job_class, expected_job_type): def test_features_schema(): - """Test the Features schema validation.""" # This should pass Features(type=FeatureType.PLM, model_id="model-1", reduction="mean") Features(type=FeatureType.SVD, model_id="model-1", reduction="mean") diff --git a/tests/prompt/test_prompt.py b/tests/prompt/test_prompt.py index 55944de..3b9cc82 100644 --- a/tests/prompt/test_prompt.py +++ b/tests/prompt/test_prompt.py @@ -1,4 +1,5 @@ """L2 integration tests for the prompt domain.""" + from datetime import datetime from unittest.mock import MagicMock @@ -12,13 +13,11 @@ @pytest.fixture def prompt_api(mock_session: MagicMock): - """Fixture to create a PromptAPI instance.""" return PromptAPI(mock_session) @pytest.fixture def mock_prompt_job(): - """Fixture for a valid PromptJob instance.""" return PromptJob( job_id="job-123", status=JobStatus.SUCCESS, @@ -28,7 +27,6 @@ def mock_prompt_job(): def test_create_prompt(prompt_api: PromptAPI, mock_session: MagicMock, mock_prompt_job): - """Test the create_prompt method.""" mock_session.post.return_value.status_code = 200 mock_session.post.return_value.json.return_value = { "id": "prompt-123", @@ -49,7 +47,6 @@ def test_create_prompt(prompt_api: PromptAPI, mock_session: MagicMock, mock_prom def test_get_prompt(prompt_api: PromptAPI, mock_session: MagicMock, mock_prompt_job): - """Test the get_prompt method.""" mock_session.get.return_value.status_code = 200 mock_session.get.return_value.json.return_value = { "id": "prompt-123", @@ -69,7 +66,6 @@ def test_get_prompt(prompt_api: PromptAPI, mock_session: MagicMock, mock_prompt_ def test_create_query(prompt_api: PromptAPI, mock_session: MagicMock): - """Test the create_query method.""" mock_session.post.return_value.status_code = 200 mock_session.post.return_value.json.return_value = { "id": "query-123", @@ -80,3 +76,23 @@ def test_create_query(prompt_api: PromptAPI, mock_session: MagicMock): mock_session.post.assert_called_once() assert isinstance(query, Query) assert query.id == "query-123" + + +class TestResolveQueryIds: + """Text in the hyphenated id form names a query, in any case and as str or bytes.""" + + UPPER = "C9BF9E57-1685-4C89-BAFB-FF5AF830BE8A" + LOWER = UPPER.lower() + + @pytest.mark.parametrize("value", [UPPER, LOWER, UPPER.encode()]) + def test_an_id_is_sent_lower_cased_without_an_upload(self, mock_session, value): + api = PromptAPI(mock_session) + api.create_query = MagicMock() + assert api._resolve_query(query=value) == self.LOWER + api.create_query.assert_not_called() + + def test_a_sequence_is_uploaded(self, mock_session): + api = PromptAPI(mock_session) + api.create_query = MagicMock() + api.create_query.return_value.id = "q-1" + assert api._resolve_query(query="ACDE") == "q-1" diff --git a/tests/prompt/test_prompt_api.py b/tests/prompt/test_prompt_api.py index b7e71de..71020d3 100644 --- a/tests/prompt/test_prompt_api.py +++ b/tests/prompt/test_prompt_api.py @@ -3,6 +3,7 @@ from pathlib import Path from unittest.mock import MagicMock +import numpy as np import pytest from openprotein.errors import APIError, InvalidParameterError @@ -11,9 +12,9 @@ from openprotein.prompt.api import ( _assert_protein_only, _coerce_sequence, + _get_query_as_complex, create_prompt, create_query, - get_prompt, get_prompt_metadata, get_query, get_query_metadata, @@ -38,13 +39,10 @@ def multichain_complex_with_structure( ) -> Complex: c2 = Complex.from_filepath(str(DATA_DIR / "9bkq-assembly2.cif"), verbose=False) other = next(iter(c2.get_proteins().values())) - return Complex( - {"A": single_chain_protein_with_structure, "B": other}, name="duo" - ) + return Complex({"A": single_chain_protein_with_structure, "B": other}, name="duo") def test_create_prompt(mock_session: MagicMock): - """Test the create_prompt function.""" mock_session.post.return_value.status_code = 200 mock_session.post.return_value.json.return_value = { "id": "prompt-123", @@ -63,7 +61,6 @@ def test_create_prompt(mock_session: MagicMock): def test_get_prompt_metadata(mock_session: MagicMock): - """Test the get_prompt_metadata function.""" mock_session.get.return_value.status_code = 200 mock_session.get.return_value.json.return_value = { "id": "prompt-123", @@ -81,7 +78,6 @@ def test_get_prompt_metadata(mock_session: MagicMock): def test_list_prompts(mock_session: MagicMock): - """Test the list_prompts function.""" mock_session.get.return_value.status_code = 200 mock_session.get.return_value.json.return_value = [ { @@ -108,7 +104,6 @@ def test_list_prompts(mock_session: MagicMock): def test_create_query(mock_session: MagicMock): - """Test the create_query function.""" mock_session.post.return_value.status_code = 200 mock_session.post.return_value.json.return_value = { "id": "query-123", @@ -124,7 +119,6 @@ def test_create_query(mock_session: MagicMock): def test_get_query_metadata(mock_session: MagicMock): - """Test the get_query_metadata function.""" mock_session.get.return_value.status_code = 200 mock_session.get.return_value.json.return_value = { "id": "query-123", @@ -139,7 +133,6 @@ def test_get_query_metadata(mock_session: MagicMock): def test_api_error_handling(mock_session: MagicMock): - """Test that APIError is raised for non-200 status codes.""" mock_session.get.return_value.status_code = 404 mock_session.get.return_value.json.return_value = {"detail": "Not Found"} @@ -148,7 +141,6 @@ def test_api_error_handling(mock_session: MagicMock): def test_invalid_parameter_error(mock_session: MagicMock): - """Test that InvalidParameterError is raised for 400 status code.""" mock_session.post.return_value.status_code = 400 mock_session.post.return_value.json.return_value = {"detail": "Invalid parameters"} @@ -156,9 +148,6 @@ def test_invalid_parameter_error(mock_session: MagicMock): create_prompt(mock_session, context=["ACGT"], name="Invalid Prompt") -# ---------- multichain support ---------- - - class TestCoerceSequence: def test_single_chain_returns_protein(self): result = _coerce_sequence("foo", "ACDE") @@ -277,6 +266,29 @@ def test_empty_chain_slot_survives_the_roundtrip(self): assert isinstance(entry, Complex) assert [p.sequence for p in entry.get_proteins().values()] == [b"", b"GHIK"] + def test_only_context_n_members_are_ordered_by_position(self): + """``context-.zip`` members sort by ``n``; other names follow in archive order.""" + import io + import zipfile + + zips = zip_prompt([["A"], ["AA"], ["AAA"], ["AAAA"], ["AAAAA"]]) + members = { + "context-v2-0.zip": 3, + "context-10.zip": 2, + "context-x.zip": 4, + "context-2.zip": 1, + "context-1.zip": 0, + } + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w") as archive: + for name, source in members.items(): + archive.writestr(name, zips[source].getvalue()) + buf.seek(0) + + result = unzip_prompt(buf) + + assert [len(entries[0].sequence) for entries in result] == [1, 2, 3, 4, 5] + def test_raw_string_with_colon_returns_complex(self): zips = zip_prompt(["ACDE:GHIK"]) outer = self._wrap(zips) @@ -451,12 +463,7 @@ def test_protein_force_structure_true_promotes_to_cif( class TestGetQueryMultichain: def test_multichain_fasta_response_returns_complex(self, mock_session: MagicMock): - """get_query must parse ':' chain breaks in FASTA responses into a Complex. - - Regression: previously this branch called ``Protein(name, sequence)`` - directly, which raised AssertionError because ':' isn't a valid amino - acid character. - """ + """get_query must parse ':' chain breaks in FASTA responses into a Complex.""" mock_session.get.return_value.status_code = 200 mock_session.get.return_value.content = b">my-query\nACDE:GHIK\n" mock_session.get.return_value.headers = { @@ -468,10 +475,8 @@ def test_multichain_fasta_response_returns_complex(self, mock_session: MagicMock seqs = sorted(p.sequence for p in result.get_proteins().values()) assert seqs == [b"ACDE", b"GHIK"] - def test_single_chain_fasta_response_returns_protein( - self, mock_session: MagicMock - ): - """Single-chain FASTA responses still collapse to Protein.""" + def test_single_chain_fasta_response_returns_protein(self, mock_session: MagicMock): + """Single-chain FASTA responses collapse to Protein.""" mock_session.get.return_value.status_code = 200 mock_session.get.return_value.content = b">my-query\nACDEFGHIK\n" mock_session.get.return_value.headers = { @@ -482,14 +487,14 @@ def test_single_chain_fasta_response_returns_protein( assert isinstance(result, Protein) assert result.sequence == b"ACDEFGHIK" - @pytest.mark.parametrize("status_code,detail", [(401, "Unauthorized"), (404, "Not Found")]) - def test_error_status_surfaces_detail_not_file_format_error( + @pytest.mark.parametrize( + "status_code,detail", [(401, "Unauthorized"), (404, "Not Found")] + ) + def test_error_status_surfaces_detail( self, mock_session: MagicMock, status_code: int, detail: str ): - """Regression: error responses must dispatch on status code before parsing - the body as a query file. Previously this raised an opaque - ``APIError("Unexpected file returned…")`` for 401/404 because file-format - parsing ran first.""" + """An error response dispatches on its status code before the body is + parsed as a query file, so the server's detail reaches the caller.""" mock_session.get.return_value.status_code = status_code mock_session.get.return_value.json.return_value = {"detail": detail} mock_session.get.return_value.headers = { @@ -534,6 +539,54 @@ def test_single_chain_cif_response_returns_protein( assert isinstance(result, Protein) +class TestGetQueryAsComplex: + def test_single_chain_mmcif_keeps_chain_id( + self, + mock_session: MagicMock, + single_chain_protein_with_structure: Protein, + ): + """A single-chain mmCIF upload whose chain isn't 'A' keeps its id.""" + c = Complex({"B": single_chain_protein_with_structure}, name="q") + cif_bytes = c.to_string("cif").encode() + mock_session.get.return_value.status_code = 200 + mock_session.get.return_value.content = cif_bytes + mock_session.get.return_value.headers = { + "Content-Disposition": "attachment; filename=query.cif", + "Content-Type": "chemical/x-mmcif", + } + result = _get_query_as_complex(mock_session, "query-789") + assert isinstance(result, Complex) + assert set(result.get_chains().keys()) == {"B"} + + def test_single_chain_fasta_wraps_as_a(self, mock_session: MagicMock): + """A FASTA query has no chain id, so it's wrapped as 'A'.""" + mock_session.get.return_value.status_code = 200 + mock_session.get.return_value.content = b">my-query\nACDEFGHIK\n" + mock_session.get.return_value.headers = { + "Content-Disposition": "attachment; filename=query.fasta", + "Content-Type": "text/x-fasta", + } + result = _get_query_as_complex(mock_session, "query-789") + assert isinstance(result, Complex) + assert set(result.get_chains().keys()) == {"A"} + + def test_multichain_mmcif_unchanged( + self, + mock_session: MagicMock, + multichain_complex_with_structure: Complex, + ): + cif_bytes = multichain_complex_with_structure.to_string("cif").encode() + mock_session.get.return_value.status_code = 200 + mock_session.get.return_value.content = cif_bytes + mock_session.get.return_value.headers = { + "Content-Disposition": "attachment; filename=query.cif", + "Content-Type": "chemical/x-mmcif", + } + result = _get_query_as_complex(mock_session, "query-789") + assert isinstance(result, Complex) + assert len(result.get_proteins()) == 2 + + class TestParseFastaAsProteins: def test_emits_future_warning_on_single_chain(self, tmp_path: Path): path = tmp_path / "single.fasta" @@ -553,3 +606,36 @@ def test_raises_on_multichain(self, tmp_path: Path): with pytest.warns(FutureWarning): with pytest.raises(ValueError, match="chain break"): parse_fasta_as_proteins(path) + + +class TestGetQueryPDB: + """The prompt service serves an uploaded .pdb query as ``chemical/x-pdb``.""" + + @pytest.mark.parametrize( + "headers", + [ + { + "Content-Disposition": "attachment; filename=query.pdb", + "Content-Type": "chemical/x-pdb", + }, + {"Content-Disposition": "attachment; filename=query.pdb"}, + {"Content-Type": "chemical/x-pdb"}, + ], + ) + def test_pdb_response_parses_as_a_complex( + self, mock_session: MagicMock, headers: dict[str, str] + ): + pdb = (DATA_DIR / "1GCM.pdb").read_bytes() + mock_session.get.return_value.status_code = 200 + mock_session.get.return_value.content = pdb + mock_session.get.return_value.headers = headers + expected = Complex.from_string(pdb, format="pdb", verbose=False) + + result = _get_query_as_complex(mock_session, "query-789") + + assert isinstance(result, Complex) + assert list(result.get_proteins()) == list(expected.get_proteins()) + for chain_id, protein in expected.get_proteins().items(): + served = result.get_proteins()[chain_id] + assert served.sequence == protein.sequence + np.testing.assert_array_equal(served.coordinates, protein.coordinates) diff --git a/tests/prompt/test_prompt_models.py b/tests/prompt/test_prompt_models.py index 50ddfb4..0d19d2f 100644 --- a/tests/prompt/test_prompt_models.py +++ b/tests/prompt/test_prompt_models.py @@ -1,18 +1,16 @@ -from openprotein.jobs import JobsAPI from datetime import datetime from unittest.mock import MagicMock, patch import pytest from openprotein.errors import InvalidParameterError -from openprotein.jobs import JobStatus, JobType +from openprotein.jobs import Future, Job, JobsAPI, JobStatus, JobType from openprotein.molecules import Complex, Protein from openprotein.prompt import Prompt, PromptJob, PromptMetadata, Query, QueryMetadata @pytest.fixture def mock_session(prompt_job): - """Fixture to create a mock APISession.""" session = MagicMock() session.jobs = MagicMock(spec=JobsAPI) session.jobs.get_job.return_value = prompt_job @@ -21,7 +19,6 @@ def mock_session(prompt_job): @pytest.fixture def prompt_metadata(): - """Fixture for PromptMetadata.""" return PromptMetadata( id="prompt-123", name="Test Prompt", @@ -35,7 +32,6 @@ def prompt_metadata(): @pytest.fixture def prompt_job(): - """Fixture for PromptJob.""" return PromptJob( job_id="job-123", job_type=JobType.align_prompt, @@ -46,7 +42,6 @@ def prompt_job(): @pytest.fixture def query_metadata(): - """Fixture for QueryMetadata.""" return QueryMetadata( id="query-123", created_date=datetime.now(), @@ -54,7 +49,6 @@ def query_metadata(): def test_prompt_initialization_with_metadata(mock_session, prompt_metadata, prompt_job): - """Test Prompt initialization using PromptMetadata.""" mock_session.jobs.get_job.return_value = prompt_job prompt = Prompt(session=mock_session, metadata=prompt_metadata) assert prompt.id == "prompt-123" @@ -63,7 +57,6 @@ def test_prompt_initialization_with_metadata(mock_session, prompt_metadata, prom def test_prompt_initialization_with_job(mock_session, prompt_job, prompt_metadata): - """Test Prompt initialization using a PromptJob.""" with patch( "openprotein.prompt.api.get_prompt_metadata", return_value=prompt_metadata ): @@ -74,7 +67,6 @@ def test_prompt_initialization_with_job(mock_session, prompt_job, prompt_metadat @patch("openprotein.prompt.api.get_prompt") def test_prompt_get(mock_get_prompt, mock_session, prompt_metadata): - """Test the get method of the Prompt class.""" mock_get_prompt.return_value = "Prompt Content" prompt = Prompt(session=mock_session, metadata=prompt_metadata) content = prompt.get() @@ -82,15 +74,64 @@ def test_prompt_get(mock_get_prompt, mock_session, prompt_metadata): assert content == "Prompt Content" +def test_an_align_prompt_job_loads_as_a_prompt(mock_session, prompt_metadata): + payload = { + "job_id": "job-123", + "job_type": "/align/prompt", + "status": "SUCCESS", + "created_date": datetime.now().isoformat(), + } + mock_session.get.return_value.json.return_value = payload + mock_session.jobs.get_job.return_value = Job.create(payload) + + with patch( + "openprotein.prompt.api.get_prompt_metadata", return_value=prompt_metadata + ): + future = Future.create(session=mock_session, job_id="job-123") + + assert isinstance(future, Prompt) + assert isinstance(future.job, PromptJob) + + +@pytest.mark.parametrize("update", ["refresh", "wait_until_done"]) +def test_the_metadata_reports_the_status_of_the_refreshed_job( + mock_session, prompt_metadata, prompt_job, update +): + mock_session.jobs.get_job.return_value = prompt_job.model_copy( + update={"status": JobStatus.PENDING} + ) + prompt = Prompt( + session=mock_session, + metadata=prompt_metadata.model_copy(update={"status": JobStatus.PENDING}), + ) + mock_session.get.return_value.json.return_value = prompt_job.model_dump(mode="json") + + getattr(prompt, update)() + + assert prompt.status == JobStatus.SUCCESS + assert prompt.metadata.status == JobStatus.SUCCESS + assert repr(prompt).startswith("Prompt(id='prompt-123'") + assert "SUCCESS" in repr(prompt) + + +def test_a_prompt_refresh_passes_its_timeout_to_the_poll( + mock_session, prompt_metadata, prompt_job +): + prompt = Prompt(session=mock_session, metadata=prompt_metadata) + mock_session.get.return_value.json.return_value = prompt_job.model_dump(mode="json") + + prompt._refresh_job(timeout=2) + + assert mock_session.get.call_args.kwargs == {"timeout": 2} + + def test_query_initialization(mock_session, query_metadata): - """Test Query initialization.""" query = Query(session=mock_session, metadata=query_metadata) assert query.id == "query-123" @patch("openprotein.prompt.api.get_query") def test_query_get(mock_get_query, mock_session, query_metadata): - """Test the get method of the Query class.""" mock_get_query.return_value = "Query Content" query = Query(session=mock_session, metadata=query_metadata) content = query.get() @@ -98,9 +139,6 @@ def test_query_get(mock_get_query, mock_session, query_metadata): assert content == "Query Content" -# ---------- multichain typed accessors ---------- - - @patch("openprotein.prompt.api.get_prompt") def test_prompt_get_as_complexes_wraps_proteins( mock_get_prompt, mock_session, prompt_metadata @@ -139,23 +177,27 @@ def test_prompt_get_as_proteins_passthrough_when_all_single( assert result == [[p]] -@patch("openprotein.prompt.api.get_query") +@patch("openprotein.prompt.api._get_query_as_complex") def test_query_get_as_complex_wraps_protein( - mock_get_query, mock_session, query_metadata + mock_get_query_as_complex, mock_session, query_metadata ): - """A Protein result is wrapped as Complex.""" - p = Protein(name="q", sequence=b"ACDE") - mock_get_query.return_value = p + """Delegates to api._get_query_as_complex.""" + c = Complex({"A": Protein(name="q", sequence=b"ACDE")}) + mock_get_query_as_complex.return_value = c query = Query(session=mock_session, metadata=query_metadata) result = query.get_as_complex() - assert isinstance(result, Complex) - assert len(result.get_proteins()) == 1 + assert result is c + mock_get_query_as_complex.assert_called_with( + session=mock_session, query_id="query-123" + ) -@patch("openprotein.prompt.api.get_query") -def test_query_get_as_complex_passthrough(mock_get_query, mock_session, query_metadata): +@patch("openprotein.prompt.api._get_query_as_complex") +def test_query_get_as_complex_passthrough( + mock_get_query_as_complex, mock_session, query_metadata +): c = Complex({"A": Protein(sequence=b"ACDE"), "B": Protein(sequence=b"GHIK")}) - mock_get_query.return_value = c + mock_get_query_as_complex.return_value = c query = Query(session=mock_session, metadata=query_metadata) assert query.get_as_complex() is c @@ -177,3 +219,25 @@ def test_query_get_as_protein_passthrough(mock_get_query, mock_session, query_me mock_get_query.return_value = p query = Query(session=mock_session, metadata=query_metadata) assert query.get_as_protein() is p + + +@pytest.fixture +def uploaded_prompt(mock_session, prompt_metadata): + return Prompt( + session=mock_session, + metadata=prompt_metadata.model_copy(update={"job_id": None}), + ) + + +def test_a_prompt_does_not_rename(mock_session, prompt_metadata): + prompt = Prompt(session=mock_session, metadata=prompt_metadata) + + with pytest.raises(NotImplementedError, match="set when it is created"): + prompt.rename(name="other") + mock_session.put.assert_not_called() + + +def test_an_uploaded_prompt_does_not_rename(mock_session, uploaded_prompt): + with pytest.raises(NotImplementedError, match="set when it is created"): + uploaded_prompt.rename(name="other") + mock_session.put.assert_not_called() diff --git a/tests/prompt/test_prompt_schemas.py b/tests/prompt/test_prompt_schemas.py index e998b72..f3f4145 100644 --- a/tests/prompt/test_prompt_schemas.py +++ b/tests/prompt/test_prompt_schemas.py @@ -8,20 +8,30 @@ def test_prompt_job_schema(): - """Test successful creation of a PromptJob.""" job_data = { "job_id": "prompt-123", "job_type": JobType.align_prompt, "status": JobStatus.SUCCESS, "created_date": datetime.now(), } - job = PromptJob(**job_data) + job = PromptJob.model_validate(job_data) assert job.job_id == "prompt-123" assert job.prompt_id == "prompt-123" +def test_prompt_job_msa_id_is_the_jobs_msa_id_when_it_carries_one(): + job_data = { + "job_id": "prompt-123", + "job_type": "/prompt/sample_msa", + "status": JobStatus.SUCCESS, + "created_date": datetime.now(), + } + + assert PromptJob.model_validate(job_data).msa_id is None + assert PromptJob.model_validate({**job_data, "msa_id": "msa-1"}).msa_id == "msa-1" + + def test_prompt_metadata_schema(): - """Test successful creation of PromptMetadata.""" metadata_data = { "id": "prompt-meta-123", "name": "Test Prompt", @@ -37,7 +47,6 @@ def test_prompt_metadata_schema(): def test_prompt_metadata_schema_optional_fields(): - """Test PromptMetadata with optional fields omitted.""" metadata_data = { "id": "prompt-meta-456", "name": "Another Test Prompt", @@ -51,7 +60,6 @@ def test_prompt_metadata_schema_optional_fields(): def test_prompt_metadata_validation_error(): - """Test validation error for missing required fields in PromptMetadata.""" with pytest.raises(ValidationError): PromptMetadata( id="prompt-meta-789", @@ -63,7 +71,6 @@ def test_prompt_metadata_validation_error(): def test_query_metadata_schema(): - """Test successful creation of QueryMetadata.""" query_data = { "id": "query-123", "created_date": datetime.now(), @@ -73,6 +80,5 @@ def test_query_metadata_schema(): def test_query_metadata_validation_error(): - """Test validation error for missing required fields in QueryMetadata.""" with pytest.raises(ValidationError): QueryMetadata(id="query-456") # type: ignore - meant to be missing diff --git a/tests/svd/test_svd.py b/tests/svd/test_svd.py index 4170515..e64bd55 100644 --- a/tests/svd/test_svd.py +++ b/tests/svd/test_svd.py @@ -16,13 +16,11 @@ @pytest.fixture def svd_api(mock_session: MagicMock): - """Fixture to create an SVDAPI instance.""" return SVDAPI(mock_session) @pytest.fixture def mock_svd_fit_job(): - """Fixture for a valid SVDFitJob instance.""" return SVDFitJob( job_id="svd-123", status=JobStatus.SUCCESS, @@ -32,7 +30,6 @@ def mock_svd_fit_job(): def test_list_svd(svd_api: SVDAPI, mock_svd_fit_job): - """Test the list_svd method.""" svd_api.session.jobs = MagicMock(spec=JobsAPI) # type: ignore svd_api.session.jobs.get_job.return_value = mock_svd_fit_job # type: ignore @@ -47,7 +44,6 @@ def test_list_svd(svd_api: SVDAPI, mock_svd_fit_job): def test_get_svd(svd_api: SVDAPI, mock_svd_fit_job): - """Test the get_svd method.""" svd_id = "svd-123" svd_api.session.jobs = MagicMock(spec=JobsAPI) # type: ignore svd_api.session.jobs.get_job.return_value = mock_svd_fit_job # type: ignore @@ -59,9 +55,41 @@ def test_get_svd(svd_api: SVDAPI, mock_svd_fit_job): mock_get.assert_called_once_with(svd_api.session, svd_id) +def test_fit_svd_accepts_a_models_namespace_handle(): + """Both fit paths take a session.models handle without a string lookup.""" + from openprotein.embeddings.poet2 import PoET2Model + from openprotein.prompt import PromptAPI + from openprotein.svd import api as svd_api_module + + session = MagicMock() + session.svd = SVDAPI(session) + session.embedding = EmbeddingsAPI(session) + session.prompt = MagicMock(spec=PromptAPI) + handle = PoET2Model(session, "poet-2", metadata=MagicMock()) + + job = MagicMock(spec=SVDFitJob) + job.job_id = "svd-123" + metadata = SVDMetadata( + id="svd-123", + status=JobStatus.PENDING, + model_id="poet-2", + n_components=1024, + ) + with ( + patch.object(svd_api_module, "svd_fit_post", return_value=job) as fit_post, + patch.object(svd_api_module, "svd_get", return_value=metadata), + ): + via_api = session.svd.fit_svd(model=handle, sequences=[b"ACGT"]) + via_handle = handle.fit_svd(sequences=[b"ACGT"]) + + assert isinstance(via_api, SVDModel) + assert isinstance(via_handle, SVDModel) + assert fit_post.call_count == 2 + assert fit_post.call_args_list[0].kwargs["model_id"] == "poet-2" + + @patch("openprotein.svd.api.svd_get") def test_fit_svd(mock_get, svd_api: SVDAPI, mock_session: MagicMock): - """Test the fit_svd method.""" model_id = "model-1" sequences = [b"ACGT"] diff --git a/tests/svd/test_svd_api.py b/tests/svd/test_svd_api.py index 34e177b..27b5e40 100644 --- a/tests/svd/test_svd_api.py +++ b/tests/svd/test_svd_api.py @@ -12,7 +12,6 @@ def test_svd_list_get(mock_session: MagicMock): - """Test svd_list_get.""" mock_session.get.return_value.json.return_value = [ { "id": "svd-1", @@ -28,7 +27,6 @@ def test_svd_list_get(mock_session: MagicMock): def test_svd_list_get_with_pagination(mock_session: MagicMock): - """Test svd_list_get with limit and offset.""" mock_session.get.return_value.json.return_value = [ { "id": "svd-1", @@ -46,7 +44,6 @@ def test_svd_list_get_with_pagination(mock_session: MagicMock): def test_svd_get(mock_session: MagicMock): - """Test svd_get.""" mock_session.get.return_value.json.return_value = { "id": "svd-1", "status": "SUCCESS", @@ -59,7 +56,6 @@ def test_svd_get(mock_session: MagicMock): def test_svd_delete(mock_session: MagicMock): - """Test svd_delete.""" mock_session.delete.return_value.status_code = 200 result = api.svd_delete(mock_session, "svd-1") mock_session.delete.assert_called_once_with("v1/embeddings/svd/svd-1") @@ -67,7 +63,6 @@ def test_svd_delete(mock_session: MagicMock): def test_svd_fit_post_with_sequences(mock_session: MagicMock): - """Test svd_fit_post with sequences.""" mock_session.post.return_value.json.return_value = { "job_id": "job-123", "job_type": JobType.svd_fit.value, @@ -82,7 +77,6 @@ def test_svd_fit_post_with_sequences(mock_session: MagicMock): def test_svd_fit_post_with_assay_id(mock_session: MagicMock): - """Test svd_fit_post with an assay_id.""" mock_session.post.return_value.json.return_value = { "job_id": "job-123", "job_type": JobType.svd_fit.value, @@ -97,7 +91,6 @@ def test_svd_fit_post_with_assay_id(mock_session: MagicMock): def test_svd_fit_post_invalid_params(mock_session: MagicMock): - """Test svd_fit_post with invalid parameters.""" with pytest.raises(InvalidParameterError): api.svd_fit_post(mock_session, "model-1") # Neither sequences nor assay_id with pytest.raises(InvalidParameterError): @@ -107,7 +100,6 @@ def test_svd_fit_post_invalid_params(mock_session: MagicMock): def test_embed_decode(): - """Test embed_decode.""" arr = np.array([1.0, 2.0, 3.0]) # The api uses np.save, which includes a header. # We need to create the bytes in the same way. diff --git a/tests/svd/test_svd_models.py b/tests/svd/test_svd_models.py index d8a6fd6..6366023 100644 --- a/tests/svd/test_svd_models.py +++ b/tests/svd/test_svd_models.py @@ -12,7 +12,6 @@ @pytest.fixture def mock_svd_metadata(): - """Fixture for SVDMetadata.""" return SVDMetadata( id="svd-123", status=JobStatus.SUCCESS, @@ -23,7 +22,6 @@ def mock_svd_metadata(): @pytest.fixture def mock_svd_fit_job(): - """Fixture for a valid SVDFitJob instance.""" return SVDFitJob( job_id="svd-123", status=JobStatus.SUCCESS, @@ -35,7 +33,6 @@ def mock_svd_fit_job(): def test_svd_model_init_with_metadata( mock_session: MagicMock, mock_svd_metadata, mock_svd_fit_job ): - """Test SVDModel initialization with metadata.""" mock_session.jobs = MagicMock(spec=JobsAPI) # type: ignore mock_session.jobs.get_job.return_value = mock_svd_fit_job # type: ignore model = SVDModel(session=mock_session, metadata=mock_svd_metadata) @@ -46,7 +43,6 @@ def test_svd_model_init_with_metadata( def test_svd_model_init_with_job( mock_session: MagicMock, mock_svd_fit_job, mock_svd_metadata ): - """Test SVDModel initialization with a job object.""" with patch( "openprotein.svd.api.svd_get", return_value=mock_svd_metadata ) as mock_api_get: @@ -58,7 +54,6 @@ def test_svd_model_init_with_job( def test_svd_model_embed(mock_session: MagicMock, mock_svd_metadata, mock_svd_fit_job): - """Test the embed method of SVDModel.""" mock_session.jobs = MagicMock(spec=JobsAPI) # type: ignore mock_session.jobs.get_job.return_value = mock_svd_fit_job # type: ignore model = SVDModel(session=mock_session, metadata=mock_svd_metadata) @@ -84,7 +79,6 @@ def test_svd_model_embed(mock_session: MagicMock, mock_svd_metadata, mock_svd_fi def test_svd_embedding_result_future_get_item(mock_session: MagicMock): - """Test the get_item override in SVDEmbeddingResultFuture.""" mock_job = MagicMock(spec=SVDEmbeddingsJob) mock_job.job_id = "job-456" future = SVDEmbeddingsResultFuture(session=mock_session, job=mock_job) diff --git a/tests/svd/test_svd_schemas.py b/tests/svd/test_svd_schemas.py index f314c42..57d339f 100644 --- a/tests/svd/test_svd_schemas.py +++ b/tests/svd/test_svd_schemas.py @@ -10,7 +10,6 @@ def test_svd_metadata_is_done(): - """Test the is_done() method on SVDMetadata.""" metadata_done = SVDMetadata( id="svd-1", status=JobStatus.SUCCESS, @@ -35,7 +34,6 @@ def test_svd_metadata_is_done(): ], ) def test_job_schemas_job_type(job_class, expected_job_type): - """Test that each job schema has the correct job_type.""" job_data = { "job_id": "job-123", "status": JobStatus.SUCCESS, @@ -47,7 +45,6 @@ def test_job_schemas_job_type(job_class, expected_job_type): def test_svd_job_schema_invalid_job_type(): - """Test that validation fails for an incorrect job_type.""" job_data = { "job_id": "job-123", "status": JobStatus.SUCCESS, @@ -55,4 +52,4 @@ def test_svd_job_schema_invalid_job_type(): "job_type": "some_other_type", # Invalid job type } with pytest.raises(ValidationError): - SVDFitJob(**job_data) + SVDFitJob.model_validate(job_data) diff --git a/tests/test_auth.py b/tests/test_auth.py index 5f57991..d2edd2e 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -51,17 +51,19 @@ def test_corrupt_file_treated_as_no_record(store, tmp_path): def test_identity_scoping_is_independent(store): - dev = store.identity("https://dev/", "user@x.com") - prod = store.identity("https://prod/", "user@x.com") + first = store.identity("https://first/", "user@x.com") + second = store.identity("https://second/", "user@x.com") store.save( - dev, TokenRecord(access_token="dev-a", refresh_token="dev-r", expires_at=1.0) + first, + TokenRecord(access_token="first-a", refresh_token="first-r", expires_at=1.0), ) store.save( - prod, TokenRecord(access_token="prod-a", refresh_token="prod-r", expires_at=2.0) + second, + TokenRecord(access_token="second-a", refresh_token="second-r", expires_at=2.0), ) - assert store.load(dev).access_token == "dev-a" - assert store.load(prod).access_token == "prod-a" + assert store.load(first).access_token == "first-a" + assert store.load(second).access_token == "second-a" def test_save_preserves_other_identities(store, tmp_path): @@ -81,9 +83,7 @@ def test_lock_is_reentrant(store): pass -# --------------------------------------------------------------------------- # APISession login behavior tests -# --------------------------------------------------------------------------- BACKEND = "https://test-backend/" @@ -203,11 +203,7 @@ def test_login_non404_error_raises_autherror(isolated_store): APISession("user@x.com", "pw", backend=BACKEND) -# --------------------------------------------------------------------------- # Session init adoption tests -# --------------------------------------------------------------------------- - - def test_init_adopts_stored_record_without_login(isolated_store): # Seed the store with a valid record for this identity. TokenStore(dir=isolated_store).save( @@ -250,9 +246,7 @@ def test_init_logs_in_when_stored_record_has_no_refresh_token(isolated_store): assert session.auth._token == "fresh-access" -# --------------------------------------------------------------------------- # _refresh / _relogin tests -# --------------------------------------------------------------------------- def _logged_in_session( @@ -353,7 +347,7 @@ def test_refresh_relogin_failure_raises_autherror(isolated_store): def test_refresh_403_triggers_relogin(isolated_store): - # Some Keycloak deployments return 403 (not 401) for an expired session. + # Some identity providers answer an expired session with 403 rather than 401. session = _logged_in_session(isolated_store) relogin_resp = _resp( json_body={ @@ -374,9 +368,8 @@ def test_refresh_403_triggers_relogin(isolated_store): def test_refresh_404_triggers_relogin(isolated_store): - # A backend that issued a refresh token but no longer exposes /auth/refresh - # (e.g. mid-rollback) returns 404; recover by re-logging-in rather than - # surfacing a raw 404. Re-login itself drops to legacy mode if needed. + # A backend that issued a refresh token but does not serve /auth/refresh + # answers 404; recover by re-logging in, dropping to legacy mode if needed. session = _logged_in_session(isolated_store) relogin_resp = _resp( json_body={ @@ -425,9 +418,7 @@ def test_refresh_without_refresh_token_falls_back_to_relogin(isolated_store): assert session.auth._token == "relogin-access" -# --------------------------------------------------------------------------- # request() proactive + reactive refresh tests -# --------------------------------------------------------------------------- def test_proactive_refresh_fires_within_skew(isolated_store): diff --git a/tests/test_base.py b/tests/test_base.py index ffc2fca..4b99118 100644 --- a/tests/test_base.py +++ b/tests/test_base.py @@ -1,9 +1,16 @@ import io +import threading +import time +import warnings +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from unittest.mock import MagicMock, patch import pytest -from openprotein.base import APISession, AuthError, BearerAuth +import requests +from openprotein.base import APISession, AuthError, BearerAuth, CloudFrontError +from openprotein.base import TimeoutError as GatewayTimeoutError +from openprotein.errors import HTTPError from tests.conf import BACKEND @@ -93,3 +100,225 @@ def test_APISession_authenticate_successful(response_mock_authenticated): headers={"X-Token-Delivery": "body"}, timeout=3, ) + + +@pytest.fixture +def session(tmp_path, monkeypatch): + from openprotein import auth_store + + monkeypatch.setattr( + "openprotein.base.TokenStore", + lambda *a, **k: auth_store.TokenStore(dir=tmp_path), + ) + login = MagicMock(status_code=200, ok=True, headers={}) + login.json.return_value = { + "access_token": "access", + "refresh_token": "refresh", + "expires_in": 900, + } + with patch.object(APISession, "post", return_value=login): + session = APISession("user@x.com", "pw", backend=BACKEND) + session._expires_at = time.time() + 10_000 + return session + + +def _answer(status: int, headers: dict[str, str]) -> MagicMock: + response = MagicMock(status_code=status, ok=status < 400, headers=headers, text="") + response.url = "u" + return response + + +DEPRECATED = { + "Deprecation": "true", + "Warning": '299 - "POST /align/prompt is deprecated; use POST /prompt/sample_msa"', +} + + +def test_a_deprecated_call_warns_with_the_servers_text(session): + deprecated = _answer(200, DEPRECATED) + with ( + patch.object(requests.Session, "request", return_value=deprecated), + pytest.warns(FutureWarning) as caught, + ): + session.request("POST", "v1/align/prompt") + assert [str(w.message) for w in caught] == [ + "POST /align/prompt is deprecated; use POST /prompt/sample_msa" + ] + + +def test_a_failed_deprecated_call_warns_before_raising(session): + missing = _answer(404, DEPRECATED) + with ( + patch.object(requests.Session, "request", return_value=missing), + pytest.warns(FutureWarning, match="deprecated"), + pytest.raises(HTTPError), + ): + session.request("POST", "v1/align/prompt") + + +@pytest.mark.parametrize( + "headers", + [{}, {"Warning": '199 - "transient"'}, {"Warning": "299 - unquoted"}], + ids=["none", "other-code", "malformed"], +) +def test_other_responses_warn_nothing(session, headers): + with ( + patch.object(requests.Session, "request", return_value=_answer(200, headers)), + warnings.catch_warnings(), + ): + warnings.simplefilter("error") + session.request("GET", "v1/jobs") + + +@pytest.mark.parametrize("status", [400, 403, 404]) +def test_an_unsuccessful_status_raises_http_error_whatever_the_server(session, status): + failed = _answer(status, {"Server": "CloudFront"}) + with ( + patch.object(requests.Session, "request", return_value=failed), + pytest.raises(HTTPError) as raised, + ): + session.request("GET", "v1/jobs") + assert raised.value.status_code == status + + +@pytest.mark.parametrize( + "status,error", + [(502, CloudFrontError), (503, CloudFrontError), (504, GatewayTimeoutError)], +) +def test_a_gateway_error_raises_its_own_error(session, status, error): + failed = _answer(status, {"Server": "CloudFront"}) + with ( + patch.object(requests.Session, "request", return_value=failed), + pytest.raises(error), + ): + session.request("GET", "v1/jobs") + + +def test_a_plain_http_backend_retries_a_stalled_read(tmp_path, monkeypatch): + from openprotein import auth_store + + seen = [] + + class Stalls(BaseHTTPRequestHandler): + def do_GET(self): + seen.append(self.path) + if len(seen) == 1: + time.sleep(1) + body = b"{}" + self.send_response(200) + self.send_header("Content-Type", "application/json") + 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), Stalls) + server.daemon_threads = True + threading.Thread(target=server.serve_forever, daemon=True).start() + monkeypatch.setattr( + "openprotein.base.TokenStore", + lambda *a, **k: auth_store.TokenStore(dir=tmp_path), + ) + login = MagicMock(status_code=200, ok=True, headers={}) + login.json.return_value = { + "access_token": "access", + "refresh_token": "refresh", + "expires_in": 900, + } + backend = f"http://127.0.0.1:{server.server_port}/" + try: + with patch.object(APISession, "post", return_value=login): + session = APISession("user@x.com", "pw", backend=backend) + session._expires_at = time.time() + 10_000 + assert session.get("v1/jobs/j", timeout=0.3).status_code == 200 + finally: + server.shutdown() + assert seen == ["/v1/jobs/j", "/v1/jobs/j"] + + +def _retry_responses(status: int, headers: dict[str, str]): + import urllib3 + + def make_request(*args, **kwargs): + return urllib3.HTTPResponse( + body=io.BytesIO(b"{}"), + status=status, + headers=headers, + preload_content=False, + ) + + return make_request + + +@pytest.mark.parametrize( + "status,headers,error", + [ + (503, {"Server": "CloudFront"}, CloudFrontError), + (502, {"Server": "CloudFront"}, CloudFrontError), + (504, {"Server": "CloudFront"}, GatewayTimeoutError), + (500, {}, HTTPError), + (503, {}, HTTPError), + ], +) +def test_a_spent_retry_budget_raises_the_sdks_own_error( + session, status, headers, error +): + """A retryable status that outlasts the retries surfaces as the SDK's error.""" + make_request = MagicMock(side_effect=_retry_responses(status, headers)) + with ( + patch("urllib3.connectionpool.HTTPConnectionPool._make_request", make_request), + patch("urllib3.util.retry.Retry.sleep"), + pytest.raises(error) as raised, + ): + session.request("GET", "v1/jobs/j") + assert not isinstance(raised.value, requests.exceptions.RetryError) + assert make_request.call_count == 5 + + +@pytest.mark.parametrize( + "method,path,attempts", + [ + ("POST", "v1/models/esm2/embed", 5), + ("GET", "v1/models/esm2", 5), + ("POST", "v1/align/msa", 1), + ], +) +def test_a_spent_model_route_budget_raises_the_sdks_error( + session, method, path, attempts +): + """Repeated 503s on a model route surface as the SDK's error, not a retry error.""" + make_request = MagicMock(side_effect=_retry_responses(503, {})) + with ( + patch("urllib3.connectionpool.HTTPConnectionPool._make_request", make_request), + patch("urllib3.util.retry.Retry.sleep"), + pytest.raises(HTTPError) as raised, + ): + session.request(method, path, json={} if method == "POST" else None) + assert not isinstance(raised.value, requests.exceptions.RetryError) + assert make_request.call_count == attempts + + +def test_a_request_without_a_timeout_uses_the_session_timeout(session): + """Every method sends the session timeout unless the caller passes one.""" + session.timeout = 42 + with patch.object( + requests.Session, "request", return_value=_answer(200, {}) + ) as send: + session.get("v1/jobs/j") + session.put("v1/jobs/j", json={}) + session.delete("v1/jobs/j") + assert [call.kwargs["timeout"] for call in send.call_args_list] == [42, 42, 42] + + +@pytest.mark.parametrize("timeout", [7, None]) +def test_an_explicit_timeout_wins_over_the_session_timeout(session, timeout): + """A timeout passed to a request, including None, is sent as given.""" + session.timeout = 42 + with patch.object( + requests.Session, "request", return_value=_answer(200, {}) + ) as send: + session.get("v1/jobs/j", timeout=timeout) + session.post("v1/jobs/j", timeout=timeout) + assert [call.kwargs["timeout"] for call in send.call_args_list] == [timeout] * 2 diff --git a/tests/test_deprecation.py b/tests/test_deprecation.py new file mode 100644 index 0000000..cd23bd4 --- /dev/null +++ b/tests/test_deprecation.py @@ -0,0 +1,35 @@ +import pytest + +from openprotein._deprecation import warn_deprecated + + +def _deprecated_function(): + warn_deprecated("old.name", "`new.name`", since="0.18.0", removed_in="0.19.0") + + +def test_warn_deprecated_message_format(): + with pytest.warns(FutureWarning) as record: + warn_deprecated("old.name", "`new.name`", since="0.18.0", removed_in="0.19.0") + assert str(record[0].message) == ( + "`old.name` is deprecated since 0.18.0 and will be removed in 0.19.0. " + "Use `new.name`." + ) + + +def test_warn_deprecated_uses_given_versions(): + with pytest.warns(FutureWarning) as record: + warn_deprecated("a", "`b`", since="0.20.0", removed_in="0.21.0") + assert str(record[0].message) == ( + "`a` is deprecated since 0.20.0 and will be removed in 0.21.0. Use `b`." + ) + + +def test_warn_deprecated_category_is_future_warning(): + with pytest.warns(FutureWarning): + warn_deprecated("old.name", "`new.name`", since="0.18.0", removed_in="0.19.0") + + +def test_warn_deprecated_points_at_the_caller_of_the_deprecated_function(): + with pytest.warns(FutureWarning) as record: + _deprecated_function() + assert record[0].filename == __file__ diff --git a/tests/test_errors.py b/tests/test_errors.py new file mode 100644 index 0000000..aed4020 --- /dev/null +++ b/tests/test_errors.py @@ -0,0 +1,14 @@ +from openprotein import errors +from openprotein.errors import NotPrepared + + +def test_not_prepared_names_the_job_whose_units_are_not_listed(): + error = NotPrepared("job-1") + + assert error.job_id == "job-1" + assert "job-1" in str(error) + assert isinstance(error, Exception) + + +def test_not_prepared_is_part_of_the_errors_surface(): + assert "NotPrepared" in errors.__all__ diff --git a/tests/test_private_names.py b/tests/test_private_names.py new file mode 100644 index 0000000..2db0716 --- /dev/null +++ b/tests/test_private_names.py @@ -0,0 +1,31 @@ +"""Helper types and fold wire models have private names.""" + +import importlib +from typing import TypeVar + +import pytest + + +def test_estimators_have_no_public_type_variables(): + estimators = importlib.import_module("openprotein.models.estimators") + + assert not hasattr(estimators, "F") + assert not hasattr(estimators, "H") + + +def test_jobs_futures_keeps_exactly_its_shipped_type_variables(): + futures = importlib.import_module("openprotein.jobs.futures") + public = { + name + for name, value in vars(futures).items() + if isinstance(value, TypeVar) and not name.startswith("_") + } + assert public == {"F", "V", "K"} + + +def test_the_fold_wire_models_are_private(): + with pytest.raises(ModuleNotFoundError): + importlib.import_module("openprotein.fold.request") + request = importlib.import_module("openprotein.fold._request") + assert hasattr(request, "MsaChain") + assert hasattr(request, "complex_chain_ids") diff --git a/tests/test_public_names.py b/tests/test_public_names.py new file mode 100644 index 0000000..289f56d --- /dev/null +++ b/tests/test_public_names.py @@ -0,0 +1,53 @@ +import importlib +import inspect +import pkgutil + +import pytest + +import openprotein + + +def _is_private(module_name: str) -> bool: + return any(part.startswith("_") for part in module_name.split(".")) + + +def _public_modules() -> list[str]: + names = ["openprotein"] + for info in pkgutil.walk_packages(openprotein.__path__, "openprotein."): + if not _is_private(info.name): + names.append(info.name) + return sorted(names) + + +@pytest.mark.parametrize("module_name", _public_modules()) +def test_public_modules_declare_their_interface(module_name): + module = importlib.import_module(module_name) + assert isinstance(getattr(module, "__all__", None), list) + assert [name for name in module.__all__ if not hasattr(module, name)] == [] + + +@pytest.mark.parametrize("module_name", _public_modules()) +def test_public_definitions_are_in_all(module_name): + module = importlib.import_module(module_name) + defined = { + name + for name, value in vars(module).items() + if not name.startswith("_") + and (inspect.isfunction(value) or inspect.isclass(value)) + and value.__module__ == module_name + } + assert defined <= set(module.__all__) + + +@pytest.mark.parametrize("module_name", _public_modules()) +def test_all_names_no_private_module_functions_or_classes(module_name): + module = importlib.import_module(module_name) + leaked = set() + for name in module.__all__: + value = getattr(module, name) + if not (inspect.isfunction(value) or inspect.isclass(value)): + continue + origin = value.__module__ or "" + if origin.startswith("openprotein.") and _is_private(origin): + leaked.add(f"{name} (from {origin})") + assert not leaked diff --git a/tests/test_session_namespaces.py b/tests/test_session_namespaces.py new file mode 100644 index 0000000..b91e6ce --- /dev/null +++ b/tests/test_session_namespaces.py @@ -0,0 +1,40 @@ +"""Compatibility session namespaces emit no runtime deprecation warnings.""" + +import time +import warnings +from unittest.mock import MagicMock, patch + +import pytest + +from openprotein import OpenProtein +from openprotein.base import APISession + + +@pytest.fixture +def session(tmp_path, monkeypatch): + from openprotein import auth_store + + monkeypatch.setattr( + "openprotein.base.TokenStore", + lambda *a, **k: auth_store.TokenStore(dir=tmp_path), + ) + monkeypatch.setattr("openprotein.fold.api.fold_models_list_get", lambda session: []) + login = MagicMock(status_code=200, ok=True, headers={}) + login.json.return_value = { + "access_token": "access", + "refresh_token": "refresh", + "expires_in": 900, + } + with patch.object(APISession, "post", return_value=login): + session = OpenProtein("user@x.com", "pw", backend="https://api.example.test/") + session._expires_at = time.time() + 10_000 + return session + + +@pytest.mark.parametrize( + "namespace", ["embedding", "embeddings", "fold", "predictor", "svd", "umap"] +) +def test_compatibility_namespaces_emit_no_warnings(session, namespace): + with warnings.catch_warnings(): + warnings.simplefilter("error") + getattr(session, namespace) diff --git a/tests/test_submission_transport.py b/tests/test_submission_transport.py new file mode 100644 index 0000000..9d85093 --- /dev/null +++ b/tests/test_submission_transport.py @@ -0,0 +1,243 @@ +"""Transport retry policy on the submission prefixes, against a local server.""" + +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from typing import Any +from unittest.mock import MagicMock, patch + +import pytest +import requests +import urllib3 +from requests.packages.urllib3.exceptions import NewConnectionError, SSLError # type: ignore +from requests.packages.urllib3.util.retry import Retry # type: ignore + +from openprotein import auth_store +from openprotein.base import APISession + + +class _Server: + def __init__(self, script): + self.requests: list[tuple[str, str, bytes, str | None]] = [] + outer = self + answers = list(script) + + class Handler(BaseHTTPRequestHandler): + def _handle(self): + length = int(self.headers.get("Content-Length") or 0) + body = self.rfile.read(length) + outer.requests.append( + ( + self.command, + self.path, + body, + self.headers.get("Idempotency-Key"), + ) + ) + answer = answers.pop(0) if len(answers) > 1 else answers[0] + if answer == "drop": + self.close_connection = True + self.connection.close() + return + status, headers = answer + self.send_response(status) + for name, value in headers.items(): + self.send_header(name, value) + self.send_header("Content-Length", "0") + self.end_headers() + + do_GET = do_POST = _handle + + def log_message(self, format: str, *args: Any) -> None: + pass + + self._httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + self.url = f"http://127.0.0.1:{self._httpd.server_port}/" + threading.Thread(target=self._httpd.serve_forever, daemon=True).start() + + def close(self): + self._httpd.shutdown() + self._httpd.server_close() + + +@pytest.fixture(autouse=True) +def no_backoff(monkeypatch): + monkeypatch.setattr(Retry, "_sleep_backoff", lambda self: None) + + +@pytest.fixture +def serve(): + servers: list[_Server] = [] + + def start(script): + server = _Server(script) + servers.append(server) + return server + + yield start + for server in servers: + server.close() + + +@pytest.fixture +def make_session(tmp_path, monkeypatch): + monkeypatch.setattr( + "openprotein.base.TokenStore", + lambda *a, **k: auth_store.TokenStore(dir=tmp_path), + ) + + def build(backend): + login = MagicMock(status_code=200, ok=True, headers={}) + login.json.return_value = { + "access_token": "access", + "refresh_token": "refresh", + "expires_in": 900, + } + with patch.object(APISession, "post", return_value=login): + session = APISession("user@x.com", "pw", backend=backend) + session._expires_at = time.time() + 10_000 + return session + + return build + + +def _send(session, method, url, **kwargs): + return requests.Session.request(session, method, url, timeout=5, **kwargs) + + +@pytest.mark.parametrize("status", [413, 429, 500, 502, 504]) +def test_a_submission_post_is_not_resent_after_an_error_response( + serve, make_session, status +): + server = serve([(status, {"Retry-After": "0"})]) + session = make_session(server.url) + + response = _send(session, "POST", server.url + "v1/models/m/in/out", json={"a": 1}) + + assert response.status_code == status + assert len(server.requests) == 1 + + +@pytest.mark.parametrize("headers", [{}, {"Retry-After": "0"}]) +def test_a_submission_post_is_resent_unchanged_after_a_503( + serve, make_session, headers +): + server = serve([(503, headers), (202, {})]) + session = make_session(server.url) + + response = _send( + session, + "POST", + server.url + "v1/models/m/in/out", + json={"a": 1}, + headers={"Idempotency-Key": "key-1"}, + ) + + assert response.status_code == 202 + assert len(server.requests) == 2 + assert server.requests[0] == server.requests[1] + assert server.requests[0][3] == "key-1" + + +def test_a_submission_post_is_not_resent_after_the_connection_drops( + serve, make_session +): + server = serve(["drop"]) + session = make_session(server.url) + + with pytest.raises(requests.exceptions.ConnectionError): + _send(session, "POST", server.url + "v1/models/m/in/out", json={"a": 1}) + + assert len(server.requests) == 1 + + +def test_a_model_post_does_not_retry_an_unclassified_transport_error(make_session): + session = make_session("https://test.invalid/") + retry = session.get_adapter("https://test.invalid/v1/models/m/in/out").max_retries + error = SSLError("TLS error") + + with pytest.raises(SSLError) as caught: + retry.increment(method="POST", error=error) + + assert caught.value is error + assert retry.increment(method="GET", error=error).total == retry.total - 1 + + +def test_a_model_post_can_retry_a_failed_connection(make_session): + session = make_session("https://test.invalid/") + retry = session.get_adapter("https://test.invalid/v1/models/m/in/out").max_retries + + assert ( + retry.increment(method="POST", error=NewConnectionError(None, "refused")).total + == retry.total - 1 + ) + + +SAMPLING_PATHS = [ + "v1/data/prompts/sample_msa", + "v1/prompt/sample_msa", + "v1/align/prompt", +] + + +@pytest.mark.parametrize("path", SAMPLING_PATHS) +def test_a_sampling_post_is_not_resent_after_an_unclassified_error(make_session, path): + session = make_session("https://test.invalid/") + retry = session.get_adapter("https://test.invalid/" + path).max_retries + error = SSLError("TLS error") + + with pytest.raises(SSLError) as caught: + retry.increment(method="POST", error=error) + + assert caught.value is error + assert retry.increment(method="GET", error=error).total == retry.total - 1 + assert ( + retry.increment(method="POST", error=NewConnectionError(None, "refused")).total + == retry.total - 1 + ) + + +@pytest.mark.parametrize("path", SAMPLING_PATHS) +@pytest.mark.parametrize("status", [500, 502, 503, 504]) +def test_a_sampling_post_is_not_resent_after_a_server_error( + serve, make_session, path, status +): + server = serve([(status, {"Retry-After": "0"}), (202, {})]) + session = make_session(server.url) + + response = _send(session, "POST", server.url + path, json={"msa_id": "m"}) + + assert response.status_code == status + assert len(server.requests) == 1 + + +def test_a_sampling_post_that_fails_after_it_was_sent_is_sent_once( + serve, make_session, monkeypatch +): + server = serve([(202, {})]) + session = make_session(server.url) + send = urllib3.connectionpool.HTTPConnectionPool._make_request + + def fail_after_send(pool, *args, **kwargs): + response = send(pool, *args, **kwargs) + response.close() + raise SSLError("TLS failure reading the response") + + monkeypatch.setattr( + urllib3.connectionpool.HTTPConnectionPool, "_make_request", fail_after_send + ) + + with pytest.raises(requests.exceptions.SSLError): + _send(session, "POST", server.url + "v1/data/prompts/sample_msa", json={"a": 1}) + + assert len(server.requests) == 1 + + +def test_a_submission_get_is_still_retried_after_a_502(serve, make_session): + server = serve([(502, {}), (200, {})]) + session = make_session(server.url) + + response = _send(session, "GET", server.url + "v1/models/m") + + assert response.status_code == 200 + assert len(server.requests) == 2 diff --git a/tests/test_uuid.py b/tests/test_uuid.py new file mode 100644 index 0000000..4a973fe --- /dev/null +++ b/tests/test_uuid.py @@ -0,0 +1,62 @@ +import pytest + +from openprotein.utils.uuid import _as_id, is_valid_uuid + + +@pytest.mark.parametrize( + "value", + [ + "c9bf9e57-1685-4c89-bafb-ff5af830be8a", + "9af6889e-504d-8bdd-bd6c-1e58a6925708", + "886313e1-3b8a-5372-9b90-0c9aee199e5d", + ], +) +def test_any_uuid_version_is_valid(value): + assert is_valid_uuid(value) + + +@pytest.mark.parametrize( + "value", + [ + "c9bf9e58", + "my-prompt", + "C9BF9E57-1685-4C89-BAFB-FF5AF830BE8A", + "c9bf9e5716854c89bafbff5af830be8a", + ], +) +def test_non_canonical_text_is_not_a_uuid(value): + assert not is_valid_uuid(value) + + +def test_a_required_version_is_checked(): + assert is_valid_uuid("c9bf9e57-1685-4c89-bafb-ff5af830be8a", version=4) + assert not is_valid_uuid("9af6889e-504d-8bdd-bd6c-1e58a6925708", version=4) + + +@pytest.mark.parametrize( + "value", + [ + "c9bf9e57-1685-4c89-bafb-ff5af830be8a", + "C9BF9E57-1685-4C89-BAFB-FF5AF830BE8A", + b"C9BF9E57-1685-4C89-BAFB-FF5AF830BE8A", + ], + ids=["lower", "upper", "bytes"], +) +def test_an_id_in_any_case_is_returned_lower_cased(value): + assert _as_id(value) == "c9bf9e57-1685-4c89-bafb-ff5af830be8a" + + +@pytest.mark.parametrize( + "value", + [ + "c9bf9e5716854c89bafbff5af830be8a", + "c9bf9e58", + "ACDEFGHIKL", + b"\xff\xfe", + "c9bf9e57-1685-4c89-bafb-ff5af830be8a ", + None, + 7, + ], +) +def test_text_outside_the_hyphenated_form_is_not_an_id(value): + assert _as_id(value) is None diff --git a/tests/umap/test_umap.py b/tests/umap/test_umap.py index 4a437c0..9a79bc3 100644 --- a/tests/umap/test_umap.py +++ b/tests/umap/test_umap.py @@ -5,23 +5,19 @@ import pytest -from openprotein.common import FeatureType from openprotein.embeddings.models import EmbeddingModel from openprotein.jobs import JobsAPI, JobStatus, JobType -from openprotein.umap.models import UMAPModel from openprotein.umap.schemas import UMAPFitJob from openprotein.umap.umap import UMAPAPI @pytest.fixture def umap_api(mock_session: MagicMock): - """Fixture to create a UMAPAPI instance.""" return UMAPAPI(mock_session) @pytest.fixture def mock_umap_fit_job(): - """Fixture for a valid UMAPFitJob instance.""" return UMAPFitJob( job_id="umap-123", status=JobStatus.SUCCESS, @@ -31,7 +27,6 @@ def mock_umap_fit_job(): def test_list_umap(umap_api: UMAPAPI, mock_umap_fit_job): - """Test the list_umap method.""" umap_api.session.jobs = MagicMock(spec=JobsAPI) # type: ignore umap_api.session.jobs.get_job.return_value = mock_umap_fit_job # type: ignore with patch("openprotein.umap.api.umap_list_get", return_value=[MagicMock()]): @@ -40,7 +35,6 @@ def test_list_umap(umap_api: UMAPAPI, mock_umap_fit_job): def test_get_umap(umap_api: UMAPAPI, mock_umap_fit_job, mock_session: MagicMock): - """Test the get_umap method.""" umap_id = "umap-123" umap_api.session = mock_session umap_api.session.jobs = MagicMock(spec=JobsAPI) @@ -52,7 +46,6 @@ def test_get_umap(umap_api: UMAPAPI, mock_umap_fit_job, mock_session: MagicMock) def test_fit_umap(umap_api: UMAPAPI, mock_session: MagicMock): - """Test the fit_umap method.""" model = MagicMock(spec=EmbeddingModel) model.id = "model-1" diff --git a/tests/umap/test_umap_api.py b/tests/umap/test_umap_api.py index 46edbbe..63bd620 100644 --- a/tests/umap/test_umap_api.py +++ b/tests/umap/test_umap_api.py @@ -7,13 +7,11 @@ from openprotein.common import FeatureType from openprotein.errors import InvalidParameterError -from openprotein.jobs import JobType from openprotein.umap import api from openprotein.umap.schemas import UMAPMetadata def test_umap_list_get(mock_session: MagicMock): - """Test umap_list_get.""" mock_session.get.return_value.json.return_value = [ { "id": "umap-1", @@ -29,7 +27,6 @@ def test_umap_list_get(mock_session: MagicMock): def test_umap_list_get_with_pagination(mock_session: MagicMock): - """Test umap_list_get with limit and offset.""" mock_session.get.return_value.json.return_value = [ { "id": "umap-1", @@ -47,7 +44,6 @@ def test_umap_list_get_with_pagination(mock_session: MagicMock): def test_umap_fit_post_invalid_params(mock_session: MagicMock): - """Test umap_fit_post with invalid parameters.""" with pytest.raises(InvalidParameterError): api.umap_fit_post( mock_session, "model-1", FeatureType.PLM @@ -63,14 +59,12 @@ def test_umap_fit_post_invalid_params(mock_session: MagicMock): def test_embed_decode(mock_session: MagicMock): - """Test embed_decode.""" arr = np.array([1.0, 2.0, 3.0]) with np.testing.assert_raises(ValueError): api.embed_decode(arr.tobytes()) def test_embed_batch_decode(mock_session: MagicMock): - """Test embed_batch_decode.""" csv_data = "sequence,0,1\nACGT,1.0,2.0\n" arr = api.embed_batch_decode(csv_data.encode("utf-8")) assert arr.shape == (1, 2) diff --git a/tests/umap/test_umap_models.py b/tests/umap/test_umap_models.py index 22247ad..76f263c 100644 --- a/tests/umap/test_umap_models.py +++ b/tests/umap/test_umap_models.py @@ -1,4 +1,5 @@ """Test the model logic for the umap domain.""" + from datetime import datetime from unittest.mock import MagicMock, patch @@ -12,7 +13,6 @@ @pytest.fixture def mock_umap_metadata(): - """Fixture for UMAPMetadata.""" return UMAPMetadata( id="umap-123", status=JobStatus.SUCCESS, @@ -23,7 +23,6 @@ def mock_umap_metadata(): @pytest.fixture def mock_umap_fit_job(): - """Fixture for UMAPFitJob.""" return UMAPFitJob( job_id="umap-123", status=JobStatus.SUCCESS, @@ -35,8 +34,9 @@ def mock_umap_fit_job(): def test_umap_model_init_with_job( mock_session: MagicMock, mock_umap_fit_job, mock_umap_metadata ): - """Test UMAPModel initialization with a job object.""" - with patch("openprotein.umap.api.umap_get", return_value=mock_umap_metadata) as mock_api_get: + with patch( + "openprotein.umap.api.umap_get", return_value=mock_umap_metadata + ) as mock_api_get: model = UMAPModel(session=mock_session, job=mock_umap_fit_job) mock_api_get.assert_called_once_with(mock_session, mock_umap_fit_job.job_id) assert model.id == "umap-123" @@ -45,18 +45,19 @@ def test_umap_model_init_with_job( def test_umap_model_get_embeddings( mock_session: MagicMock, mock_umap_metadata, mock_umap_fit_job ): - """Test the embeddings property.""" mock_session.jobs = MagicMock(spec=JobsAPI) # type: ignore mock_session.jobs.get_job.return_value = mock_umap_fit_job # type: ignore model = UMAPModel(session=mock_session, metadata=mock_umap_metadata) # Mock the api calls made by the 'embeddings' property - with patch( - "openprotein.umap.api.embed_get_batch_result", return_value=b"" - ) as mock_get_batch, patch( - "openprotein.umap.api.embed_batch_decode", return_value=[(1, 2)] - ) as mock_decode, patch( - "openprotein.umap.models.UMAPModel.get_inputs", return_value=["ACGT"] + with ( + patch( + "openprotein.umap.api.embed_get_batch_result", return_value=b"" + ) as mock_get_batch, + patch( + "openprotein.umap.api.embed_batch_decode", return_value=[(1, 2)] + ) as mock_decode, + patch("openprotein.umap.models.UMAPModel.get_inputs", return_value=["ACGT"]), ): embeddings = model.embeddings mock_get_batch.assert_called_once_with(session=mock_session, job_id=model.id) diff --git a/tests/umap/test_umap_schemas.py b/tests/umap/test_umap_schemas.py index 75cf4b8..8f6803d 100644 --- a/tests/umap/test_umap_schemas.py +++ b/tests/umap/test_umap_schemas.py @@ -11,7 +11,6 @@ def test_umap_metadata_is_done(): - """Test the is_done() method on UMAPMetadata.""" metadata_done = UMAPMetadata( id="umap-1", status=JobStatus.SUCCESS, @@ -36,7 +35,6 @@ def test_umap_metadata_is_done(): ], ) def test_job_schemas_job_type(job_class, expected_job_type): - """Test that each job schema has the correct job_type.""" job_data = { "job_id": "job-123", "status": JobStatus.SUCCESS, @@ -48,7 +46,6 @@ def test_job_schemas_job_type(job_class, expected_job_type): def test_umap_job_schema_invalid_job_type(): - """Test that validation fails for an incorrect job_type.""" job_data = { "job_id": "job-123", "status": JobStatus.SUCCESS, @@ -56,4 +53,4 @@ def test_umap_job_schema_invalid_job_type(): "job_type": "some_other_type", } with pytest.raises(ValidationError): - UMAPFitJob(**job_data) + UMAPFitJob.model_validate(job_data) diff --git a/tests/utils/sequences.py b/tests/utils/sequences.py index 55dae29..3fdd158 100644 --- a/tests/utils/sequences.py +++ b/tests/utils/sequences.py @@ -23,9 +23,9 @@ def mutate_sequence( """ Return a copy of ``sequence`` with random substitutions applied. - Substitution-only (no insertions or deletions) so antibody variable domains - keep a valid length and numbering. Used to make each test run produce a - unique sequence and bust server-side caches. + Substitution-only, so antibody variable domains keep a valid length and + numbering, and each test run produces a unique sequence that busts + server-side caches. When ``ensure_mutation`` is True, at least one residue is guaranteed to be substituted, so callers can rely on the result differing from the input. @@ -55,82 +55,79 @@ def random_sequence_fake(length: int) -> str: return "".join(random.choice(amino_acids) for _ in range(length)) +# Window sources for `random_sequence_real`. Real, full-length, reviewed +# sequences: a signal-peptide-bearing transcription factor, human insulin +# preproprotein, human haemoglobin alpha, human serum albumin, and E. coli +# beta-galactosidase. The last is 1024 residues, so every length the tests ask +# for can be windowed without reaching the network. +WINDOW_SOURCE_PROTEINS = [ + "MKTVRQERLKSIVRILERSKEPVSGAQLAEELSVSRQVIVQDIAYLRSLGYNIVATPRGYVLAGG", + "MALWMRLLPLLALLALWGPDPAAAFVNQHLCGSHLVEALYLVCGERGFFYTPKTRREAEDLQVGQVELGGGPGAGSLQPLALEGSLQKRGIVEQCCTSICSLYQLENYCN", + "MVLSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTYFPHFDLSHGSAQVKGHGKKVADALTNAVAHVDDMPNALSALSDLHAHKLRVDPVNFKLLSHCLLVTLAAHLPAEFTPAVHASLDKFLASVSTVLTSKYR", + "MKWVTFISLLFLFSSAYSRGVFRRDAHKSEVAHRFKDLGEENFKALVLIAFAQYLQQCPFEDHVKLVNEVTEFAKTCVADESAENCDKSLHTLFGDKLCTVATLRETYGEMADCCAKQEPERNECFLQHKDDNPNLPRLVRPEVDVMCTAFHDNEETFLKKYLYEIARRHPYFYAPELLFFAKRYKAAFTECCQAADKAACLLPKLDELRDEGKASSAKQRLKCASLQKFGERAFKAWAVARLSQRFPKAEFAEVSKLVTDLTKVHTECCHGDLLECADDRADLAKYICENQDSISSKLKECCEKPLLEKSHCIAEVENDEMPADLPSLAADFVESKDVCKNYAEAKDVFLGMFLYEYARRHPDYSVVLLLRLAKTYETTLEKCCAAADPHECYAKVFDEFKPLVEEPQNLIKQNCELFEQLGEYKFQNALLVRYTKKVPQVSTPTLVEVSRNLGKVGSKCCKHPEAKRMPCAEDYLSVVLNQLCVLHEKTPVSDRVTKCCTESLVNRRPCFSALEVDETYVPKEFNAETFTFHADICTLSEKERQIKKQTALVELVKHKPKATKEQLKAVMDDFAAFVEKCCKADDKETCFAEEGKKLVAASQAALGL", + "MTMITDSLAVVLQRRDWENPGVTQLNRLAAHPPFASWRNSEEARTDRPSQQLRSLNGEWRFAWFPAPEAVPESWLECDLPEADTVVVPSNWQMHGYDAPIYTNVTYPITVNPPFVPTENPTGCYSLTFNVDESWLQEGQTRIIFDGVNSAFHLWCNGRWVGYGQDSRLPSEFDLSAFLRAGENRLAVMVLRWSDGSYLEDQDMWRMSGIFRDVSLLHKPTTQISDFHVATRFNDDFSRAVLEAEVQMCGELRDYLRVTVSLWQGETQVASGTAPFGGEIIDERGGYADRVTLRLNVENPKLWSAEIPNLYRAVVELHTADGTLIEAEACDVGFREVRIENGLLLLNGKPLLIRGVNRHEHHPLHGQVMDEQTMVQDILLMKQNNFNAVRCSHYPNHPLWYTLCDRYGLYVVDEANIETHGMVPMNRLTDDPRWLPAMSERVTRMVQRDRNHPSVIIWSLGNESGHGANHDALYRWIKSVDPSRPVQYEGGGADTTATDIICPMYARVDEDQPFPAVPKWSIKKWLSLPGETRPLILCEYAHAMGNSLGGFAKYWQAFRQYPRLQGGFVWDWVDQSLIKYDENGNPWSAYGGDFGDTPNDRQFCMNGLVFADRTPHPALTEAKHQQQFFQFRLSGQTIEVTSEYLFRHSDNELLHWMVALDGKPLASGEVPLDVAPQGKQLIELPELPQPESAGQLWLTVRVVQPNATAWSEAGHISAWQQWRLAENLSVTLPAASHAIPHLTTSEMDFCIELGNKRWQFNRQSGFLSQMWIGDKKQLLTPLRDQFTRAPLDNDIGVSEATRIDPNAWVERWKAAGHYQAEAALLQCTADTLADAVLITTAHAWQHQGKTLFISRKTYRIDGSGQMAITVDVEVASDTPHPARIGLNCQLAQVAERVNWLGLGPQENYPDRLTAACFDRWDLPLSDMYTPYVFPSENGLRCGTRELNYGPHQWRGDFQFNISRYSQQQLMETSHRHLLHAEEGTWLNIDGFHMGIGGDDSWSPSVSAEFQLSAGRYHYQLVWCQK", +] + +_UNIPROT_SEARCH = "https://rest.uniprot.org/uniprotkb/search" +_fetched_sources: list[str] = [] + + +def _fetch_window_sources(min_length: int, size: int = 25) -> list[str]: + """Reviewed UniProt sequences of at least ``min_length`` residues.""" + import urllib.parse + import urllib.request + + query = f"reviewed:true AND length:[{min_length} TO {min_length * 3}]" + url = f"{_UNIPROT_SEARCH}?" + urllib.parse.urlencode( + {"query": query, "format": "fasta", "size": size} + ) + with urllib.request.urlopen(url, timeout=30) as response: + fasta = response.read().decode() + return [ + "".join(record.splitlines()[1:]) + for record in fasta.split(">") + if record.strip() + ] + + +def _window_sources(length: int) -> list[str]: + """Proteins long enough to yield a ``length``-residue window. + + The bundled set covers the shorter lengths without a network call. Anything + longer is drawn from UniProt once and reused for the rest of the session. + """ + usable = [p for p in WINDOW_SOURCE_PROTEINS + _fetched_sources if len(p) >= length] + if usable: + return usable + _fetched_sources.extend(_fetch_window_sources(length)) + usable = [p for p in _fetched_sources if len(p) >= length] + if not usable: + raise RuntimeError( + f"no source protein of at least {length} residues is available" + ) + return usable + + def random_sequence_real(length: int, real_proteins: list[str] | None = None) -> str: """ - Generate a realistic protein sequence by combining snippets from real proteins - and filling gaps with biologically probable amino acids. + Return a contiguous window of one real protein sequence. + + A window of a single protein keeps the homology a search needs to find: + stitching snippets of unrelated proteins together, or padding with random + residues, yields a sequence with no relatives in any database. """ if length < 0: raise ValueError("length must be non-negative") - - # Default set of real protein sequences (you can expand this) - if real_proteins is None: - real_proteins = [ - "MKTVRQERLKSIVRILERSKEPVSGAQLAEELSVSRQVIVQDIAYLRSLGYNIVATPRGYVLAGG", - "MALWMRLLPLLALLALWGPDPAAAFVNQHLCGSHLVEALYLVCGERGFFYTPKTRREAEDLQVGQVELGGGPGAGSLQPLALEGSLQKRGIVEQCCTSICSLYQLENYCN", - "MVLSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTYFPHFDLSHGSAQVKGHGKKVADALTNAVAHVDDMPNALSALSDLHAHKLRVDPVNFKLLSHCLLVTLAAHLPAEFTPAVHASLDKFLASVSTVLTSKYR", - "MKWVTFISLLFLFSSAYSRGVFRRDAHKSEVAHRFKDLGEENFKALVLIAFAQYLQQCPFEDHVKLVNEVTEFAKTCVADESAENCDKSLHTLFGDKLCTVATLRETYGEMADCCAKQEPERNECFLQHKDDNPNLPRLVRPEVDVMCTAFHDNEETFLKKYLYEIARRHPYFYAPELLFFAKRYKAAFTECCQAADKAACLLPKLDELRDEGKASSAKQRLKCASLQKFGERAFKAWAVARLSQRFPKAEFAEVSKLVTDLTKVHTECCHGDLLECADDRADLAKYICENQDSISSKLKECCEKPLLEKSHCIAEVENDEMPADLPSLAADFVESKDVCKNYAEAKDVFLGMFLYEYARRHPDYSVVLLLRLAKTYETTLEKCCAAADPHECYAKVFDEFKPLVEEPQNLIKQNCELFEQLGEYKFQNALLVRYTKKVPQVSTPTLVEVSRNLGKVGSKCCKHPEAKRMPCAEDYLSVVLNQLCVLHEKTPVSDRVTKCCTESLVNRRPCFSALEVDETYVPKEFNAETFTFHADICTLSEKERQIKKQTALVELVKHKPKATKEQLKAVMDDFAAFVEKCCKADDKETCFAEEGKKLVAASQAALGL", - ] - - # Amino acid frequencies based on natural proteins (approximate) - aa_weights = { - "A": 8.25, - "R": 5.53, - "N": 4.06, - "D": 5.45, - "C": 1.37, - "Q": 3.93, - "E": 6.75, - "G": 7.07, - "H": 2.27, - "I": 5.96, - "L": 9.66, - "K": 5.84, - "M": 2.42, - "F": 3.86, - "P": 4.70, - "S": 6.56, - "T": 5.34, - "W": 1.08, - "Y": 2.92, - "V": 6.87, - } - - amino_acids = list(aa_weights.keys()) - weights = list(aa_weights.values()) - - def weighted_random_aa(): - return random.choices(amino_acids, weights=weights)[0] - if length == 0: return "" - sequence = "" - - while len(sequence) < length: - remaining = length - len(sequence) - - # Choose a random protein and extract a snippet - protein = random.choice(real_proteins) - - # Random snippet length (3-15 residues, but not more than remaining) - snippet_length = min(random.randint(3, 15), remaining, len(protein)) - - if snippet_length > 0: - # Random starting position - start_pos = random.randint(0, len(protein) - snippet_length) - snippet = protein[start_pos : start_pos + snippet_length] - sequence += snippet - - # Fill remaining space with weighted random amino acids - remaining = length - len(sequence) - if remaining > 0: - # Add 1-5 random amino acids (or whatever fits) - fill_length = min(random.randint(1, 5), remaining) - for _ in range(fill_length): - sequence += weighted_random_aa() - - return sequence[:length] # Ensure exact length + sources = real_proteins or _window_sources(length) + candidates = [p for p in sources if len(p) >= length] + if not candidates: + raise ValueError(f"no supplied protein is at least {length} residues long") + protein = random.choice(candidates) + start = random.randint(0, len(protein) - length) + return protein[start : start + length] def mutated_antibody_sequences( @@ -139,12 +136,10 @@ def mutated_antibody_sequences( """ Generate unique antibody sequences via substitution-only mutation. - Returns the base sequence plus mutated copies. Unlike - ``random_mutated_sequences``, this never inserts or deletes residues, so the - variable-domain length and framing stay intact and every sequence remains a - valid antibody that AbNumber/ANARCI can number. Used to make each test run - unique and bust server-side caches without producing un-numberable - sequences. + Returns the base sequence plus mutated copies. Substitution keeps the + variable-domain length and framing intact, so every sequence stays a valid + antibody that AbNumber/ANARCI can number, while making each test run unique + to bust server-side caches. """ sequences = {base_seq} while len(sequences) < num_sequences: @@ -181,8 +176,7 @@ def random_mutated_sequences( mutated_seq_list.append(random.choice(AMINO_ACIDS)) mutated_seq_list.append(base_seq[i]) # keep the original - # For 'delete', we simply do not append the current residue, - # effectively deleting it. + # "delete" appends nothing, dropping the residue. else: # No mutation mutated_seq_list.append(base_seq[i]) diff --git a/tests/utils/strings.py b/tests/utils/strings.py index 888ff47..9eaceb4 100644 --- a/tests/utils/strings.py +++ b/tests/utils/strings.py @@ -1,9 +1,7 @@ - import random import string def random_string(length: int = 10) -> str: - """Generate a random string of fixed length.""" letters = string.ascii_lowercase return "".join(random.choice(letters) for i in range(length)) diff --git a/tests/utils/svd.py b/tests/utils/svd.py index 370841b..26e8a38 100644 --- a/tests/utils/svd.py +++ b/tests/utils/svd.py @@ -1,11 +1,5 @@ """Decomposition using PyTorch.""" -import gc -from abc import ABC, abstractmethod -from functools import wraps -from typing import Optional, Union - -import numpy as np # NOTE disabled since torch isnt even a dependency diff --git a/uv.lock b/uv.lock index cbfffb0..00df103 100644 --- a/uv.lock +++ b/uv.lock @@ -3,8 +3,8 @@ revision = 3 requires-python = ">=3.10, <3.15" resolution-markers = [ "python_full_version >= '3.14' and sys_platform != 'darwin'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin'", "python_full_version >= '3.14' and sys_platform == 'darwin'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin'", "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", "python_full_version == '3.11.*' and sys_platform != 'darwin'", "python_full_version == '3.11.*' and sys_platform == 'darwin'", @@ -449,8 +449,8 @@ version = "1.3.3" source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.14' and sys_platform != 'darwin'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin'", "python_full_version >= '3.14' and sys_platform == 'darwin'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin'", "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", "python_full_version == '3.11.*' and sys_platform != 'darwin'", "python_full_version == '3.11.*' and sys_platform == 'darwin'", @@ -910,8 +910,8 @@ version = "9.9.0" source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.14' and sys_platform != 'darwin'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin'", "python_full_version >= '3.14' and sys_platform == 'darwin'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin'", "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", "python_full_version == '3.11.*' and sys_platform != 'darwin'", "python_full_version == '3.11.*' and sys_platform == 'darwin'", @@ -1588,8 +1588,8 @@ version = "3.6.1" source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.14' and sys_platform != 'darwin'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin'", "python_full_version >= '3.14' and sys_platform == 'darwin'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin'", "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", "python_full_version == '3.11.*' and sys_platform != 'darwin'", "python_full_version == '3.11.*' and sys_platform == 'darwin'", @@ -1683,8 +1683,8 @@ version = "2.4.1" source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.14' and sys_platform != 'darwin'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin'", "python_full_version >= '3.14' and sys_platform == 'darwin'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin'", "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", "python_full_version == '3.11.*' and sys_platform != 'darwin'", "python_full_version == '3.11.*' and sys_platform == 'darwin'", @@ -1779,12 +1779,18 @@ dependencies = [ { name = "tqdm" }, ] +[package.optional-dependencies] +msa = [ + { name = "pyarrow" }, +] + [package.dev-dependencies] dev = [ { name = "editables" }, { name = "hatch-vcs" }, { name = "hatchling" }, { name = "ipykernel" }, + { name = "jsonschema" }, { name = "jupyterlab" }, { name = "matplotlib" }, { name = "pandas-stubs" }, @@ -1804,11 +1810,13 @@ requires-dist = [ { name = "gemmi", specifier = ">=0.6.0,<0.8" }, { name = "numpy", specifier = ">=1.9" }, { name = "pandas", specifier = ">=2.2.2" }, + { name = "pyarrow", marker = "extra == 'msa'", specifier = ">=14" }, { name = "pydantic", specifier = ">=2.5" }, { name = "requests", specifier = ">=2.32.3" }, { name = "tomli", specifier = ">=2.3.0" }, { name = "tqdm", specifier = ">=4.66.4" }, ] +provides-extras = ["msa"] [package.metadata.requires-dev] dev = [ @@ -1816,6 +1824,7 @@ dev = [ { name = "hatch-vcs", specifier = ">=0.5" }, { name = "hatchling", specifier = ">=1.26.1" }, { name = "ipykernel", specifier = ">=6.29.5" }, + { name = "jsonschema", specifier = ">=4.26" }, { name = "jupyterlab", specifier = ">=4.4.1" }, { name = "matplotlib", specifier = ">=3.9.2" }, { name = "pandas-stubs", specifier = ">=2.1.4.240909" }, @@ -2152,6 +2161,56 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/8e/37/efad0257dc6e593a18957422533ff0f87ede7c9c6ea010a2177d738fb82f/pure_eval-0.2.3-py3-none-any.whl", hash = "sha256:1db8e35b67b3d218d818ae653e27f06c3aa420901fa7b081ca98cbedc874e0d0", size = 11842, upload-time = "2024-07-21T12:58:20.04Z" }, ] +[[package]] +name = "pyarrow" +version = "25.0.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/3d/e3/27f57f80141379d60defe6703eb50a707325706f07fedfd1312c7a751995/pyarrow-25.0.1.tar.gz", hash = "sha256:9150a83248bfed9813ea3c3af74c3856c1984d444aa28e58bf7733b9750ddf6a", size = 1201653, upload-time = "2026-08-10T12:40:53.904Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0a/3e/5cd70becb51e1d044c54ba5e627424a6e87df5b98008cbd22cc6abd409ca/pyarrow-25.0.1-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:0b1edbb2f385a6a65e9711b62ba86ac54a7816a3f8d17bb3e8a5929d65fb2485", size = 35954271, upload-time = "2026-08-10T12:36:33.857Z" }, + { url = "https://files.pythonhosted.org/packages/64/be/17599e086df264ea7dc221d1101e3131e181e00da428a2f9bd0358f0d06b/pyarrow-25.0.1-cp310-cp310-macosx_12_0_x86_64.whl", hash = "sha256:a4dd8bf99a8fac133efc0ed6a92f5fddbe2adba0d0f6dd720e39ba9855cea85c", size = 37647543, upload-time = "2026-08-10T12:36:39.486Z" }, + { url = "https://files.pythonhosted.org/packages/42/34/e138b451fd3970a6eda4599f68ae3b2b32b661bc958de3239d54a0bf6575/pyarrow-25.0.1-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:bddd0c4f7630c2a3ddf6347c1bdaa79d97bcf6bd445f9e60c816b7d77c85a5ae", size = 46837120, upload-time = "2026-08-10T12:36:46.58Z" }, + { url = "https://files.pythonhosted.org/packages/57/5c/f8fc0eb2de03464a557d5a4d0c15e972d73362414696618833b771f7eddd/pyarrow-25.0.1-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:a4d6d5e9a3d1879a97c08ded0c797579b7965eafd0f0c26c30b45ccc06db939b", size = 50066460, upload-time = "2026-08-10T12:36:53.702Z" }, + { url = "https://files.pythonhosted.org/packages/3f/d1/0dd64fd06de0333b808a02f60981635f067b71aad3a30698a9a104fae778/pyarrow-25.0.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:514ddb60285631af068875550c90eddc181db3e8e63a032b1559be189e82f056", size = 49937892, upload-time = "2026-08-10T12:37:00.349Z" }, + { url = "https://files.pythonhosted.org/packages/cb/3c/f89d1bd76d5f3284c2a44d7d7ebbd8204535e5ae2b41f4077069b4ff2ec6/pyarrow-25.0.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:cab40b1edfef0262e0e5251aa2c58d75630f24d06dd7794480243acc001a1d7d", size = 53107240, upload-time = "2026-08-10T12:37:07.205Z" }, + { url = "https://files.pythonhosted.org/packages/67/67/b554a8e09f3f3decccf405eb8fbe86696321cbcb5b62d18b4a5057a4c113/pyarrow-25.0.1-cp310-cp310-win_amd64.whl", hash = "sha256:60e89d8f13861a1f7f8d950fa54aebb8023b30734d0ac51ffa80beabe2df4bba", size = 27848683, upload-time = "2026-08-10T12:37:12.058Z" }, + { url = "https://files.pythonhosted.org/packages/ee/8b/0d23b47702fcfe8b3618d5292035099675c5a1c48258932350c08020f7b5/pyarrow-25.0.1-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:51093dd9e10325fbdb3c10a2ae7c4806e5c822d94e74ae4938b26524a3323fee", size = 35946180, upload-time = "2026-08-10T12:37:18.934Z" }, + { url = "https://files.pythonhosted.org/packages/d8/17/707d17a5476c55a9541fde0db8213ac30979a792864d72415f176ba50c45/pyarrow-25.0.1-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:eb6203482ff3746a5632303a7279ae0b5a304c46985b49ed1378cb350ea6728d", size = 37644787, upload-time = "2026-08-10T12:37:25.795Z" }, + { url = "https://files.pythonhosted.org/packages/c1/b2/cdc98ecf1a6408280bc3a6a07054cdd99a3f4670acc0545d383ce113e87d/pyarrow-25.0.1-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:880523be3d29efcf83d3998835d206118ccf35e3871dbd2fb60408cf6b007a80", size = 46834633, upload-time = "2026-08-10T12:37:33.604Z" }, + { url = "https://files.pythonhosted.org/packages/c8/6e/d3fafc41f378b2c65be43b827798c0fae42049a641c8526633ed3eb573e2/pyarrow-25.0.1-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:25f8720bf6387d5dc2ebd2622112de630760419e4b66134405dd24110d15f37e", size = 50065507, upload-time = "2026-08-10T12:37:40.565Z" }, + { url = "https://files.pythonhosted.org/packages/d5/12/8d0698954b8c3001844a898e0a6900bebe83d7ee40c11195174c5122f324/pyarrow-25.0.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:4facd65742a024a4a366328a1d2292062d72d6e023c1b7dda8d4c37544933a25", size = 49955690, upload-time = "2026-08-10T12:37:46.644Z" }, + { url = "https://files.pythonhosted.org/packages/d3/0b/1ecb936ac6409e90a34d58eea1c7cec09a9ae6d2141b9e49ad01a2b1ea47/pyarrow-25.0.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:aa0559502e1cd6254d6814614085dd9c5a3dd0419362978a936a3f68a9e5c3df", size = 53128198, upload-time = "2026-08-10T12:37:52.531Z" }, + { url = "https://files.pythonhosted.org/packages/8e/1c/5236033550633c9b7377b2a53660b2bbb06cb06dc09c4356332d67643ca1/pyarrow-25.0.1-cp311-cp311-win_amd64.whl", hash = "sha256:62cd0d785b8aa6675ee355f9fc02252a340f4441257c42674937826fd7594325", size = 27857263, upload-time = "2026-08-10T12:37:56.943Z" }, + { url = "https://files.pythonhosted.org/packages/a6/e2/9ab15b88cbfac28e16419ce5439ec29234c5172cb8259301b4ba639bdec0/pyarrow-25.0.1-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:df961f2e7ae9cf496459259d798652c70625f6c080650d6952f8c04053c58ee9", size = 35861559, upload-time = "2026-08-10T12:38:02.567Z" }, + { url = "https://files.pythonhosted.org/packages/58/79/a0036dbe1eabe1f73127427342f1d99982584c4a2cde2651d6c93499c6f6/pyarrow-25.0.1-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:cc4aa407fde9fc660be3939e49ea31f50f3e9fec17c0ec63159f7711edd3efc9", size = 37628383, upload-time = "2026-08-10T12:38:09.083Z" }, + { url = "https://files.pythonhosted.org/packages/13/49/d93a57d375f4bf0cf82913dd6bb54acafde83dd993be2282c81ac5616cad/pyarrow-25.0.1-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:4340f0ba6c1d2e13f21658de1d7c662ca2545018568d0030a1e9afca159d87e3", size = 46820190, upload-time = "2026-08-10T12:38:15.458Z" }, + { url = "https://files.pythonhosted.org/packages/60/c9/711ca85d79f1ec98f29a5eae2b051e25b4ecec5de3e3c0e2d5c5dcb15664/pyarrow-25.0.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:5389cdf79447ed1515c9e31620e6e1e2302249564d603f2ad727d4f6d313e4c3", size = 50102437, upload-time = "2026-08-10T12:38:22.487Z" }, + { url = "https://files.pythonhosted.org/packages/80/53/8fb8359ff17cfb6263a1cf3ebf7caec9fe197de118719e84fcb1d0618026/pyarrow-25.0.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:d51592cb7561e87877c506113e7adbf1342ab579e6c21f0ef44b8ba41cb74c80", size = 49942424, upload-time = "2026-08-10T12:38:28.755Z" }, + { url = "https://files.pythonhosted.org/packages/e8/83/4e5ae02a9341571b18a6fca380ac7a58ce6ddae7ab3c060208c0a1e79f02/pyarrow-25.0.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:6109c94d8b9f3b17a041daca16cacb2f651ad8f1ef70a4232c2c0f37a23da2a8", size = 53144206, upload-time = "2026-08-10T12:38:34.862Z" }, + { url = "https://files.pythonhosted.org/packages/65/ee/197cbf47e49f83e6ebeb946a5259a48a638dea27ac774db42fe78022179d/pyarrow-25.0.1-cp312-cp312-win_amd64.whl", hash = "sha256:8858d7bfc22e3f51529aeaa4077225029724623e4595dc9eff8c793935c34140", size = 27953934, upload-time = "2026-08-10T12:38:39.808Z" }, + { url = "https://files.pythonhosted.org/packages/cc/8d/8f271a7a034c834910ec925d56fa4b29733b1380f5289419f5aaa3b02777/pyarrow-25.0.1-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:c7c534ec03c358a76ea3e505e74c1b6aef290af90c444dfd092dbfe23e755b85", size = 35855328, upload-time = "2026-08-10T12:38:45.489Z" }, + { url = "https://files.pythonhosted.org/packages/d2/cd/5bac242f4e841b9971d5eb94fdfe2577e2b70be983e27401e72055786037/pyarrow-25.0.1-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:dda9470024204d7bbf2042b47c6e8a0e47a3eeb8e34405882dfaea6577e0c153", size = 37622415, upload-time = "2026-08-10T12:38:51.107Z" }, + { url = "https://files.pythonhosted.org/packages/63/1f/96d03b4e1506524f7087adb0fd6b2f69f0c9c7aaff1ec36d8030082e15a5/pyarrow-25.0.1-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:44a9120ce5bd81936b8ab9a88076e3fd47c2c6838e0e43630fed83626aca81d9", size = 46813813, upload-time = "2026-08-10T12:38:57.773Z" }, + { url = "https://files.pythonhosted.org/packages/98/d6/33a411115b61dbfc16ad6ad73e71730f6fea654ee3667673bc53ab0e2fe7/pyarrow-25.0.1-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:0befcf816e45a1af33ac775a9970b749e4868a230c7372f0ae5e932bee27039f", size = 50104452, upload-time = "2026-08-10T12:39:04.579Z" }, + { url = "https://files.pythonhosted.org/packages/33/ae/b1b97c9ca87f9f9ddbb5230c798df94eccce61bd79b9b45458c69a478588/pyarrow-25.0.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:3f89685964f46e4216103c75483aac0c0692a5f72212d7ca835adba5ede56ce3", size = 49951343, upload-time = "2026-08-10T12:39:11.8Z" }, + { url = "https://files.pythonhosted.org/packages/98/9e/a112df5cfd5a68cb1d9fc31cfe38c28d5aec9f10865ce37ecef2e4450873/pyarrow-25.0.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6943e2fe7954d29d84de45d29d34c8dc36ce96570e67d89aa9976e650a4a9138", size = 53144784, upload-time = "2026-08-10T12:39:20.503Z" }, + { url = "https://files.pythonhosted.org/packages/31/24/97e8bd98f1e3b07e2ba08bcdff690674fbe16d69a7d2712cc3884665e615/pyarrow-25.0.1-cp313-cp313-win_amd64.whl", hash = "sha256:31e49a7888fcdf3a835da33ae777f6bb9a866334e5a789282fc26dcf426f7f15", size = 27870159, upload-time = "2026-08-10T12:39:26.161Z" }, + { url = "https://files.pythonhosted.org/packages/36/4c/b525824ad3094076919273cd97db61fb3d78252dee76fa3b8dc8f76774aa/pyarrow-25.0.1-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:bf0b672390cdcb640d7288f96b826d71ff4e9abb254a86c89890baf51a29cee6", size = 35885255, upload-time = "2026-08-10T12:39:32.366Z" }, + { url = "https://files.pythonhosted.org/packages/08/62/448bb0e940de41aec31d1a956e63ad9c54afdf122a103cc3ab20c2a3ce33/pyarrow-25.0.1-cp314-cp314-macosx_12_0_x86_64.whl", hash = "sha256:38a9a4b4b9613380e200641891495a56c3d5a98a092db4a870af9975e220471d", size = 37644461, upload-time = "2026-08-10T12:39:38.142Z" }, + { url = "https://files.pythonhosted.org/packages/6e/9a/13587e38bd4806fd218f50fd13b8903fab60588a699ff0c406372e5b4043/pyarrow-25.0.1-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:0b726ad7e7b669be982b0c71c07fe4b037d654354130da79a7902a669e93a66b", size = 46877146, upload-time = "2026-08-10T12:39:43.722Z" }, + { url = "https://files.pythonhosted.org/packages/8d/61/1c5d1229fa21da4cff5365e41e57177aaac57c563c727f35419b8513d1c1/pyarrow-25.0.1-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:9171748cdf796972d85a4b60157c279913e242992e350c90c7450182a9838b2a", size = 50131616, upload-time = "2026-08-10T12:39:49.304Z" }, + { url = "https://files.pythonhosted.org/packages/43/20/291e1d65cc0b09aa19f03cf25cf51a2f5fa94b5db315178f2d254ed5cad4/pyarrow-25.0.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:b7a296aac7a71fa0886c08e155ddb6c636a50013f801f6178daafa0f9e726188", size = 50008879, upload-time = "2026-08-10T12:39:56.891Z" }, + { url = "https://files.pythonhosted.org/packages/8b/7c/1b7c9ec28e76576337e4f97b31141c9a181b89b6d1d6221e9d8205621a58/pyarrow-25.0.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:0fe7c8b6c03969b49c8c66182e4a18e3819ab92d07cfab5d8370c531b9369ef0", size = 53170864, upload-time = "2026-08-10T12:40:04.918Z" }, + { url = "https://files.pythonhosted.org/packages/b7/75/f3d789dc06011a765d14d86bda799cf72ac1d715b6a6edecaa0d73d95062/pyarrow-25.0.1-cp314-cp314-win_amd64.whl", hash = "sha256:f729cfdbd36fd99d543b67a914d2de044c84ebe45be8b34902b299b608c15c8f", size = 28620729, upload-time = "2026-08-10T12:40:51.41Z" }, + { url = "https://files.pythonhosted.org/packages/fc/05/647a8ee6f7c2662feb6921315617bc04dcd6034763fb61b1199720bf6162/pyarrow-25.0.1-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:59a2de54c0cbd954da861eee4d1d330f8e909c45b53455baef696380f2c55033", size = 36130288, upload-time = "2026-08-10T12:40:11.014Z" }, + { url = "https://files.pythonhosted.org/packages/93/f8/c9ee997554d7bea94520667dd1933f109ac1da3ee3556d2b49381e023484/pyarrow-25.0.1-cp314-cp314t-macosx_12_0_x86_64.whl", hash = "sha256:35935cd5de130aa5cf4dea052a63e6bf2e17006c35c3a468194242b9b2bf5956", size = 37762187, upload-time = "2026-08-10T12:40:16.592Z" }, + { url = "https://files.pythonhosted.org/packages/a2/08/a28c01c7fe9e96e8233ce2d13df1d402f4f999f848f51d2daacd6bb4c036/pyarrow-25.0.1-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:f3831aaa25c67a99f99dc8b05873cb9d64560390372e2aa197ce9dd4a3f06a44", size = 46888003, upload-time = "2026-08-10T12:40:23.242Z" }, + { url = "https://files.pythonhosted.org/packages/1b/b9/58612e977d28dc58c878448866838369ee8da2f1e7cc8ed2c84b952aafee/pyarrow-25.0.1-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:6a1fdfc6659b6b19022f2e50627fb5cf7156a66c46bf4299379955cbe742382a", size = 50079036, upload-time = "2026-08-10T12:40:29.169Z" }, + { url = "https://files.pythonhosted.org/packages/72/13/66e1402dcc860e1dc2760b1e0292c9a569b62b3bccab69def1b3e907d006/pyarrow-25.0.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:169d3429d5be7c752125890620f75a60776d38b0035eddae939651640822332e", size = 50040226, upload-time = "2026-08-10T12:40:35.186Z" }, + { url = "https://files.pythonhosted.org/packages/78/10/3f1a5497a7ef732ab0f03ecca3e66d89d9c0f57fdc61b4794c456b781f01/pyarrow-25.0.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:119297a6dc197e45d9c6d4415f7814a67ffa36c180d26f68c154c58067ae782d", size = 53149035, upload-time = "2026-08-10T12:40:41.454Z" }, + { url = "https://files.pythonhosted.org/packages/93/c0/37d4a7e8e2f7a6076283673d5298018ca26478b934c6ee369e10505ab32c/pyarrow-25.0.1-cp314-cp314t-win_amd64.whl", hash = "sha256:4288f27577352d608ca08553b0865e4a9b3aa14820c5d95b53337218d609835b", size = 28753071, upload-time = "2026-08-10T12:40:46.623Z" }, +] + [[package]] name = "pycparser" version = "3.0" @@ -2775,8 +2834,8 @@ version = "1.17.0" source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.14' and sys_platform != 'darwin'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin'", "python_full_version >= '3.14' and sys_platform == 'darwin'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin'", "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", "python_full_version == '3.11.*' and sys_platform != 'darwin'", "python_full_version == '3.11.*' and sys_platform == 'darwin'",