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.
Files changed (81) hide show
  1. openprotein/__init__.py +40 -17
  2. openprotein/api/__init__.py +2 -7
  3. openprotein/api/align.py +68 -496
  4. openprotein/api/assaydata.py +216 -0
  5. openprotein/api/deprecated/__init__.py +0 -0
  6. openprotein/api/deprecated/poet.py +304 -0
  7. openprotein/api/design.py +7 -433
  8. openprotein/api/embedding.py +155 -999
  9. openprotein/api/fold.py +26 -319
  10. openprotein/api/job.py +91 -0
  11. openprotein/api/predict.py +25 -381
  12. openprotein/api/predictor.py +205 -0
  13. openprotein/api/svd.py +150 -0
  14. openprotein/api/train.py +42 -481
  15. openprotein/app/__init__.py +11 -0
  16. openprotein/app/models/__init__.py +20 -0
  17. openprotein/app/models/align/__init__.py +5 -0
  18. openprotein/app/models/align/base.py +20 -0
  19. openprotein/app/models/align/msa.py +140 -0
  20. openprotein/app/models/align/prompt.py +83 -0
  21. openprotein/app/models/assaydata.py +176 -0
  22. openprotein/app/models/deprecated/__init__.py +0 -0
  23. openprotein/app/models/deprecated/poet.py +183 -0
  24. openprotein/app/models/design.py +102 -0
  25. openprotein/app/models/embeddings/__init__.py +7 -0
  26. openprotein/app/models/embeddings/base.py +269 -0
  27. openprotein/app/models/embeddings/esm.py +32 -0
  28. openprotein/app/models/embeddings/future.py +98 -0
  29. openprotein/app/models/embeddings/openprotein.py +21 -0
  30. openprotein/app/models/embeddings/poet.py +393 -0
  31. openprotein/app/models/embeddings/test.py +38 -0
  32. openprotein/app/models/fold/__init__.py +6 -0
  33. openprotein/app/models/fold/alphafold2.py +50 -0
  34. openprotein/app/models/fold/base.py +81 -0
  35. openprotein/app/models/fold/esmfold.py +31 -0
  36. openprotein/app/models/fold/future.py +53 -0
  37. openprotein/app/models/futures.py +445 -0
  38. openprotein/app/models/predict.py +158 -0
  39. openprotein/app/models/predictor/__init__.py +4 -0
  40. openprotein/app/models/predictor/predict.py +78 -0
  41. openprotein/app/models/predictor/predictor.py +141 -0
  42. openprotein/app/models/svd.py +171 -0
  43. openprotein/app/models/train.py +300 -0
  44. openprotein/app/services/__init__.py +11 -0
  45. openprotein/app/services/align.py +147 -0
  46. openprotein/app/services/assaydata.py +127 -0
  47. openprotein/app/services/design.py +77 -0
  48. openprotein/app/services/embeddings.py +126 -0
  49. openprotein/app/services/fold.py +89 -0
  50. openprotein/app/services/job.py +48 -0
  51. openprotein/app/services/predict.py +139 -0
  52. openprotein/app/services/predictor.py +168 -0
  53. openprotein/app/services/svd.py +102 -0
  54. openprotein/app/services/train.py +135 -0
  55. openprotein/config.py +0 -3
  56. openprotein/errors.py +22 -5
  57. openprotein/schemas/__init__.py +59 -0
  58. openprotein/schemas/align.py +55 -0
  59. openprotein/schemas/assaydata.py +27 -0
  60. openprotein/schemas/deprecated/__init__.py +0 -0
  61. openprotein/schemas/deprecated/poet.py +70 -0
  62. openprotein/schemas/design.py +251 -0
  63. openprotein/schemas/embeddings.py +103 -0
  64. openprotein/schemas/fold.py +10 -0
  65. openprotein/schemas/job.py +110 -0
  66. openprotein/schemas/predict.py +83 -0
  67. openprotein/schemas/predictor.py +83 -0
  68. openprotein/schemas/svd.py +32 -0
  69. openprotein/schemas/train.py +34 -0
  70. {openprotein_python-0.4.3.dist-info → openprotein_python-0.5.0.dev0.dist-info}/METADATA +19 -14
  71. openprotein_python-0.5.0.dev0.dist-info/RECORD +76 -0
  72. {openprotein_python-0.4.3.dist-info → openprotein_python-0.5.0.dev0.dist-info}/WHEEL +1 -1
  73. openprotein/api/data.py +0 -532
  74. openprotein/api/jobs.py +0 -351
  75. openprotein/api/poet.py +0 -612
  76. openprotein/futures.py +0 -60
  77. openprotein/jobs.py +0 -186
  78. openprotein/pydantic.py +0 -20
  79. openprotein/schemas.py +0 -55
  80. openprotein_python-0.4.3.dist-info/RECORD +0 -24
  81. {openprotein_python-0.4.3.dist-info → openprotein_python-0.5.0.dev0.dist-info/licenses}/LICENSE.txt +0 -0
