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/design.py CHANGED
@@ -1,261 +1,5 @@
1
- from typing import Optional, Dict, List, Union, Literal, Any
2
- from enum import Enum
3
-
4
1
  from openprotein.base import APISession
5
- from openprotein.api.jobs import AsyncJobFuture
6
- from openprotein.schemas import JobType
7
- import openprotein.config as config
8
- from openprotein.jobs import JobType, Job
9
-
10
- from openprotein.errors import APIError
11
- from openprotein.futures import FutureFactory, FutureBase
12
- from openprotein.pydantic import BaseModel, Field, validator
13
- from datetime import datetime
14
- import re
15
-
16
-
17
- class DesignMetadata(BaseModel):
18
- y_mu: Optional[float] = None
19
- y_var: Optional[float] = None
20
-
21
-
22
- class DesignSubscore(BaseModel):
23
- score: float
24
- metadata: DesignMetadata
25
-
26
-
27
- class DesignStep(BaseModel):
28
- step: int
29
- sample_index: int
30
- sequence: str
31
- # scores: List[int]
32
- # subscores_metadata: List[List[DesignSubscore]]
33
- __initial_scores: List[float] = Field(
34
- ..., alias="scores"
35
- ) # renaming 'scores' to 'initial_scores' # noqa: E501
36
- scores: List[List[DesignSubscore]] = Field(
37
- ..., alias="subscores_metadata"
38
- ) # renaming 'subscores_metadata' to 'scores' # noqa: E501
39
- # umap1: float
40
- # umap2: float
41
-
42
-
43
- class DesignResults(BaseModel):
44
- status: str
45
- job_id: str
46
- job_type: str
47
- created_date: datetime
48
- start_date: datetime
49
- end_date: Optional[datetime]
50
- assay_id: str
51
- num_rows: int
52
- result: List[DesignStep]
53
-
54
-
55
- class DirectionEnum(str, Enum):
56
- gt = ">"
57
- lt = "<"
58
- eq = "="
59
-
60
-
61
- class Criterion(BaseModel):
62
- target: float
63
- weight: float
64
- direction: str
65
-
66
-
67
- class ModelCriterion(BaseModel):
68
- criterion_type: Literal["model"]
69
- model_id: str
70
- measurement_name: str
71
- criterion: Criterion
72
-
73
-
74
- class NMutationCriterion(BaseModel):
75
- criterion_type: Literal["n_mutations"]
76
- # sequences: Optional[List[str]]
77
-
78
-
79
- CriterionItem = Union[ModelCriterion, NMutationCriterion]
80
-
81
-
82
- class DesignConstraint:
83
- def __init__(self, sequence: str):
84
- self.sequence = sequence
85
- self.mutations = self.initialize(sequence)
86
-
87
- def initialize(self, sequence: str) -> Dict[int, List[str]]:
88
- """Initialize with no changes allowed to the sequence."""
89
- return {i: [aa] for i, aa in enumerate(sequence, start=1)}
90
-
91
- def allow(
92
- self, positions: Union[int, List[int]], amino_acids: Union[List[str], str]
93
- ) -> None:
94
- """Allow specific amino acids at given positions."""
95
- if isinstance(positions, int):
96
- positions = [positions]
97
- if isinstance(amino_acids, str):
98
- amino_acids = list(amino_acids)
99
-
100
- for position in positions:
101
- if position in self.mutations:
102
- self.mutations[position].extend(amino_acids)
103
- else:
104
- self.mutations[position] = amino_acids
105
-
106
- def remove(
107
- self, positions: Union[int, List[int]], amino_acids: Union[List[str], str]
108
- ) -> None:
109
- """Remove specific amino acids from being allowed at given positions."""
110
- if isinstance(positions, int):
111
- positions = [positions]
112
- if isinstance(amino_acids, str):
113
- amino_acids = list(amino_acids)
114
-
115
- for position in positions:
116
- if position in self.mutations:
117
- for aa in amino_acids:
118
- if aa in self.mutations[position]:
119
- self.mutations[position].remove(aa)
120
-
121
- def as_dict(self) -> Dict[int, List[str]]:
122
- """Convert the internal mutations representation into a dictionary."""
123
- return self.mutations
124
-
125
-
126
- class DesignJobCreate(BaseModel):
127
- assay_id: str
128
- criteria: List[List[CriterionItem]]
129
- num_steps: Optional[int] = 8
130
- pop_size: Optional[int] = None
131
- n_offsprings: Optional[int] = None
132
- crossover_prob: Optional[float] = None
133
- crossover_prob_pointwise: Optional[float] = None
134
- mutation_average_mutations_per_seq: Optional[int] = None
135
- allowed_tokens: Optional[Union[DesignConstraint, Dict[int, List[str]]]] = None
136
-
137
- class Config:
138
- arbitrary_types_allowed = True
139
-
140
- @validator("allowed_tokens", pre=True)
141
- def ensure_dict(cls, v):
142
- if isinstance(v, DesignConstraint):
143
- return v.as_dict()
144
- return v
145
-
146
-
147
- def _validate_mutation_dict(d: dict, amino_acids: str = "ACDEFGHIKLMNPQRSTVWY"):
148
- validated = {}
149
- for k, v in d.items():
150
- _ = [i for i in v if i in amino_acids]
151
- validated[k] = _
152
- return validated
153
-
154
-
155
- def mutation_regex(
156
- constraints: str,
157
- amino_acids: Union[List[str], str] = "ACDEFGHIKLMNPQRSTVWY",
158
- verbose: bool = False,
159
- ) -> dict:
160
- """
161
- Parses a constraint string for sequence and return a mutation dict.
162
-
163
- Syntax supported:
164
- * [AC] - position must be A or C ONLY
165
- * X - position can be any amino acid
166
- * A - position will always be A
167
- * [^ACD] - anything except A, C or D
168
- * X{3} - 3 consecutive positions of any residue
169
- * A{3} - 3 consecutive positions of A
170
-
171
- Parameters
172
- ----------
173
- constraints: A string representing the constraints on the protein sequence.
174
- amino_acids: A list or string of all possible amino acids.
175
- verbose: control verbosity
176
-
177
- Returns
178
- -------
179
- dict : mutation dict
180
- """
181
- if isinstance(amino_acids, str):
182
- amino_acids = list(amino_acids)
183
- constraints_dict = {}
184
-
185
- constraints_dict = {}
186
- pos = 1
187
-
188
- pattern = re.compile(
189
- r"(\[[^\]]*\])|(\{[A-Z]+\})|([A-Z]\{\d+\})|([A-Z]\{\d+,\d*\})|(X\{\d+\})|([A-Z])|(X)"
190
- )
191
-
192
- for match in pattern.finditer(constraints):
193
- token = match.group()
194
- if verbose:
195
- print(f"parsed: {token}")
196
-
197
- if token.startswith("[") and token.endswith("]"):
198
- if "^" in token:
199
- # Negation
200
- excluded = set(token[2:-1])
201
- options = [aa for aa in amino_acids if aa not in excluded]
202
- else:
203
- # Specific options
204
- options = list(token[1:-1])
205
- constraints_dict[pos] = options
206
- pos += 1
207
- elif token.startswith("{") and token.endswith("}"):
208
- # Ranges of positions or exact repetitions for specific amino acids
209
- options = list(token[1:-1])
210
- constraints_dict[pos] = options
211
- pos += 1
212
- elif "{" in token and "X" not in token:
213
- # Ranges of positions or exact repetitions for specific amino acids
214
- base, range_part = token.split("{")
215
- if "," in range_part:
216
- # Range specified, handle similarly to previous versions
217
- start, end = map(int, range_part[:-1].split(","))
218
- for _ in range(start, end + 1):
219
- constraints_dict[pos] = [base]
220
- pos += 1
221
- else:
222
- # Exact repetition specified
223
- count = int(range_part[:-1])
224
- for _ in range(count):
225
- constraints_dict[pos] = [base]
226
- pos += 1
227
- elif token.startswith("X{") and token.endswith("}"):
228
- # Fixed number of wildcard positions
229
- num = int(token[2:-1])
230
- for _ in range(num):
231
- constraints_dict[pos] = list(amino_acids)
232
- pos += 1
233
- elif token == "X":
234
- # Any amino acid
235
- constraints_dict[pos] = list(amino_acids)
236
- pos += 1
237
- else:
238
- # Specific amino acid
239
- constraints_dict[pos] = [token]
240
- pos += 1
241
-
242
- return _validate_mutation_dict(constraints_dict)
243
-
244
-
245
- def position_mutation(
246
- positions: List, amino_acids: Union[str, List] = "ACDEFGHIKLMNPQRSTVWY"
247
- ):
248
- if isinstance(amino_acids, list):
249
- amino_acids = "".join(amino_acids)
250
- return {k: list(amino_acids) for k in positions}
251
-
252
-
253
- def nochange(sequence: str):
254
- return {k + 1: [v] for k, v in enumerate(sequence)}
255
-
256
-
257
- def keep_cys(sequence: str):
258
- return {k + 1: [v] for k, v in enumerate(sequence) if v == "C"}
2
+ from openprotein.schemas import DesignJobCreate, DesignResults, Job
259
3
 
