openprotein-python 0.4.3__py3-none-any.whl → 0.5.0.dev0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- openprotein/__init__.py +40 -17
- openprotein/api/__init__.py +2 -7
- openprotein/api/align.py +68 -496
- openprotein/api/assaydata.py +216 -0
- openprotein/api/deprecated/__init__.py +0 -0
- openprotein/api/deprecated/poet.py +304 -0
- openprotein/api/design.py +7 -433
- openprotein/api/embedding.py +155 -999
- openprotein/api/fold.py +26 -319
- openprotein/api/job.py +91 -0
- openprotein/api/predict.py +25 -381
- openprotein/api/predictor.py +205 -0
- openprotein/api/svd.py +150 -0
- openprotein/api/train.py +42 -481
- openprotein/app/__init__.py +11 -0
- openprotein/app/models/__init__.py +20 -0
- openprotein/app/models/align/__init__.py +5 -0
- openprotein/app/models/align/base.py +20 -0
- openprotein/app/models/align/msa.py +140 -0
- openprotein/app/models/align/prompt.py +83 -0
- openprotein/app/models/assaydata.py +176 -0
- openprotein/app/models/deprecated/__init__.py +0 -0
- openprotein/app/models/deprecated/poet.py +183 -0
- openprotein/app/models/design.py +102 -0
- openprotein/app/models/embeddings/__init__.py +7 -0
- openprotein/app/models/embeddings/base.py +269 -0
- openprotein/app/models/embeddings/esm.py +32 -0
- openprotein/app/models/embeddings/future.py +98 -0
- openprotein/app/models/embeddings/openprotein.py +21 -0
- openprotein/app/models/embeddings/poet.py +393 -0
- openprotein/app/models/embeddings/test.py +38 -0
- openprotein/app/models/fold/__init__.py +6 -0
- openprotein/app/models/fold/alphafold2.py +50 -0
- openprotein/app/models/fold/base.py +81 -0
- openprotein/app/models/fold/esmfold.py +31 -0
- openprotein/app/models/fold/future.py +53 -0
- openprotein/app/models/futures.py +445 -0
- openprotein/app/models/predict.py +158 -0
- openprotein/app/models/predictor/__init__.py +4 -0
- openprotein/app/models/predictor/predict.py +78 -0
- openprotein/app/models/predictor/predictor.py +141 -0
- openprotein/app/models/svd.py +171 -0
- openprotein/app/models/train.py +300 -0
- openprotein/app/services/__init__.py +11 -0
- openprotein/app/services/align.py +147 -0
- openprotein/app/services/assaydata.py +127 -0
- openprotein/app/services/design.py +77 -0
- openprotein/app/services/embeddings.py +126 -0
- openprotein/app/services/fold.py +89 -0
- openprotein/app/services/job.py +48 -0
- openprotein/app/services/predict.py +139 -0
- openprotein/app/services/predictor.py +168 -0
- openprotein/app/services/svd.py +102 -0
- openprotein/app/services/train.py +135 -0
- openprotein/config.py +0 -3
- openprotein/errors.py +22 -5
- openprotein/schemas/__init__.py +59 -0
- openprotein/schemas/align.py +55 -0
- openprotein/schemas/assaydata.py +27 -0
- openprotein/schemas/deprecated/__init__.py +0 -0
- openprotein/schemas/deprecated/poet.py +70 -0
- openprotein/schemas/design.py +251 -0
- openprotein/schemas/embeddings.py +103 -0
- openprotein/schemas/fold.py +10 -0
- openprotein/schemas/job.py +110 -0
- openprotein/schemas/predict.py +83 -0
- openprotein/schemas/predictor.py +83 -0
- openprotein/schemas/svd.py +32 -0
- openprotein/schemas/train.py +34 -0
- {openprotein_python-0.4.3.dist-info → openprotein_python-0.5.0.dev0.dist-info}/METADATA +19 -14
- openprotein_python-0.5.0.dev0.dist-info/RECORD +76 -0
- {openprotein_python-0.4.3.dist-info → openprotein_python-0.5.0.dev0.dist-info}/WHEEL +1 -1
- openprotein/api/data.py +0 -532
- openprotein/api/jobs.py +0 -351
- openprotein/api/poet.py +0 -612
- openprotein/futures.py +0 -60
- openprotein/jobs.py +0 -186
- openprotein/pydantic.py +0 -20
- openprotein/schemas.py +0 -55
- openprotein_python-0.4.3.dist-info/RECORD +0 -24
- {openprotein_python-0.4.3.dist-info → openprotein_python-0.5.0.dev0.dist-info/licenses}/LICENSE.txt +0 -0
openprotein/api/predict.py
CHANGED
|
@@ -1,109 +1,15 @@
|
|
|
1
|
-
from typing import Optional, List, Union, Any, Dict, Literal
|
|
2
|
-
from openprotein.pydantic import BaseModel, root_validator
|
|
3
|
-
|
|
4
1
|
from openprotein.base import APISession
|
|
5
|
-
from openprotein.
|
|
6
|
-
from openprotein.
|
|
7
|
-
from openprotein.errors import InvalidParameterError, APIError
|
|
8
|
-
from openprotein.futures import FutureFactory, FutureBase
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
class SequenceData(BaseModel):
|
|
12
|
-
sequence: str
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
class SequenceDataset(BaseModel):
|
|
16
|
-
sequences: List[str]
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
class _Prediction(BaseModel):
|
|
20
|
-
"""Prediction details."""
|
|
21
|
-
|
|
22
|
-
@root_validator(pre=True)
|
|
23
|
-
def extract_pred(cls, values):
|
|
24
|
-
p = values.pop("properties")
|
|
25
|
-
name = list(p.keys())[0]
|
|
26
|
-
ymu = p[name]["y_mu"]
|
|
27
|
-
yvar = p[name]["y_var"]
|
|
28
|
-
p["name"] = name
|
|
29
|
-
p["y_mu"] = ymu
|
|
30
|
-
p["y_var"] = yvar
|
|
31
|
-
|
|
32
|
-
values.update(p)
|
|
33
|
-
return values
|
|
34
|
-
|
|
35
|
-
model_id: str
|
|
36
|
-
model_name: str
|
|
37
|
-
y_mu: Optional[float] = None
|
|
38
|
-
y_var: Optional[float] = None
|
|
39
|
-
name: Optional[str]
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
class Prediction(BaseModel):
|
|
43
|
-
"""Prediction details."""
|
|
44
|
-
|
|
45
|
-
model_id: str
|
|
46
|
-
model_name: str
|
|
47
|
-
properties: Dict[str, Dict[str, float]]
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
class PredictJobBase(Job):
|
|
51
|
-
# might be none if just fetching
|
|
52
|
-
job_id: Optional[str] = None
|
|
53
|
-
job_type: str
|
|
54
|
-
status: JobStatus
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
@register_job_type(JobType.workflow_predict)
|
|
58
|
-
class PredictJob(PredictJobBase):
|
|
59
|
-
"""Properties about predict job returned via API."""
|
|
60
|
-
|
|
61
|
-
@root_validator(pre=True)
|
|
62
|
-
def extract_pred(cls, values):
|
|
63
|
-
# Extracting 'predictions' and 'sequences' from the input values
|
|
64
|
-
v = values.pop("result")
|
|
65
|
-
preds = [i["predictions"] for i in v]
|
|
66
|
-
seqs = [i["sequence"] for i in v]
|
|
67
|
-
values["result"] = [
|
|
68
|
-
{"sequence": i, "predictions": p} for i, p in zip(seqs, preds)
|
|
69
|
-
]
|
|
70
|
-
return values
|
|
71
|
-
|
|
72
|
-
class SequencePrediction(BaseModel):
|
|
73
|
-
"""Sequence prediction."""
|
|
74
|
-
|
|
75
|
-
sequence: str
|
|
76
|
-
predictions: List[Prediction] = []
|
|
77
|
-
|
|
78
|
-
result: Optional[List[SequencePrediction]] = None
|
|
79
|
-
job_type: str
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
@register_job_type(JobType.worflow_predict_single_site)
|
|
83
|
-
class PredictSingleSiteJob(PredictJobBase):
|
|
84
|
-
"""Properties about single-site prediction job returned via API."""
|
|
85
|
-
|
|
86
|
-
class SequencePrediction(BaseModel):
|
|
87
|
-
"""Sequence prediction."""
|
|
88
|
-
|
|
89
|
-
position: int
|
|
90
|
-
amino_acid: str
|
|
91
|
-
# sequence: str
|
|
92
|
-
predictions: List[Prediction] = []
|
|
93
|
-
|
|
94
|
-
result: Optional[List[SequencePrediction]] = None
|
|
95
|
-
job_type: Literal[JobType.worflow_predict_single_site] = (
|
|
96
|
-
JobType.worflow_predict_single_site
|
|
97
|
-
)
|
|
2
|
+
from openprotein.errors import InvalidParameterError
|
|
3
|
+
from openprotein.schemas import WorkflowPredictJob, WorkflowPredictSingleSiteJob
|
|
98
4
|
|
|
99
5
|
|
|
100
6
|
def _create_predict_job(
|
|
101
7
|
session: APISession,
|
|
102
8
|
endpoint: str,
|
|
103
9
|
payload: dict,
|
|
104
|
-
model_ids:
|
|
105
|
-
train_job_id:
|
|
106
|
-
) ->
|
|
10
|
+
model_ids: list[str] | None = None,
|
|
11
|
+
train_job_id: str | None = None,
|
|
12
|
+
) -> WorkflowPredictJob:
|
|
107
13
|
"""
|
|
108
14
|
Creates a Predict request and returns the job object.
|
|
109
15
|
|
|
@@ -156,15 +62,15 @@ def _create_predict_job(
|
|
|
156
62
|
payload["train_job_id"] = train_job_id
|
|
157
63
|
|
|
158
64
|
response = session.post(endpoint, json=payload)
|
|
159
|
-
return
|
|
65
|
+
return WorkflowPredictJob.model_validate(response.json())
|
|
160
66
|
|
|
161
67
|
|
|
162
68
|
def create_predict_job(
|
|
163
69
|
session: APISession,
|
|
164
|
-
sequences:
|
|
165
|
-
|
|
166
|
-
model_ids:
|
|
167
|
-
) ->
|
|
70
|
+
sequences: list[str],
|
|
71
|
+
train_job_id: str | None = None,
|
|
72
|
+
model_ids: list[str] | None = None,
|
|
73
|
+
) -> WorkflowPredictJob:
|
|
168
74
|
"""
|
|
169
75
|
Creates a predict job with a given set of sequences and a train job.
|
|
170
76
|
|
|
@@ -200,8 +106,7 @@ def create_predict_job(
|
|
|
200
106
|
if isinstance(model_ids, str):
|
|
201
107
|
model_ids = [model_ids]
|
|
202
108
|
endpoint = "v1/workflow/predict"
|
|
203
|
-
payload = {"sequences": sequences
|
|
204
|
-
train_job_id = train_job.id if train_job is not None else None
|
|
109
|
+
payload = {"sequences": sequences}
|
|
205
110
|
return _create_predict_job(
|
|
206
111
|
session, endpoint, payload, model_ids=model_ids, train_job_id=train_job_id
|
|
207
112
|
)
|
|
@@ -209,10 +114,10 @@ def create_predict_job(
|
|
|
209
114
|
|
|
210
115
|
def create_predict_single_site(
|
|
211
116
|
session: APISession,
|
|
212
|
-
sequence:
|
|
213
|
-
|
|
214
|
-
model_ids:
|
|
215
|
-
) ->
|
|
117
|
+
sequence: str,
|
|
118
|
+
train_job_id: str | None = None,
|
|
119
|
+
model_ids: list[str] | None = None,
|
|
120
|
+
) -> WorkflowPredictJob:
|
|
216
121
|
"""
|
|
217
122
|
Creates a predict job for single site mutants with a given sequence and a train job.
|
|
218
123
|
|
|
@@ -244,18 +149,18 @@ def create_predict_single_site(
|
|
|
244
149
|
If the response cannot be parsed into a 'Job' object.
|
|
245
150
|
"""
|
|
246
151
|
endpoint = "v1/workflow/predict/single_site"
|
|
247
|
-
payload = {"sequence": sequence
|
|
152
|
+
payload = {"sequence": sequence}
|
|
248
153
|
return _create_predict_job(
|
|
249
|
-
session, endpoint, payload, model_ids=model_ids, train_job_id=
|
|
154
|
+
session, endpoint, payload, model_ids=model_ids, train_job_id=train_job_id
|
|
250
155
|
)
|
|
251
156
|
|
|
252
157
|
|
|
253
158
|
def get_prediction_results(
|
|
254
159
|
session: APISession,
|
|
255
160
|
job_id: str,
|
|
256
|
-
page_size:
|
|
257
|
-
page_offset:
|
|
258
|
-
) ->
|
|
161
|
+
page_size: int | None = None,
|
|
162
|
+
page_offset: int | None = None,
|
|
163
|
+
) -> WorkflowPredictJob:
|
|
259
164
|
"""
|
|
260
165
|
Retrieves the results of a Predict job.
|
|
261
166
|
|
|
@@ -289,15 +194,15 @@ def get_prediction_results(
|
|
|
289
194
|
|
|
290
195
|
response = session.get(endpoint, params=params)
|
|
291
196
|
# get results to assemble into list
|
|
292
|
-
return
|
|
197
|
+
return WorkflowPredictJob.model_validate(response.json())
|
|
293
198
|
|
|
294
199
|
|
|
295
200
|
def get_single_site_prediction_results(
|
|
296
201
|
session: APISession,
|
|
297
202
|
job_id: str,
|
|
298
|
-
page_size:
|
|
299
|
-
page_offset:
|
|
300
|
-
) ->
|
|
203
|
+
page_size: int | None = None,
|
|
204
|
+
page_offset: int | None = None,
|
|
205
|
+
) -> WorkflowPredictSingleSiteJob:
|
|
301
206
|
"""
|
|
302
207
|
Retrieves the results of a single site Predict job.
|
|
303
208
|
|
|
@@ -331,265 +236,4 @@ def get_single_site_prediction_results(
|
|
|
331
236
|
|
|
332
237
|
response = session.get(endpoint, params=params)
|
|
333
238
|
# get results to assemble into list
|
|
334
|
-
return
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
class PredictFutureMixin:
|
|
338
|
-
"""
|
|
339
|
-
Class to to retrieve results from a Predict job.
|
|
340
|
-
|
|
341
|
-
Attributes
|
|
342
|
-
----------
|
|
343
|
-
session : APISession
|
|
344
|
-
APIsession with auth
|
|
345
|
-
job : PredictJob
|
|
346
|
-
The job object that represents the current Predict job.
|
|
347
|
-
|
|
348
|
-
Methods
|
|
349
|
-
-------
|
|
350
|
-
get_results(page_size: Optional[int] = None, page_offset: Optional[int] = None) -> Union[PredictSingleSiteJob, PredictJob]
|
|
351
|
-
Retrieves results from a Predict job.
|
|
352
|
-
"""
|
|
353
|
-
|
|
354
|
-
session: APISession
|
|
355
|
-
job: PredictJob
|
|
356
|
-
id: Optional[str] = None
|
|
357
|
-
|
|
358
|
-
def get_results(
|
|
359
|
-
self, page_size: Optional[int] = None, page_offset: Optional[int] = None
|
|
360
|
-
) -> Union[PredictSingleSiteJob, PredictJob]:
|
|
361
|
-
"""
|
|
362
|
-
Retrieves results from a Predict job.
|
|
363
|
-
|
|
364
|
-
it uses the appropriate method to retrieve the results based on job_type.
|
|
365
|
-
|
|
366
|
-
Parameters
|
|
367
|
-
----------
|
|
368
|
-
page_size : Optional[int], default is None
|
|
369
|
-
The number of results to be returned per page. If None, all results are returned.
|
|
370
|
-
page_offset : Optional[int], default is None
|
|
371
|
-
The number of results to skip. If None, defaults to 0.
|
|
372
|
-
|
|
373
|
-
Returns
|
|
374
|
-
-------
|
|
375
|
-
Union[PredictSingleSiteJob, PredictJob]
|
|
376
|
-
The job object representing the Predict job. The exact type of job depends on the job type.
|
|
377
|
-
|
|
378
|
-
Raises
|
|
379
|
-
------
|
|
380
|
-
HTTPError
|
|
381
|
-
If the GET request does not succeed.
|
|
382
|
-
"""
|
|
383
|
-
assert self.id is not None
|
|
384
|
-
if "single_site" in self.job.job_type:
|
|
385
|
-
return get_single_site_prediction_results(
|
|
386
|
-
self.session, self.id, page_size, page_offset
|
|
387
|
-
)
|
|
388
|
-
else:
|
|
389
|
-
return get_prediction_results(self.session, self.id, page_size, page_offset)
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
class PredictFuture(PredictFutureMixin, AsyncJobFuture, FutureBase): # type: ignore
|
|
393
|
-
"""Future Job for manipulating results"""
|
|
394
|
-
|
|
395
|
-
job_type = [JobType.workflow_predict, JobType.worflow_predict_single_site]
|
|
396
|
-
|
|
397
|
-
def __init__(self, session: APISession, job: PredictJob, page_size=1000):
|
|
398
|
-
super().__init__(session, job)
|
|
399
|
-
self.page_size = page_size
|
|
400
|
-
|
|
401
|
-
def __str__(self) -> str:
|
|
402
|
-
return str(self.job)
|
|
403
|
-
|
|
404
|
-
def __repr__(self) -> str:
|
|
405
|
-
return repr(self.job)
|
|
406
|
-
|
|
407
|
-
@property
|
|
408
|
-
def id(self):
|
|
409
|
-
return self.job.job_id
|
|
410
|
-
|
|
411
|
-
def _fmt_results(self, results):
|
|
412
|
-
properties = set(
|
|
413
|
-
list(i["properties"].keys())[0] for i in results[0].dict()["predictions"]
|
|
414
|
-
)
|
|
415
|
-
dict_results = {}
|
|
416
|
-
for p in properties:
|
|
417
|
-
dict_results[p] = {}
|
|
418
|
-
for i, r in enumerate(results):
|
|
419
|
-
s = r.sequence
|
|
420
|
-
props = [i.properties[p] for i in r.predictions if p in i.properties][0]
|
|
421
|
-
dict_results[p][s] = {"mean": props["y_mu"], "variance": props["y_var"]}
|
|
422
|
-
dict_results
|
|
423
|
-
return dict_results
|
|
424
|
-
|
|
425
|
-
def _fmt_ssp_results(self, results):
|
|
426
|
-
properties = set(
|
|
427
|
-
list(i["properties"].keys())[0] for i in results[0].dict()["predictions"]
|
|
428
|
-
)
|
|
429
|
-
dict_results = {}
|
|
430
|
-
for p in properties:
|
|
431
|
-
dict_results[p] = {}
|
|
432
|
-
for i, r in enumerate(results):
|
|
433
|
-
s = s = f"{r.position+1}{r.amino_acid}"
|
|
434
|
-
props = [i.properties[p] for i in r.predictions if p in i.properties][0]
|
|
435
|
-
dict_results[p][s] = {"mean": props["y_mu"], "variance": props["y_var"]}
|
|
436
|
-
return dict_results
|
|
437
|
-
|
|
438
|
-
def get(self, verbose: bool = False) -> Dict:
|
|
439
|
-
"""
|
|
440
|
-
Get all the results of the predict job.
|
|
441
|
-
|
|
442
|
-
Args:
|
|
443
|
-
verbose (bool, optional): If True, print verbose output. Defaults False.
|
|
444
|
-
|
|
445
|
-
Raises:
|
|
446
|
-
APIError: If there is an issue with the API request.
|
|
447
|
-
|
|
448
|
-
Returns:
|
|
449
|
-
PredictJob: A list of predict objects representing the results.
|
|
450
|
-
"""
|
|
451
|
-
step = self.page_size
|
|
452
|
-
|
|
453
|
-
results: List = []
|
|
454
|
-
num_returned = step
|
|
455
|
-
offset = 0
|
|
456
|
-
|
|
457
|
-
while num_returned >= step:
|
|
458
|
-
try:
|
|
459
|
-
response = self.get_results(page_offset=offset, page_size=step)
|
|
460
|
-
assert isinstance(response.result, list)
|
|
461
|
-
results += response.result
|
|
462
|
-
num_returned = len(response.result)
|
|
463
|
-
offset += num_returned
|
|
464
|
-
except APIError as exc:
|
|
465
|
-
if verbose:
|
|
466
|
-
print(f"Failed to get results: {exc}")
|
|
467
|
-
|
|
468
|
-
if self.job.job_type == JobType.workflow_predict:
|
|
469
|
-
return self._fmt_results(results)
|
|
470
|
-
else:
|
|
471
|
-
return self._fmt_ssp_results(results)
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
class PredictService:
|
|
475
|
-
"""interface for calling Predict endpoints"""
|
|
476
|
-
|
|
477
|
-
def __init__(self, session: APISession):
|
|
478
|
-
"""
|
|
479
|
-
Initialize a new instance of the PredictService class.
|
|
480
|
-
|
|
481
|
-
Parameters
|
|
482
|
-
----------
|
|
483
|
-
session : APISession
|
|
484
|
-
APIsession with auth
|
|
485
|
-
"""
|
|
486
|
-
self.session = session
|
|
487
|
-
|
|
488
|
-
def create_predict_job(
|
|
489
|
-
self,
|
|
490
|
-
sequences: List,
|
|
491
|
-
train_job: Optional[Any] = None,
|
|
492
|
-
model_ids: Optional[List[str]] = None,
|
|
493
|
-
) -> PredictFuture:
|
|
494
|
-
"""
|
|
495
|
-
Creates a new Predict job for a given list of sequences and a trained model.
|
|
496
|
-
|
|
497
|
-
Parameters
|
|
498
|
-
----------
|
|
499
|
-
sequences : List
|
|
500
|
-
The list of sequences to be used for the Predict job.
|
|
501
|
-
train_job : Any
|
|
502
|
-
The train job object representing the trained model.
|
|
503
|
-
model_ids : List[str], optional
|
|
504
|
-
The list of model ids to be used for Predict. Default is None.
|
|
505
|
-
|
|
506
|
-
Returns
|
|
507
|
-
-------
|
|
508
|
-
PredictFuture
|
|
509
|
-
The job object representing the Predict job.
|
|
510
|
-
|
|
511
|
-
Raises
|
|
512
|
-
------
|
|
513
|
-
InvalidParameterError
|
|
514
|
-
If the sequences are not of the same length as the assay data or if the train job has not completed successfully.
|
|
515
|
-
InvalidParameterError
|
|
516
|
-
If BOTH train_job and model_ids are specified
|
|
517
|
-
InvalidParameterError
|
|
518
|
-
If NEITHER train_job or model_ids is specified
|
|
519
|
-
APIError
|
|
520
|
-
If the backend refuses the job (due to sequence length or invalid inputs)
|
|
521
|
-
"""
|
|
522
|
-
if train_job is not None:
|
|
523
|
-
if train_job.assaymetadata is not None:
|
|
524
|
-
if train_job.assaymetadata.sequence_length is not None:
|
|
525
|
-
if any(
|
|
526
|
-
[
|
|
527
|
-
train_job.assaymetadata.sequence_length != len(s)
|
|
528
|
-
for s in sequences
|
|
529
|
-
]
|
|
530
|
-
):
|
|
531
|
-
raise InvalidParameterError(
|
|
532
|
-
f"Predict sequences length {len(sequences[0])} != training assaydata ({train_job.assaymetadata.sequence_length})"
|
|
533
|
-
)
|
|
534
|
-
if not train_job.done():
|
|
535
|
-
print(f"WARNING: training job has status {train_job.status}")
|
|
536
|
-
# raise InvalidParameterError(
|
|
537
|
-
# f"train job has status {train_job.status.value}, Predict requires status SUCCESS"
|
|
538
|
-
# )
|
|
539
|
-
|
|
540
|
-
sequence_dataset = SequenceDataset(sequences=sequences)
|
|
541
|
-
return create_predict_job(
|
|
542
|
-
self.session, sequence_dataset, train_job, model_ids=model_ids # type: ignore
|
|
543
|
-
)
|
|
544
|
-
|
|
545
|
-
def create_predict_single_site(
|
|
546
|
-
self,
|
|
547
|
-
sequence: str,
|
|
548
|
-
train_job: Any,
|
|
549
|
-
model_ids: Optional[List[str]] = None,
|
|
550
|
-
) -> PredictFuture:
|
|
551
|
-
"""
|
|
552
|
-
Creates a new Predict job for single site mutation analysis with a trained model.
|
|
553
|
-
|
|
554
|
-
Parameters
|
|
555
|
-
----------
|
|
556
|
-
sequence : str
|
|
557
|
-
The sequence for single site analysis.
|
|
558
|
-
train_job : Any
|
|
559
|
-
The train job object representing the trained model.
|
|
560
|
-
model_ids : List[str], optional
|
|
561
|
-
The list of model ids to be used for Predict. Default is None.
|
|
562
|
-
|
|
563
|
-
Returns
|
|
564
|
-
-------
|
|
565
|
-
PredictFuture
|
|
566
|
-
The job object representing the Predict job.
|
|
567
|
-
|
|
568
|
-
Raises
|
|
569
|
-
------
|
|
570
|
-
InvalidParameterError
|
|
571
|
-
If the sequences are not of the same length as the assay data or if the train job has not completed successfully.
|
|
572
|
-
InvalidParameterError
|
|
573
|
-
If BOTH train_job and model_ids are specified
|
|
574
|
-
InvalidParameterError
|
|
575
|
-
If NEITHER train_job or model_ids is specified
|
|
576
|
-
APIError
|
|
577
|
-
If the backend refuses the job (due to sequence length or invalid inputs)
|
|
578
|
-
"""
|
|
579
|
-
if train_job.assaymetadata is not None:
|
|
580
|
-
if train_job.assaymetadata.sequence_length is not None:
|
|
581
|
-
if any([train_job.assaymetadata.sequence_length != len(sequence)]):
|
|
582
|
-
raise InvalidParameterError(
|
|
583
|
-
f"Predict sequences length {len(sequence)} != training assaydata ({train_job.assaymetadata.sequence_length})"
|
|
584
|
-
)
|
|
585
|
-
train_job.refresh()
|
|
586
|
-
if not train_job.done():
|
|
587
|
-
print(f"WARNING: training job has status {train_job.status}")
|
|
588
|
-
# raise InvalidParameterError(
|
|
589
|
-
# f"train job has status {train_job.status.value}, Predict requires status SUCCESS"
|
|
590
|
-
# )
|
|
591
|
-
|
|
592
|
-
sequence_dataset = SequenceData(sequence=sequence)
|
|
593
|
-
return create_predict_single_site(
|
|
594
|
-
self.session, sequence_dataset, train_job, model_ids=model_ids # type: ignore
|
|
595
|
-
)
|
|
239
|
+
return WorkflowPredictSingleSiteJob.model_validate(response)
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import io
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import pandas as pd
|
|
5
|
+
from openprotein.base import APISession
|
|
6
|
+
from openprotein.schemas import Job, PredictorMetadata
|
|
7
|
+
from pydantic import TypeAdapter
|
|
8
|
+
|
|
9
|
+
PATH_PREFIX = "v1/predictor"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def predictor_list(session: APISession) -> list[PredictorMetadata]:
|
|
13
|
+
"""
|
|
14
|
+
List trained predictors.
|
|
15
|
+
|
|
16
|
+
Parameters
|
|
17
|
+
----------
|
|
18
|
+
session : APISession
|
|
19
|
+
Session object for API communication.
|
|
20
|
+
|
|
21
|
+
Returns
|
|
22
|
+
-------
|
|
23
|
+
list[PredictorMetadata]
|
|
24
|
+
List of predictors
|
|
25
|
+
"""
|
|
26
|
+
endpoint = PATH_PREFIX
|
|
27
|
+
response = session.get(endpoint)
|
|
28
|
+
return TypeAdapter(list[PredictorMetadata]).validate_python(response.json())
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def predictor_get(session: APISession, predictor_id: str) -> PredictorMetadata:
|
|
32
|
+
endpoint = PATH_PREFIX + f"/{predictor_id}"
|
|
33
|
+
response = session.get(endpoint)
|
|
34
|
+
return TypeAdapter(PredictorMetadata).validate_python(response.json())
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def predictor_fit_gp_post(
|
|
38
|
+
session: APISession,
|
|
39
|
+
assay_id: str,
|
|
40
|
+
properties: list[str],
|
|
41
|
+
feature_type: str,
|
|
42
|
+
model_id: str,
|
|
43
|
+
reduction: str | None = None,
|
|
44
|
+
prompt_id: str | None = None,
|
|
45
|
+
name: str | None = None,
|
|
46
|
+
description: str | None = None,
|
|
47
|
+
) -> Job:
|
|
48
|
+
"""
|
|
49
|
+
Create SVD fit job.
|
|
50
|
+
|
|
51
|
+
Parameters
|
|
52
|
+
----------
|
|
53
|
+
session : APISession
|
|
54
|
+
Session object for API communication.
|
|
55
|
+
assay_id : str
|
|
56
|
+
Assay ID to fit GP on.
|
|
57
|
+
properties: list[str]
|
|
58
|
+
Properties in the assay to fit the gp on.
|
|
59
|
+
feature_type: str
|
|
60
|
+
Type of features to use for encoding sequences. PLM or SVD.
|
|
61
|
+
model_id : str
|
|
62
|
+
Protembed/SVD model to use depending on feature type.
|
|
63
|
+
reduction : str | None
|
|
64
|
+
Type of embedding reduction to use for computing features. default = None
|
|
65
|
+
prompt_id: str | None
|
|
66
|
+
Prompt ID if using PoET-based models.
|
|
67
|
+
name: str | None
|
|
68
|
+
Optional name of predictor model. Randomly generated if not provided.
|
|
69
|
+
description: str | None
|
|
70
|
+
Optional description to attach to the model.
|
|
71
|
+
|
|
72
|
+
Returns
|
|
73
|
+
-------
|
|
74
|
+
PredictorTrainJob
|
|
75
|
+
"""
|
|
76
|
+
endpoint = PATH_PREFIX + "/gp"
|
|
77
|
+
|
|
78
|
+
body = {
|
|
79
|
+
"dataset": {
|
|
80
|
+
"assay_id": assay_id,
|
|
81
|
+
"properties": properties,
|
|
82
|
+
},
|
|
83
|
+
"features": {
|
|
84
|
+
"type": feature_type,
|
|
85
|
+
"model_id": model_id,
|
|
86
|
+
},
|
|
87
|
+
"kernel": {
|
|
88
|
+
"type": "rbf",
|
|
89
|
+
# "multitask": True
|
|
90
|
+
},
|
|
91
|
+
}
|
|
92
|
+
if reduction is not None:
|
|
93
|
+
body["features"]["reduction"] = reduction
|
|
94
|
+
if prompt_id is not None:
|
|
95
|
+
body["features"]["prompt_id"] = prompt_id
|
|
96
|
+
if name is not None:
|
|
97
|
+
body["name"] = name
|
|
98
|
+
if description is not None:
|
|
99
|
+
body["description"] = description
|
|
100
|
+
|
|
101
|
+
response = session.post(endpoint, json=body)
|
|
102
|
+
return Job.model_validate(response.json())
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def predictor_delete(session: APISession, predictor_id: str):
|
|
106
|
+
raise NotImplementedError()
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def predictor_predict_post(
|
|
110
|
+
session: APISession, predictor_id: str, sequences: list[bytes] | list[str]
|
|
111
|
+
):
|
|
112
|
+
endpoint = PATH_PREFIX + f"/{predictor_id}/predict"
|
|
113
|
+
|
|
114
|
+
sequences_unicode = [(s if isinstance(s, str) else s.decode()) for s in sequences]
|
|
115
|
+
body = {
|
|
116
|
+
"sequences": sequences_unicode,
|
|
117
|
+
}
|
|
118
|
+
response = session.post(endpoint, json=body)
|
|
119
|
+
|
|
120
|
+
return Job.model_validate(response.json())
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def predictor_predict_get_sequences(
|
|
124
|
+
session: APISession, prediction_job_id: str
|
|
125
|
+
) -> list[bytes]:
|
|
126
|
+
endpoint = PATH_PREFIX + f"/predict/{prediction_job_id}/sequences"
|
|
127
|
+
|
|
128
|
+
response = session.get(endpoint)
|
|
129
|
+
return TypeAdapter(list[bytes]).validate_python(response.json())
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def predictor_predict_get_sequence_result(
|
|
133
|
+
session: APISession, prediction_job_id: str, sequence: bytes | str
|
|
134
|
+
) -> bytes:
|
|
135
|
+
"""
|
|
136
|
+
Get encoded result for a sequence from the request ID.
|
|
137
|
+
|
|
138
|
+
Parameters
|
|
139
|
+
----------
|
|
140
|
+
session : APISession
|
|
141
|
+
Session object for API communication.
|
|
142
|
+
job_id : str
|
|
143
|
+
job ID to retrieve results from
|
|
144
|
+
sequence from: bytes
|
|
145
|
+
sequence to retrieve results for
|
|
146
|
+
|
|
147
|
+
Returns
|
|
148
|
+
-------
|
|
149
|
+
result : bytes
|
|
150
|
+
"""
|
|
151
|
+
if isinstance(sequence, bytes):
|
|
152
|
+
sequence = sequence.decode()
|
|
153
|
+
endpoint = PATH_PREFIX + f"/predict/{prediction_job_id}/{sequence}"
|
|
154
|
+
response = session.get(endpoint)
|
|
155
|
+
return response.content
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def predictor_predict_get_batched_result(
|
|
159
|
+
session: APISession, prediction_job_id: str
|
|
160
|
+
) -> bytes:
|
|
161
|
+
"""
|
|
162
|
+
Get encoded result for a sequence from the request ID.
|
|
163
|
+
|
|
164
|
+
Parameters
|
|
165
|
+
----------
|
|
166
|
+
session : APISession
|
|
167
|
+
Session object for API communication.
|
|
168
|
+
prediction_job_id : str
|
|
169
|
+
job ID to retrieve results from
|
|
170
|
+
sequence : bytes
|
|
171
|
+
sequence to retrieve results for
|
|
172
|
+
|
|
173
|
+
Returns
|
|
174
|
+
-------
|
|
175
|
+
result : bytes
|
|
176
|
+
"""
|
|
177
|
+
endpoint = PATH_PREFIX + f"/predict/{prediction_job_id}"
|
|
178
|
+
response = session.get(endpoint)
|
|
179
|
+
return response.content
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def decode_score(data: bytes, batched: bool = False) -> tuple[np.ndarray, np.ndarray]:
|
|
183
|
+
"""
|
|
184
|
+
Decode embedding.
|
|
185
|
+
|
|
186
|
+
Args:
|
|
187
|
+
data (bytes): raw bytes encoding the array received over the API
|
|
188
|
+
batched (bool): whether or not the result was batched. affects the retrieved csv format whether they contain additional columns and header rows.
|
|
189
|
+
|
|
190
|
+
Returns:
|
|
191
|
+
mus (np.ndarray): decoded array of means
|
|
192
|
+
vars (np.ndarray): decoded array of variances
|
|
193
|
+
"""
|
|
194
|
+
s = io.BytesIO(data)
|
|
195
|
+
if batched:
|
|
196
|
+
# should contain header and sequence column
|
|
197
|
+
df = pd.read_csv(s)
|
|
198
|
+
scores = df.iloc[:, 1:].values
|
|
199
|
+
else:
|
|
200
|
+
# should be a single row with 2n columns
|
|
201
|
+
df = pd.read_csv(s, header=None)
|
|
202
|
+
scores = df.values
|
|
203
|
+
mus = scores[:, ::2]
|
|
204
|
+
vars = scores[:, 1::2]
|
|
205
|
+
return mus, vars
|