openprotein/api/fold.py CHANGED
@@ -1,58 +1,12 @@
1
- from openprotein.base import APISession
2
- from openprotein.api.jobs import Job, MappedAsyncJobFuture
3
- import openprotein.config as config
4
1
  from openprotein.api.embedding import ModelMetadata
5
- from openprotein.api.align import validate_msa, MSAFuture
6
- import openprotein.pydantic as pydantic
7
- from typing import Optional, List, Union, Tuple
8
- from openprotein.futures import FutureBase, FutureFactory
9
- from abc import ABC, abstractmethod
10
-
2
+ from openprotein.base import APISession
3
+ from openprotein.schemas import Job
4
+ from pydantic import TypeAdapter
11
5
 
12
6
  PATH_PREFIX = "v1/fold"
13
7
 
14
8
 
15
- class FoldModelBase:
16
- # overridden by subclasses
17
- # get correct fold model
18
-
19
- model_id = None
20
-
21
- @classmethod
22
- def get_model(cls):
23
- if isinstance(cls.model_id, str):
24
- return [cls.model_id]
25
- return cls.model_id
26
-
27
-
28
- class FoldModelFactory:
29
- """Factory class for creating Future instances based on job_type."""
30
-
31
- @staticmethod
32
- def create_model(session, model_id, metadata=None, default=None):
33
- """
34
- Create and return an instance of the appropriate Future class based on the job type.
35
-
36
- Returns:
37
- - An instance of the appropriate Future class.
38
- """
39
- # Dynamically discover all subclasses of FutureBase
40
- future_classes = FoldModelBase.__subclasses__()
41
-
42
- # Find the Future class that matches the job type
43
- for future_class in future_classes:
44
- if model_id in future_class.get_model():
45
- return future_class(
46
- session=session, model_id=model_id, metadata=metadata
47
- )
48
- # default to FoldModel
49
- try:
50
- return default(session=session, model_id=model_id, metadata=metadata)
51
- except Exception:
52
- raise ValueError(f"Unsupported model_id type: {model_id}")
53
-
54
-
55
- def fold_models_list_get(session: APISession) -> List[str]:
9
+ def fold_models_list_get(session: APISession) -> list[str]:
56
10
  """
57
11
  List available fold models.
58
12
 
@@ -76,7 +30,7 @@ def fold_model_get(session: APISession, model_id: str) -> ModelMetadata:
76
30
  return ModelMetadata(**result)
77
31
 
78
32
 
79
- def fold_get_sequences(session: APISession, job_id: str) -> List[bytes]:
33
+ def fold_get_sequences(session: APISession, job_id: str) -> list[bytes]:
80
34
  """
81
35
  Get results associated with the given request ID.
82
36
 
@@ -93,11 +47,11 @@ def fold_get_sequences(session: APISession, job_id: str) -> List[bytes]:
93
47
  """
94
48
  endpoint = PATH_PREFIX + f"/{job_id}/sequences"
95
49
  response = session.get(endpoint)
96
- return pydantic.parse_obj_as(List[bytes], response.json())
50
+ return TypeAdapter(list[bytes]).validate_python(response.json())
97
51
 
98
52
 
99
53
  def fold_get_sequence_result(
100
- session: APISession, job_id: str, sequence: bytes
54
+ session: APISession, job_id: str, sequence: bytes | str
101
55
  ) -> bytes:
102
56
  """
103
57
  Get encoded result for a sequence from the request ID.