260
4
 
261
5
  def create_design_job(session: APISession, design_job: DesignJobCreate):
@@ -283,19 +27,18 @@ def create_design_job(session: APISession, design_job: DesignJobCreate):
283
27
  Job
284
28
  The created job as a Job instance.
285
29
  """
286
- params = design_job.dict(exclude_none=True)
30
+ params = design_job.model_dump(exclude_none=True)
287
31
  # print(f"sending design: {params}")
288
32
  response = session.post("v1/workflow/design/genetic-algorithm", json=params)
289
-
290
- return FutureFactory.create_future(session=session, response=response)
33
+ return Job.model_validate(response.json())
291
34
 
292
35
 
293
36
  def get_design_results(
294
37
  session: APISession,
295
38
  job_id: str,
296
- step: Optional[int] = None,
297
- page_size: Optional[int] = None,
298
- page_offset: Optional[int] = None,
39
+ step: int | None = None,
40
+ page_size: int | None = None,
41
+ page_offset: int | None = None,
299
42
  ) -> DesignResults:
300
43
  """
301
44
  Retrieves the results of a Design job.
@@ -336,173 +79,4 @@ def get_design_results(
336
79
 
337
80
  response = session.get(endpoint, params=params)
338
81
 
339
- return DesignResults(**response.json())
340
-
341
-
342
- class DesignFutureMixin:
343
- session: APISession
344
- job: Job
345
-
346
- def get_results(
347
- self,
348
- step: Optional[int] = None,
349
- page_size: Optional[int] = None,
350
- page_offset: Optional[int] = None,
351
- ) -> DesignResults:
352
- """
353
- Retrieves the results of a Design job.
354
-
355
- This function retrieves the results of a Design job by making a GET request to design..
356
-
357
- Parameters
358
- ----------
359
- page_size : Optional[int], default is None
360
- The number of results to be returned per page. If None, all results are returned.
361
- page_offset : Optional[int], default is None
362
- The number of results to skip. If None, defaults to 0.
363
-
364
- Returns
365
- -------
366
- DesignJob
367
- The job object representing the Design job.
368
-
369
- Raises
370
- ------
371
- HTTPError
372
- If the GET request does not succeed.
373
- """
374
- return get_design_results(
375
- self.session,
376
- job_id=self.job.job_id,
377
- step=step,
378
- page_size=page_size,
379
- page_offset=page_offset,
380
- )
381
-
382
-
383
- class DesignFuture(DesignFutureMixin, AsyncJobFuture, FutureBase):
384
- """Future Job for manipulating results"""
385
-
386
- job_type = [JobType.workflow_design]
387
-
388
- def __init__(self, session: APISession, job: Job, page_size=1000):
389
- super().__init__(session, job)
390
- self.page_size = page_size
391
-
392
- def __str__(self) -> str:
393
- return str(self.job)
394
-
395
- def __repr__(self) -> str:
396
- return repr(self.job)
397
-
398
- def _fmt_results(self, results) -> List[Dict]:
399
- return [i.dict() for i in results]
400
-
401
- @property
402
- def id(self):
403
- return self.job.job_id
404
-
405
- def get(self, step: Optional[int] = None, verbose: bool = False) -> List[Dict]:
406
- """
407
- Get all the results of the design job.
408
-
409
- Args:
410
- verbose (bool, optional): If True, print verbose output. Defaults False.
411
-
412
- Raises:
413
- APIError: If there is an issue with the API request.
414
-
415
- Returns:
416
- List: A list of predict objects representing the results.
417
- """
418
- page = self.page_size
419
-
420
- results = []
421
- num_returned = page
422
- offset = 0
423
-
424
- while num_returned >= page:
425
- try:
426
- response = self.get_results(
427
- page_offset=offset, step=step, page_size=page
428
- )
429
- results += response.result
430
- num_returned = len(response.result)
431
- offset += num_returned
432
- except APIError as exc:
433
- if verbose:
434
- print(f"Failed to get results: {exc}")
435
- return self._fmt_results(results)
436
-
437
-
438
- class DesignAPI:
439
- """interface for calling Design endpoints"""
440
-
441
- session: APISession
442
-
443
- def __init__(self, session: APISession):
444
- self.session = session
445
-
446
- def create_design_job(self, design_job: DesignJobCreate) -> DesignFuture:
447
- """
448
- Start a protein design job based on your assaydata, a trained ML model and Criteria (specified here).
449
-
450
- Parameters
451
- ----------
452
- design_job : DesignJobCreate
453
- The details of the design job to be created, with the following parameters:
454
- - assay_id: The ID for the assay.
455
- - criteria: A list of CriterionItem lists for evaluating the design.
456
- - num_steps: The number of steps in the genetic algo. Default is 8.
457
- - pop_size: The population size for the genetic algo. Default is None.
458
- - n_offsprings: The number of offspring for the genetic algo. Default is None.
459
- - crossover_prob: The crossover probability for the genetic algo. Default is None.
460
- - crossover_prob_pointwise: The pointwise crossover probability for the genetic algo. Default is None.
461
- - mutation_average_mutations_per_seq: The average number of mutations per sequence. Default is None.
462
- - allowed_tokens: A dict of positions and allows tokens (e.g. *{1:['G','L']})* ) designating how mutations may occur. Default is None.
463
-
464
- Returns
465
- -------
466
- DesignFuture
467
- The created job as a DesignFuture instance.
468
- """
469
- return create_design_job(self.session, design_job)
470
-
471
- def get_design_results(
472
- self,
473
- job_id: str,
474
- step: Optional[int] = None,
475
- page_size: Optional[int] = None,
476
- page_offset: Optional[int] = None,
477
- ) -> DesignResults:
478
- """
479
- Retrieves the results of a Design job.
480
-
481
- Parameters
482
- ----------
483
- job_id : str
484
- The ID for the design job
485
- step: int
486
- The design step to retrieve, if None: retrieve all.
487
- page_size : Optional[int], default is None
488
- The number of results to be returned per page. If None, all results are returned.
489
- page_offset : Optional[int], default is None
490
- The number of results to skip. If None, defaults to 0.
491
-
492
- Returns
493
- -------
494
- DesignJob
495
- The job object representing the Design job.
496
-
497
- Raises
498
- ------
499
- HTTPError
500
- If the GET request does not succeed.
501
- """
502
- return get_design_results(
503
- self.session,
504
- step=step,
505
- job_id=job_id,
506
- page_size=page_size,
507
- page_offset=page_offset,
508
- )
82
+ return DesignResults.model_validate(response.json())