-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathqueries.py
More file actions
804 lines (670 loc) · 27.5 KB
/
queries.py
File metadata and controls
804 lines (670 loc) · 27.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
"""Classes to define queries to the Ginkgo AI API."""
from typing import Dict, Optional, Any, List, Literal, Union
from abc import ABC, abstractmethod
from pathlib import Path
from functools import lru_cache
import json
import yaml
import tempfile
import pydantic
import requests
import pandas
from ginkgo_ai_client.utils import (
fasta_sequence_iterator,
IteratorWithLength,
cif_to_pdb,
)
## ---- Base classes --------------------------------------------------------------
class QueryBase(pydantic.BaseModel, ABC):
"""Base class for all queries. It's functions are:
- Specify the mandatory class methods `to_request_params` and `parse_response`
- Provide a better error message when a user forgets to use named arguments only.
Without that tweak, the default error message from pydantic is very technical
and confusing to new users.
"""
def __new__(cls, *args, **kwargs):
if args:
raise TypeError(
f"Invalid initialization: {cls.__name__} does not accept unnamed "
f"arguments. Please name all inputs, for instance "
f"`{cls.__name__}(field_name=value, other_field=value, ...)`."
)
return super().__new__(cls)
@abstractmethod
def to_request_params(self) -> Dict:
pass
@abstractmethod
def parse_response(self, results: Dict) -> Any:
pass
class ResponseBase(pydantic.BaseModel):
def write_to_jsonl(self, path: str):
with open(path, "a") as f:
f.write(self.model_dump_json() + "\n")
## ---- MASKEDLM AND EMBEDDINGS ------------------------------------------------------
_maskedlm_models_properties = {
"ginkgo-aa0-650M": "protein",
"esm2-650M": "protein",
"esm2-3B": "protein",
"ginkgo-maskedlm-3utr-v1": "dna",
"lcdna": "dna-iupac",
"abdiffusion": "protein",
"mrna-foundation": "dna",
}
_maskedlm_models_properties_str = "\n".join(
f"- {model}: {sequence_type}"
for model, sequence_type in _maskedlm_models_properties.items()
)
def _validate_model_and_sequence(
model: str, sequence: str, allow_masks: bool = False, extra_chars: List[str] = []
):
"""Raise an error if the model is unknown or the sequence isn't compatible.
Parameters
----------
model: str
Model name. Used to infer input type.
sequence: str
Sequence to validate
allow_masks: bool
Whether to allow masks in input. Default = False.
extra_chars: List[str]=[]
List of extra valid characters. Default = [].
"""
valid_models = list(_maskedlm_models_properties.keys())
if model not in valid_models:
raise ValueError(f"Model '{model}' unknown. Sould be one of {valid_models}")
sequence_type = _maskedlm_models_properties[model]
if allow_masks:
sequence = sequence.replace("<mask>", "")
chars = {
"dna": set("ATGC"),
"dna-iupac": set("ATGCNRSYWKMDHBV"),
"protein": set("ACDEFGHIKLMNPQRSTVWY"),
}[sequence_type]
chars = chars.union(set([e.upper() for e in extra_chars]))
if not set(sequence.upper()).issubset(chars):
raise ValueError(
f"Model {model} requires the sequence to only contain "
f"the following characters (lower or upper-case): {''.join(chars)}"
)
class EmbeddingResponse(ResponseBase):
"""A response to a MeanEmbeddingQuery, with attributes `embedding` (the mean
embedding of the model's last encoder layer) and `query_name` (the original
query's name).
"""
embedding: List[float]
query_name: Optional[str] = None
class MeanEmbeddingQuery(QueryBase):
"""A query to infer mean embeddings from a DNA or protein sequence.
Parameters
----------
sequence: str
The sequence to unmask. The sequence should be of the form "MLPP<mask>PPLM" with
as many masks as desired.
model: str
The model to use for the inference.
query_name: Optional[str] = None
The name of the query. It will appear in the API response and can be used to
handle exceptions.
Returns
-------
EmbeddingResponse
``client.send_request(query)`` returns an ``EmbeddingResponse`` with attributes
``embedding`` (the mean embedding of the model's last encoder layer) and
``query_name`` (the original query's name).
Examples
--------
>>> query = MeanEmbeddingQuery("MLPP<mask>PPLM", model="ginkgo-aa0-650M")
>>> client.send_request(query)
EmbeddingResponse(embedding=[1.05, 0.002, ...])
"""
sequence: str
model: str
query_name: Optional[str] = None
def to_request_params(self) -> Dict:
return {
"model": self.model,
"text": self.sequence,
"transforms": [{"type": "EMBEDDING"}],
}
def parse_response(self, results: Dict) -> EmbeddingResponse:
return EmbeddingResponse(
embedding=results["embedding"], query_name=self.query_name
)
@pydantic.model_validator(mode="after")
def check_model_and_sequence_compatibility(cls, query):
sequence, model = query.sequence, query.model
_validate_model_and_sequence(model=model, sequence=sequence, allow_masks=False)
return query
@classmethod
def iter_from_fasta(cls, fasta_path: str, model: str):
"""Return an iterator over the sequences in a fasta file. The iterator has
a length attribute that gives the number of sequences in the fasta file."""
fasta_iterator = fasta_sequence_iterator(fasta_path)
query_iterator = (
cls(sequence=str(record.seq), model=model, query_name=record.id)
for record in fasta_iterator
)
return IteratorWithLength(query_iterator, len(fasta_iterator))
@classmethod
def list_from_fasta(cls, fasta_path: str, model: str):
return list(cls.iter_from_fasta(fasta_path, model))
class SequenceResponse(ResponseBase):
"""A response to a MaskedInferenceQuery, with attributes `sequence` (the predicted
sequence) and `query_name` (the original query's name).
"""
sequence: str
query_name: Optional[str] = None
class MaskedInferenceQuery(QueryBase):
"""A query to infer masked tokens in a DNA or protein sequence.
Parameters
----------
sequence: str
The sequence to unmask. The sequence should be of the form "MLPP<mask>PPLM" with
as many masks as desired.
model: str
The model to use for the inference (only "ginkgo-aa0-650M" is supported for now).
query_name: Optional[str] = None
The name of the query. It will appear in the API response and can be used to
handle exceptions.
Returns
--------
SequenceResponse
``client.send_request(query)`` returns a ``SequenceResponse`` with attributes
``sequence` (the predicted sequence) and ``query_name`` (the original query's
name).
"""
sequence: str
model: str
query_name: Optional[str] = None
def to_request_params(self) -> Dict:
return {
"model": self.model,
"text": self.sequence,
"transforms": [{"type": "FILL_MASK"}],
}
def parse_response(self, response: Dict) -> SequenceResponse:
"""The response has a sequence and the original query's name"""
return SequenceResponse(
sequence=response["sequence"], query_name=self.query_name
)
@pydantic.model_validator(mode="after")
def check_model_and_sequence_compatibility(cls, query):
sequence, model = query.sequence, query.model
_validate_model_and_sequence(model=model, sequence=sequence, allow_masks=True)
return query
auto_doc_str = f"""
Supported inference models
--------------------------
Here are the supported models, and the sequence type they support. Sequences must
be upper-case and not contain any mask etc. for embeddings computation.
{_maskedlm_models_properties_str}
"""
for cls in [MeanEmbeddingQuery, MaskedInferenceQuery]:
cls.__doc__ += auto_doc_str[:1]
## ---- PROMOTER ACTIVITY QUERIES ---------------------------------------------------
class PromoterActivityResponse(ResponseBase):
"""A response to a PromoterActivityQuery, with attributes `activity` (the predicted
activity) and `query_name` (the original query's name).
Attributes
----------
activity_by_tissue: Dict[str, float]
The activity of the promoter in each tissue.
query_name: Optional[str] = None
The name of the query. It will appear in the API response and can be used to
handle exceptions.
"""
activity_by_tissue: Dict[str, float]
query_name: Optional[str] = None
class PromoterActivityQuery(QueryBase):
"""A query to infer the activity of a promoter in different tissues.
Parameters
----------
promoter_sequence: str
The promoter sequence. Only ATGCN characters are allowed.
orf_sequence: str
The ORF sequence. Only ATGCN characters are allowed.
tissue_of_interest: Dict[str, List[str]]
The tissues of interest, with the tracks representing each tissue, for instance
`{"heart": ["CNhs10608+", "CNhs10612+"], "liver": ["CNhs10608+", "CNhs10612+"]}`.
query_name: Optional[str] = None
The name of the query. It will appear in the API response and can be used to
handle exceptions.
inference_framework: Literal["promoter-0"] = "promoter-0"
The inference framework to use for the inference. Currently only supports
borzoi_model: Literal["human-fold0"] = "human-fold0"
The model to use for the inference. Currently only supports the trained
model of "human-fold0".
Returns
-------
PromoterActivityResponse
``client.send_request(query)`` returns a ``PromoterActivityResponse`` with
attributes ``activity_by_tissue`` (the activity of the promoter in each tissue)
and ``query_name`` (the original query's name).
"""
promoter_sequence: str
orf_sequence: str
tissue_of_interest: Dict[str, List[str]]
source: str
inference_framework: Literal["promoter-0"] = "promoter-0"
borzoi_model: Literal["human-fold0"] = "human-fold0"
query_name: Optional[str] = None
def to_request_params(self) -> Dict:
# TODO: update the web API so the conversion isn't necessary
data = {
"prom": self.promoter_sequence,
"orf": self.orf_sequence,
"tissue_of_interest": self.tissue_of_interest,
"source": self.source,
}
return {
"model": f"borzoi-{self.borzoi_model}",
"text": json.dumps(data),
"transforms": [{"type": "PROMOTER_ACTIVITY"}],
}
def parse_response(self, results):
return PromoterActivityResponse(
query_name=self.query_name, activity_by_tissue=results
)
@pydantic.model_validator(mode="after")
def sequences_are_valid_nucleotide_sequences(cls, query):
"""Raise an error if the sequences contain non-ATGCN characters."""
query.promoter_sequence = query.promoter_sequence.upper()
query.orf_sequence = query.orf_sequence.upper()
if not set(query.promoter_sequence).issubset(set("ATGCN")):
raise ValueError(
f"Promoter sequence in query <{query.query_name}> contains "
"non-ATGCN characters."
)
if not set(query.orf_sequence).issubset(set("ATGCN")):
raise ValueError(
f"ORF sequence in query <{query.query_name}> contains "
"non-ATGCN characters."
)
return query
@classmethod
def iter_with_promoter_from_fasta(
cls,
fasta_path: str,
orf_sequence: str,
tissue_of_interest: Dict[str, List[str]],
source: str,
model: str = "borzoi-human-fold0",
):
"""Return an iterator of PromoterActivityQuery objects from the promoter
sequences in a fasta file. The iterator has a length attribute that gives the
number of sequences in the fasta file.
Parameters
----------
fasta_path: str
The path to the fasta file containing the promoter sequences.
orf_sequence: str
The ORF sequence.
tissue_of_interest: Dict[str, List[str]]
The tissues of interest, with the tracks representing each tissue, e.g.
`{"heart": ["CNhs10608+", "CNhs10612+"], "liver": ["CNhs10608+", "CNhs10612+"]}`.
model: str = "borzoi-human-fold0"
The model to use for the inference (only one default model is supported for now).
"""
fasta_iterator = fasta_sequence_iterator(fasta_path)
query_iterator = (
cls(
promoter_sequence=str(record.seq),
orf_sequence=orf_sequence,
tissue_of_interest=tissue_of_interest,
source=source,
model=model,
query_name=record.id,
)
for record in fasta_iterator
)
return IteratorWithLength(query_iterator, len(fasta_iterator))
@classmethod
def list_with_promoter_from_fasta(
cls,
fasta_path: str,
orf_sequence: str,
tissue_of_interest: Dict[str, List[str]],
source: str,
model: str = "borzoi-human-fold0",
):
"""Return a list of PromoterActivityQuery objects from the promoter sequences
in a fasta file.
Parameters
----------
fasta_path: str
The path to the fasta file containing the promoter sequences.
orf_sequence: str
The ORF sequence.
tissue_of_interest: Dict[str, List[str]]
The tissues of interest, with the tracks representing each tissue, e.g.
`{"heart": ["CNhs10608+", "CNhs10612+"], "liver": ["CNhs10608+", "CNhs10612+"]}`.
model: str = "borzoi-human-fold0"
The model to use for the inference (only one default model is supported for now).
"""
iterator = cls.iter_with_promoter_from_fasta(
fasta_path=fasta_path,
orf_sequence=orf_sequence,
tissue_of_interest=tissue_of_interest,
source=source,
model=model,
)
return list(iterator)
@classmethod
@lru_cache(maxsize=1)
def _get_full_tissue_dataframe(cls):
file_id = "13eQTxjqW3KMCzbaRYUSbZiyzXCaNYTIg"
url = f"https://drive.google.com/uc?export=download&id={file_id}"
tracks = pandas.read_csv(url)
return tracks
@classmethod
def get_tissue_track_dataframe(
cls, tissue: str = None, assay: str = None
) -> pandas.DataFrame:
"""Return a pandas DataFrame with the tissues and their corresponding tracks.
Parameters
----------
tissue: str, optional
If provided, only rows with the tissue name will be returned.
assay: str, optional
If provided, only rows with the assay name will be returned.
"""
df = cls._get_full_tissue_dataframe()
if tissue is not None:
df = df[df["sample"].str.contains(tissue, case=False)]
if assay is not None:
df = df[df.assay.str.contains(assay)]
return df
## ---- mRNA DIFFUSION QUERIES -----------------------------------------------------
class MultimodalDiffusionMaskedResponse(ResponseBase):
"""A response to a RNADiffusionMaskedQuery, with attributes `samples` (a list of predicted
samples, with modality name: predicted sequence) and `query_name` (the original query's name).
"""
samples: List[Dict[str, Union[int, str, float]]]
query_name: Optional[str] = None
class RNADiffusionMaskedQuery(QueryBase):
"""A query to perform masked sampling using a mRNA diffusion model.
Examples
--------
>>> query = RNADiffusionMaskedQuery(
... three_utr="ATTG<mask>TAC",
... five_utr="ATTG<mask>TAC",
... protein_sequence="ATTG<mask>TAC",
... species="HOMO_SAPIENS",
... model="mrna-foundation",
... temperature=1.0,
... decoding_order_strategy="entropy",
... unmaskings_per_step=4,
... )
>>> client.send_request(query)
DiffusionMaskedResponse([{"three_utr":, "five_utr":...}, ]], query_name=None)
"""
three_utr: str
five_utr: str
protein_sequence: str
species: str
temperature: float = 1.0
decoding_order_strategy: str = "max_prob"
unmaskings_per_step: int = 4
num_samples: int = 1
model: str
query_name: Optional[str] = None
def to_request_params(self) -> Dict:
data = {
# Many people in the field use [MASK] but our API client uses <mask> for all models
"three_utr": self.three_utr.replace("[MASK]", "<mask>"),
"five_utr": self.five_utr.replace("[MASK]", "<mask>"),
"sequence_aa": self.protein_sequence,
"species": self.species,
"temperature": self.temperature,
"decoding_order_strategy": self.decoding_order_strategy,
"unmaskings_per_step": self.unmaskings_per_step,
"num_samples": self.num_samples,
}
return {
"model": self.model,
"text": json.dumps(data),
"transforms": [{"type": "MRNA_DIFFUSION_GENERATE"}],
}
def parse_response(self, results: Dict) -> MultimodalDiffusionMaskedResponse:
"""
Parameters
----------
results: Dict
List of dictionaries with keys "three_utr","five_utr","sequence_aa","species"
"""
responses = results["samples"]
for response in responses:
response["codon_sequence"] = response.pop("sequence_aa")
response["protein_sequence"] = (
self.protein_sequence
) # add back in initial protein sequence that was queried
return MultimodalDiffusionMaskedResponse(
samples=responses,
query_name=self.query_name,
)
@classmethod
@lru_cache(maxsize=1)
def get_species_dataframe(cls):
file_id = "1PSkil-Ui0AkFXtYy4vJ7P6CG2QsztIxh"
url = f"https://drive.google.com/uc?export=download&id={file_id}"
df = pandas.read_csv(url).filter(["Species"])
df.Species = df.Species.str.upper() # OMNI code lower cases Species
return df
@pydantic.model_validator(mode="after")
def validate_query(cls, query):
_validate_model_and_sequence(query.model, query.three_utr, allow_masks=True)
_validate_model_and_sequence(query.model, query.five_utr, allow_masks=True)
# extra char for "-" that denotes end of the protein sequence
_validate_model_and_sequence(
"esm2-650M", query.protein_sequence, allow_masks=False, extra_chars=["-"]
)
if query.species not in cls.get_species_dataframe().Species.tolist():
raise ValueError(
"species is not valid. See cls.get_species_dataframe() for list of available species."
)
# Validate temperature
if not 0 <= query.temperature <= 1:
raise ValueError("temperature must be between 0 and 1")
# Validate decoding_order_strategy
if query.decoding_order_strategy not in ["max_prob", "entropy"]:
raise ValueError("decoding_order_strategy must be 'max_prob' or 'entropy'")
# Validate unmaskings_per_step
if not 1 <= query.unmaskings_per_step <= 1000:
raise ValueError("unmaskings_per_step must be between 1 and 1000")
return query
## ---- DIFFUSION QUERIES ---------------------------------------------------------
class DiffusionMaskedResponse(ResponseBase):
"""A response to a DiffusionMaskedQuery, with attributes `sequence` (the predicted
sequence) and `query_name` (the original query's name).
"""
sequence: str
query_name: Optional[str] = None
class DiffusionMaskedQuery(QueryBase):
"""A query to perform masked sampling using a diffusion model.
Parameters
----------
sequence: str
Input sequence for masked sampling. The sequence may contain "<mask>" tokens.
temperature: float, optional (default=0.5)
Sampling temperature, a value between 0 and 1.
decoding_order_strategy: str, optional (default="entropy")
Strategy for decoding order, must be either "max_prob" or "entropy".
unmaskings_per_step: int, optional (default=50)
Number of tokens to unmask per step, an integer between 1 and 1000.
model: str
The model to use for the inference.
query_name: Optional[str] = None
The name of the query. It will appear in the API response and can be used to handle exceptions.
Returns
-------
DiffusionMaskedResponse
``client.send_request(query)`` returns a ``DiffusionMaskedResponse`` with attributes
``sequence`` (the predicted sequence) and ``query_name`` (the original query's name).
Examples
--------
>>> query = DiffusionMaskedQuery(
... sequence="ATTG<mask>TAC",
... model="lcdna",
... temperature=0.7,
... decoding_order_strategy="entropy",
... unmaskings_per_step=20,
... )
>>> client.send_request(query)
DiffusionMaskedResponse(sequence="ATTGCGTAC", query_name=None)
"""
sequence: str
temperature: float = 0.5
decoding_order_strategy: str = "entropy"
unmaskings_per_step: int = 50
model: str
query_name: Optional[str] = None
def to_request_params(self) -> Dict:
data = {
"sequence": self.sequence,
"temperature": self.temperature,
"decoding_order_strategy": self.decoding_order_strategy,
"unmaskings_per_step": self.unmaskings_per_step,
}
return {
"model": self.model,
"text": json.dumps(data),
"transforms": [{"type": "DIFFUSION_GENERATE"}],
}
def parse_response(self, results: Dict) -> DiffusionMaskedResponse:
return DiffusionMaskedResponse(
sequence=results["sequence"][0],
query_name=self.query_name,
)
@pydantic.model_validator(mode="after")
def validate_query(cls, query):
sequence, model = query.sequence, query.model
# Validate sequence and model compatibility
_validate_model_and_sequence(
model=model,
sequence=sequence,
allow_masks=True,
)
# Validate temperature
if not 0 <= query.temperature <= 1:
raise ValueError("temperature must be between 0 and 1")
# Validate decoding_order_strategy
if query.decoding_order_strategy not in ["max_prob", "entropy"]:
raise ValueError("decoding_order_strategy must be 'max_prob' or 'entropy'")
# Validate unmaskings_per_step
if not 1 <= query.unmaskings_per_step <= 1000:
raise ValueError("unmaskings_per_step must be between 1 and 1000")
return query
## ---- STRUCTURE PREDICTION QUERIES ------------------------------------------------
class _Protein(pydantic.BaseModel):
id: Union[List[str], str]
sequence: str
@pydantic.validator("sequence")
def validate_sequence(cls, sequence):
if len(sequence) > 1000:
raise ValueError(
f"We currently only accept sequences of length 1000 or less for Boltz "
f"structure prediction (length: {len(sequence)})"
)
sequence = sequence.upper()
invalid_chars = [c for c in sequence if c not in "LAGVSERTIDPKQNFYMHWCXBUZO"]
if len(invalid_chars) > 0:
invalid_chars_str = ", ".join(sorted(set(invalid_chars)))
raise ValueError(
f"Sequence contains invalid characters: {invalid_chars_str}"
)
return sequence
class _CCD(pydantic.BaseModel):
id: Union[List[str], str]
ccd: str
class _Smiles(pydantic.BaseModel):
id: Union[List[str], str]
smiles: str
class BoltzStructurePredictionResponse(ResponseBase):
"""A response to a BoltzStructurePredictionQuery
Attributes
----------
cif_file_url: str
The URL of the cif file.
confidence_data: Dict[str, Any]
The confidence data.
query_name: Optional[str] = None
The name of the query. It will appear in the API response and can be used to
handle exceptions.
Examples
--------
.. code:: python
response = BoltzStructurePredictionResponse(
cif_file_url="https://example.com/structure.cif",
confidence_data={"confidence": 0.95},
query_name="my_query",
)
response.download_structure("structure.cif") # or...
response.download_structure("structure.pdb")
"""
cif_file_url: str
confidence_data: Dict[str, Any]
query_name: Optional[str] = None
def download_structure(self, path: str):
"""Download the structure from the URL and save it to a file."""
path = Path(path)
if str(path).endswith(".pdb"):
with tempfile.TemporaryDirectory() as temp_dir:
cif_path = Path(temp_dir) / "temp.cif"
self.download_structure(cif_path)
cif_to_pdb(cif_path, path)
else:
response = requests.get(self.cif_file_url)
with open(path, "w") as f:
f.write(response.text)
class BoltzStructurePredictionQuery(QueryBase):
"""A query to predict the structure of a protein using the Boltz model.
This type of query is better constructed using the `from_yaml_file` or
`from_protein_sequence` methods.
Parameters
----------
sequences: List[Dict[Literal["protein", "ligand"], Union[_Protein, _CCD, _Smiles]]]
The sequences to predict the structure for.
Only protein sequences of size <1000aa are supported for now.
model: Literal["boltz"] = "boltz"
The model to use for the inference (only Boltz(1) is supported for now).
query_name: Optional[str] = None
The name of the query. It will appear in the API response and can be used to
handle exceptions.
Examples
--------
.. code:: python
query = BoltzStructurePredictionQuery.from_yaml_file("input.yaml") # or below:
query = BoltzStructurePredictionQuery.from_protein_sequence("MLLKP")
response = client.send_request(query)
response.download_structure("structure.cif") # or below:
response.download_structure("structure.pdb")
"""
sequences: List[Dict[Literal["protein", "ligand"], Union[_Protein, _CCD, _Smiles]]]
model: Literal["boltz"] = "boltz"
query_name: Optional[str] = None
def to_request_params(self) -> Dict:
return {
"model": "boltz",
"transforms": [{"type": "INFER_STRUCTURE"}],
"text": self.model_dump(exclude=["model", "query_name"], mode="json"),
}
def parse_response(self, results: Dict) -> BoltzStructurePredictionResponse:
return BoltzStructurePredictionResponse(
cif_file_url=results["cif_file_url"],
confidence_data=results["confidence_data"],
query_name=self.query_name,
)
@classmethod
def from_yaml_file(cls, path, query_name: Optional[str] = "auto"):
path = Path(path)
if query_name == "auto":
query_name = path.name
with open(path, "r") as f:
data = yaml.load(f, yaml.SafeLoader)
return cls(sequences=data["sequences"], query_name=query_name)
@classmethod
def from_protein_sequence(cls, sequence: str, query_name: Optional[str] = None):
return cls(
sequences=[{"protein": {"id": "A", "sequence": sequence}}],
query_name=query_name,
)