@@ -122,57 +76,11 @@ def fold_get_sequence_result(
122
76
  return response.content
123
77
 
124
78
 
125
- class FoldResultFuture(MappedAsyncJobFuture, FutureBase):
126
- job_type = ["/embeddings/fold"]
127
- """Future Job for manipulating results"""
128
-
129
- def __init__(
130
- self,
131
- session: APISession,
132
- job: Job,
133
- sequences=None,
134
- max_workers=config.MAX_CONCURRENT_WORKERS,
135
- ):
136
- super().__init__(session, job, max_workers)
137
- if sequences is None:
138
- sequences = fold_get_sequences(self.session, job_id=job.job_id)
139
- self._sequences = sequences
140
-
141
- @property
142
- def sequences(self):
143
- if self._sequences is None:
144
- self._sequences = fold_get_sequences(self.session, self.job.job_id)
145
- return self._sequences
146
-
147
- @property
148
- def id(self):
149
- return self.job.job_id
150
-
151
- def keys(self):
152
- return self.sequences
153
-
154
- def get(self, verbose=False) -> List[Tuple[str, str]]:
155
- return super().get(verbose=verbose)
156
-
157
- def get_item(self, sequence: bytes) -> bytes:
158
- """
159
- Get fold results for specified sequence.
160
-
161
- Args:
162
- sequence (bytes): sequence to fetch results for
163
-
164
- Returns:
165
- np.ndarray: fold
166
- """
167
- data = fold_get_sequence_result(self.session, self.job.job_id, sequence)
168
- return data #
169
-
170
-
171
79
  def fold_models_esmfold_post(
172
80
  session: APISession,
173
- sequences: List[bytes],
174
- num_recycles: Optional[int] = None,
175
- ):
81
+ sequences: list[bytes],
82
+ num_recycles: int | None = None,
83
+ ) -> Job:
176
84
  """
177
85
  POST a request for structure prediction using ESMFold. Returns a Job object referring to this request
178
86
  that can be used to retrieve results later.
@@ -193,25 +101,23 @@ def fold_models_esmfold_post(
193
101
  endpoint = PATH_PREFIX + "/models/esmfold"
194
102
 
195
103
  sequences_unicode = [(s if isinstance(s, str) else s.decode()) for s in sequences]
196
- body = {
104
+ body: dict = {
197
105
  "sequences": sequences_unicode,
198
106
  }
199
107
  if num_recycles is not None:
200
108
  body["num_recycles"] = num_recycles
201
109
 
202
110
  response = session.post(endpoint, json=body)
203
- return FutureFactory.create_future(
204
- session=session, response=response, sequences=sequences
205
- )
111
+ return Job.model_validate(response.json())
206
112
 
207
113
 
208
114
  def fold_models_alphafold2_post(
209
115
  session: APISession,
210
- msa: Union[str, MSAFuture],
211
- num_recycles: Optional[int] = None,
212
- num_models: Optional[int] = 1,
213
- num_relax: Optional[int] = 0,
214
- ):
116
+ msa_id: str,
117
+ num_recycles: int | None = None,
118
+ num_models: int = 1,
119
+ num_relax: int = 0,
120
+ ) -> Job:
215
121
  """
216
122
  POST a request for structure prediction using AlphaFold2. Returns a Job object referring to this request
217
123
  that can be used to retrieve results later.
@@ -220,14 +126,14 @@ def fold_models_alphafold2_post(
220
126
  ----------
221
127
  session : APISession
222
128
  Session object for API communication.
223
- msa : Union[str, MSAfuture]
224
- MSA to use for structure prediction. The first sequence in the MSA is the query sequence.
225
- num_recycles : Optional[int] = None
226
- number of recycles for structure prediction
227
- num_models : Optional[int] = 1
228
- number of models to predict
229
- num_relax : Optional[int] = 0
230
- number of relaxation iterations to run
129
+ msa_id : str
130
+ ID of MSA to use for structure prediction. The first sequence in the MSA is the query sequence.
131
+ num_recycles : Optional, int.
132
+ Number of recycles for structure prediction. Default to nil which lets the system decide.
133
+ num_models : int
134
+ Number of models to predict. Defaults to 1.
135
+ num_relax : int
136
+ Number of relaxation iterations to run. Defaults to 0.
231
137
 
232
138
  Returns
233
139
  -------
@@ -235,10 +141,6 @@ def fold_models_alphafold2_post(
235
141
  """
236
142
  endpoint = PATH_PREFIX + "/models/alphafold2"
237
143
 
238
- msa_id = msa
239
- if isinstance(msa, MSAFuture):
240
- msa_id = msa.msa_id
241
-
242
144
  body = {
243
145
  "msa_id": msa_id,
244
146
  "num_models": num_models,
@@ -250,199 +152,4 @@ def fold_models_alphafold2_post(
250
152
  response = session.post(endpoint, json=body)
251
153
  # GET endpoint for AF2 expects the query sequence (first sequence) within the MSA
252
154
  # since we don't know what the is, leave the sequence out of the future to be retrieved when calling get()
253
- return FutureFactory.create_future(session=session, response=response)
254
-
255
-
256
- class FoldModel(ABC):
257
- """
258
- ABC Class providing inference endpoints for protein fold models served by OpenProtein.
259
-
260
- Must implement fold() method.
261
- """
262
-
263
- def __init__(self, session, model_id, metadata=None):
264
- self.session = session
265
- self.id = model_id
266
- self._metadata = metadata
267
-
268
- def __str__(self) -> str:
269
- return self.id
270
-
271
- def __repr__(self) -> str:
272
- return self.id
273
-
274
- @property
275
- def metadata(self):
276
- return self.get_metadata()
277
-
278
- def get_metadata(self) -> ModelMetadata:
279
- """
280
- Get model metadata for this model.
281
-
282
- Returns
283
- -------
284
- ModelMetadata
285
- """
286
- if self._metadata is not None:
287
- return self._metadata
288
- self._metadata = fold_model_get(self.session, self.id)
289
- return self._metadata
290
-
291
- @abstractmethod
292
- def fold(self, sequence: str, **kwargs):
293
- pass
294
-
295
-
296
- class ESMFoldModel(FoldModel, FoldModelBase):
297
- model_id = "esmfold"
298
-
299
- def __init__(self, session, model_id, metadata=None):
300
- super().__init__(session, model_id, metadata)
301
- self.id = self.model_id
302
-
303
- def fold(self, sequences: List[bytes], num_recycles: int = 1) -> FoldResultFuture:
304
- """
305
- Fold sequences using this model.
306
-
307
- Parameters
308
- ----------
309
- sequences : List[bytes]
310
- sequences to fold
311
- num_recycles : int
312
- number of times to recycle models
313
- Returns
314
- -------
315
- FoldResultFuture
316
- """
317
- return fold_models_esmfold_post(
318
- self.session, sequences, num_recycles=num_recycles
319
- )
320
-
321
-
322
- class AlphaFold2Model(FoldModel, FoldModelBase):
323
- model_id = "alphafold2"
324
-
325
- def __init__(self, session, model_id, metadata=None):
326
- super().__init__(session, model_id, metadata)
327
- self.id = self.model_id
328
-
329
- def fold(
330
- self,
331
- msa: Union[str, MSAFuture],
332
- num_recycles: Optional[int] = None,
333
- num_models: int = 1,
334
- num_relax: Optional[int] = 0,
335
- ):
336
- """
337
- Post sequences to alphafold model.
338
-
339
- Parameters
340
- ----------
341
- msa : Union[str, MSAFuture]
342
- msa
343
- num_recycles : int
344
- number of times to recycle models
345
- num_models : int
346
- number of models to train - best model will be used
347
- max_msa : Union[str, int]
348
- maximum number of sequences in the msa to use.
349
- relax_max_iterations : int
350
- maximum number of iterations
351
-
352
- Returns
353
- -------
354
- job : Job
355
- """
356
- if msa and not isinstance(msa, str):
357
- msa = validate_msa(msa)
358
-
359
- return fold_models_alphafold2_post(
360
- self.session,
361
- msa,
362
- num_recycles=num_recycles,
363
- num_models=num_models,
364
- num_relax=num_relax,
365
- )
366
-
367
-
368
- def validate_fold_id(fold):
369
- if isinstance(fold, str):
370
- return fold
371
- return fold.id
372
-
373
-
374
- class FoldAPI:
375
- """
376
- This class defines a high level interface for accessing the fold API.
377
- """
378
-
379
- esmfold: ESMFoldModel
380
- alphafold2: AlphaFold2Model
381
-
382
- def __init__(self, session: APISession):
383
- self.session = session
384
- self._load_models()
385
-
386
- @property
387
- def af2(self):
388
- """Alias for AlphaFold2"""
389
- return self.alphafold2
390
-
391
- def _load_models(self):
392
- # Dynamically add model instances as attributes - precludes any drift
393
- models = self.list_models()
394
- for model in models:
395
- model_name = model.id.replace("-", "_") # hyphens out
396
- setattr(self, model_name, model)
397
-
398
- def list_models(self) -> List[FoldModel]:
399
- """list models available for creating folds of your sequences"""
400
- models = []
401
- for model_id in fold_models_list_get(self.session):
402
- models.append(
403
- FoldModelFactory.create_model(self.session, model_id, default=FoldModel)
404
- )
405
- return models
406
-
407
- def get_model(self, model_id: str) -> FoldModel:
408
- """
409
- Get model by model_id.
410
-
411
- FoldModel allows all the usual job manipulation: \
412
- e.g. making POST and GET requests for this model specifically.
413
-
414
-
415
- Parameters
416
- ----------
417
- model_id : str
418
- the model identifier
419
-
420
- Returns
421
- -------
422
- FoldModel
423
- The model
424
-
425
- Raises
426
- ------
427
- HTTPError
428
- If the GET request does not succeed.
429
- """
430
- return FoldModelFactory.create_model(
431
- session=self.session, model_id=model_id, default=FoldModel
432
- )
433
-
434
- def get_results(self, job) -> FoldResultFuture:
435
- """
436
- Retrieves the results of a fold job.
437
-
438
- Parameters
439
- ----------
440
- job : Job
441
- The fold job whose results are to be retrieved.
442
-
443
- Returns
444
- -------
445
- FoldResultFuture
446
- An instance of FoldResultFuture
447
- """
448
- return FutureFactory.create_future(job=job, session=self.session)
155
+ return Job.model_validate(response.json())
openprotein/api/job.py ADDED
@@ -0,0 +1,91 @@
1
+ """Jobs and job-centric flows."""
2
+
3
+ from typing import List
4
+
5
+ from openprotein.base import APISession
6
+ from openprotein.schemas import Job
7
+ from pydantic import TypeAdapter
8
+
9
+ # def load_job(session: APISession, job_id: str) -> Future:
10
+ # """
11
+ # Reload a Submitted job to resume from where you left off!
12
+
13
+
14
+ # Parameters
15
+ # ----------
16
+ # session : APISession
17
+ # The current API session for communication with the server.
18
+ # job_id : str
19
+ # The identifier of the job whose details are to be loaded.
20
+
21
+ # Returns
22
+ # -------
23
+ # Job
24
+ # Job
25
+
26
+ # Raises
27
+ # ------
28
+ # HTTPError
29
+ # If the request to the server fails.
30
+
31
+ # """
32
+ # return Future.create(session=session, job_id=job_id)
33
+
34
+
35
+ def job_args_get(session: APISession, job_id: str) -> dict:
36
+ """Get job."""
37
+ endpoint = f"v1/jobs/{job_id}/args"
38
+ response = session.get(endpoint)
39
+ return dict(**response.json())
40
+
41
+
42
+ def job_get(session: APISession, job_id: str) -> Job:
43
+ """Get job."""
44
+ endpoint = f"v1/jobs/{job_id}"
45
+ response = session.get(endpoint)
46
+ return TypeAdapter(Job).validate_python(response.json())
47
+
48
+
49
+ def jobs_list(
50
+ session: APISession,
51
+ status: str | None = None,
52
+ job_type: str | None = None,
53
+ assay_id: str | None = None,
54
+ more_recent_than: str | None = None,
55
+ ) -> List[Job]:
56
+ """
57
+ Retrieve a list of jobs filtered by specific criteria.
58
+
59
+ Parameters
60
+ ----------
61
+ session : APISession
62
+ The current API session for communication with the server.
63
+ status : str, optional
64
+ Filter by job status. If None, jobs of all statuses are retrieved. Default is None.
65
+ job_type : str, optional
66
+ Filter by Filter. If None, jobs of all types are retrieved. Default is None.
67
+ assay_id : str, optional
68
+ Filter by assay. If None, jobs for all assays are retrieved. Default is None.
69
+ more_recent_than : str, optional
70
+ Retrieve jobs that are more recent than a specified date. If None, no date filtering is applied. Default is None.
71
+
72
+ Returns
73
+ -------
74
+ List[Job]
75
+ A list of Job instances that match the specified criteria.
76
+ """
77
+ endpoint = "v1/jobs"
78
+
79
+ params = {}
80
+ if status is not None:
81
+ params["status"] = status
82
+ if job_type is not None:
83
+ params["job_type"] = job_type
84
+ if assay_id is not None:
85
+ params["assay_id"] = assay_id
86
+ if more_recent_than is not None:
87
+ params["more_recent_than"] = more_recent_than
88
+
89
+ response = session.get(endpoint, params=params)
90
+ # return jobs, not futures
91
+ return TypeAdapter(List[Job]).validate_python(response.json())