rcsb-embedding-model 0.0.6__tar.gz → 0.0.8__tar.gz

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.

Potentially problematic release.


This version of rcsb-embedding-model might be problematic. Click here for more details.

Files changed (49) hide show
  1. {rcsb_embedding_model-0.0.6 → rcsb_embedding_model-0.0.8}/.gitignore +1 -0
  2. rcsb_embedding_model-0.0.8/PKG-INFO +129 -0
  3. rcsb_embedding_model-0.0.8/README.md +111 -0
  4. rcsb_embedding_model-0.0.8/examples/esm_embeddings.py +23 -0
  5. {rcsb_embedding_model-0.0.6 → rcsb_embedding_model-0.0.8}/pyproject.toml +1 -1
  6. {rcsb_embedding_model-0.0.6 → rcsb_embedding_model-0.0.8}/src/rcsb_embedding_model/cli/args_utils.py +0 -2
  7. rcsb_embedding_model-0.0.8/src/rcsb_embedding_model/cli/inference.py +271 -0
  8. rcsb_embedding_model-0.0.8/src/rcsb_embedding_model/dataset/esm_prot_from_chain.py +102 -0
  9. rcsb_embedding_model-0.0.8/src/rcsb_embedding_model/dataset/esm_prot_from_structure.py +63 -0
  10. rcsb_embedding_model-0.0.8/src/rcsb_embedding_model/dataset/resdiue_assembly_embedding_from_structure.py +68 -0
  11. rcsb_embedding_model-0.0.8/src/rcsb_embedding_model/dataset/residue_assembly_embedding_from_tensor_file.py +94 -0
  12. rcsb_embedding_model-0.0.8/src/rcsb_embedding_model/dataset/residue_embedding_from_tensor_file.py +43 -0
  13. rcsb_embedding_model-0.0.8/src/rcsb_embedding_model/inference/assembly_inferece.py +53 -0
  14. {rcsb_embedding_model-0.0.6 → rcsb_embedding_model-0.0.8}/src/rcsb_embedding_model/inference/chain_inference.py +12 -8
  15. {rcsb_embedding_model-0.0.6 → rcsb_embedding_model-0.0.8}/src/rcsb_embedding_model/inference/esm_inference.py +18 -8
  16. rcsb_embedding_model-0.0.8/src/rcsb_embedding_model/inference/structure_inference.py +61 -0
  17. rcsb_embedding_model-0.0.8/src/rcsb_embedding_model/modules/structure_module.py +27 -0
  18. {rcsb_embedding_model-0.0.6 → rcsb_embedding_model-0.0.8}/src/rcsb_embedding_model/rcsb_structure_embedding.py +7 -8
  19. rcsb_embedding_model-0.0.8/src/rcsb_embedding_model/types/api_types.py +51 -0
  20. {rcsb_embedding_model-0.0.6 → rcsb_embedding_model-0.0.8}/src/rcsb_embedding_model/utils/data.py +30 -0
  21. rcsb_embedding_model-0.0.8/src/rcsb_embedding_model/utils/structure_parser.py +81 -0
  22. rcsb_embedding_model-0.0.8/src/rcsb_embedding_model/utils/structure_provider.py +27 -0
  23. rcsb_embedding_model-0.0.8/tests/resources/embeddings/1acb.A.pt +0 -0
  24. rcsb_embedding_model-0.0.8/tests/resources/embeddings/1acb.B.pt +0 -0
  25. rcsb_embedding_model-0.0.8/tests/resources/embeddings/2uzi.A.pt +0 -0
  26. rcsb_embedding_model-0.0.8/tests/resources/embeddings/2uzi.B.pt +0 -0
  27. rcsb_embedding_model-0.0.8/tests/resources/embeddings/2uzi.C.pt +0 -0
  28. rcsb_embedding_model-0.0.8/tests/resources/esm-from-chain-inference.csv +2 -0
  29. rcsb_embedding_model-0.0.8/tests/resources/pdb/2uzi.cif +6685 -0
  30. {rcsb_embedding_model-0.0.6 → rcsb_embedding_model-0.0.8}/tests/test_embedding_model.py +8 -8
  31. rcsb_embedding_model-0.0.8/tests/test_inference.py +154 -0
  32. rcsb_embedding_model-0.0.6/PKG-INFO +0 -117
  33. rcsb_embedding_model-0.0.6/README.md +0 -99
  34. rcsb_embedding_model-0.0.6/examples/esm_embeddings.py +0 -77
  35. rcsb_embedding_model-0.0.6/src/rcsb_embedding_model/cli/inference.py +0 -149
  36. rcsb_embedding_model-0.0.6/src/rcsb_embedding_model/dataset/esm_prot_from_csv.py +0 -91
  37. rcsb_embedding_model-0.0.6/src/rcsb_embedding_model/dataset/residue_embedding_from_csv.py +0 -32
  38. rcsb_embedding_model-0.0.6/src/rcsb_embedding_model/types/api_types.py +0 -29
  39. rcsb_embedding_model-0.0.6/src/rcsb_embedding_model/utils/structure_parser.py +0 -51
  40. {rcsb_embedding_model-0.0.6 → rcsb_embedding_model-0.0.8}/LICENSE.md +0 -0
  41. {rcsb_embedding_model-0.0.6 → rcsb_embedding_model-0.0.8}/assets/embedding-model-architecture.png +0 -0
  42. {rcsb_embedding_model-0.0.6 → rcsb_embedding_model-0.0.8}/src/rcsb_embedding_model/__init__.py +0 -0
  43. {rcsb_embedding_model-0.0.6 → rcsb_embedding_model-0.0.8}/src/rcsb_embedding_model/model/layers.py +0 -0
  44. {rcsb_embedding_model-0.0.6 → rcsb_embedding_model-0.0.8}/src/rcsb_embedding_model/model/residue_embedding_aggregator.py +0 -0
  45. {rcsb_embedding_model-0.0.6 → rcsb_embedding_model-0.0.8}/src/rcsb_embedding_model/modules/chain_module.py +0 -0
  46. {rcsb_embedding_model-0.0.6 → rcsb_embedding_model-0.0.8}/src/rcsb_embedding_model/modules/esm_module.py +0 -0
  47. {rcsb_embedding_model-0.0.6 → rcsb_embedding_model-0.0.8}/src/rcsb_embedding_model/utils/model.py +0 -0
  48. {rcsb_embedding_model-0.0.6 → rcsb_embedding_model-0.0.8}/src/rcsb_embedding_model/writer/batch_writer.py +0 -0
  49. {rcsb_embedding_model-0.0.6/tests/resources → rcsb_embedding_model-0.0.8/tests/resources/pdb}/1acb.cif +0 -0
@@ -2,3 +2,4 @@
2
2
  /rcsb-embedding-model.iml
3
3
  /dist/
4
4
  /.pypi.rc
5
+ __pycache__
@@ -0,0 +1,129 @@
1
+ Metadata-Version: 2.4
2
+ Name: rcsb-embedding-model
3
+ Version: 0.0.8
4
+ Summary: Protein Embedding Model for Structure Search
5
+ Project-URL: Homepage, https://github.com/rcsb/rcsb-embedding-model
6
+ Project-URL: Issues, https://github.com/rcsb/rcsb-embedding-model/issues
7
+ Author-email: Joan Segura <joan.segura@rcsb.org>
8
+ License-Expression: BSD-3-Clause
9
+ License-File: LICENSE.md
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.10
13
+ Requires-Dist: esm>=3.2.0
14
+ Requires-Dist: lightning>=2.5.0
15
+ Requires-Dist: torch>=2.2.0
16
+ Requires-Dist: typer>=0.15.0
17
+ Description-Content-Type: text/markdown
18
+
19
+ # RCSB Embedding Model
20
+
21
+ **Version** 0.0.8
22
+
23
+
24
+ ## Overview
25
+
26
+ RCSB Embedding Model is a neural network architecture designed to encode macromolecular 3D structures into fixed-length vector embeddings for efficient large-scale structure similarity search.
27
+
28
+ Preprint: [Multi-scale structural similarity embedding search across entire proteomes](https://www.biorxiv.org/content/10.1101/2025.02.28.640875v1).
29
+
30
+ A web-based implementation using this model for structure similarity search is available at [rcsb-embedding-search](http://embedding-search.rcsb.org).
31
+
32
+ If you are interested in training the model with a new dataset, visit the [rcsb-embedding-search repository](https://github.com/bioinsilico/rcsb-embedding-search), which provides scripts and documentation for training.
33
+
34
+
35
+ ## Features
36
+
37
+ - **Residue-level embeddings** computed using the ESM3 protein language model
38
+ - **Structure-level embeddings** aggregated via a transformer-based aggregator network
39
+ - **Command-line interface** implemented with Typer for high-throughput inference workflows
40
+ - **Python API** for interactive embedding computation and integration into analysis pipelines
41
+ - **High-performance inference** leveraging PyTorch Lightning, with multi-node and multi-GPU support
42
+
43
+ ---
44
+
45
+ ## Installation
46
+
47
+ pip install rcsb-embedding-model
48
+
49
+ **Requirements:**
50
+
51
+ - Python ≥ 3.10
52
+ - ESM ≥ 3.2.0
53
+ - PyTorch ≥ 2.2.0
54
+ - Lightning ≥ 2.5.0
55
+ - Typer ≥ 0.15.0
56
+
57
+ ---
58
+
59
+ ## Quick Start
60
+
61
+ ### CLI
62
+
63
+ # 1. Compute residue embeddings: Calculate residue level embeddings of protein structures using ESM3. Predictions are stored as torch tensor files.
64
+ inference residue-embedding --src-file data/structures.csv --output-path results/residue_embeddings --structure-format mmcif --batch-size 8 --devices auto
65
+
66
+ # 2. Compute structure embeddings: Calculate single-chain protein embeddings from structural files. Predictions are stored in a single pandas DataFrame file.
67
+ inference structure-embedding --src-file data/structures.csv --output-path results/residue_embeddings --out-df-name df-res-embeddings --batch-size 4 --devices 0 --devives 1
68
+
69
+ # 3. Compute chain embeddings: Calculate single-chain protein embeddings from residue level embeddings stored as torch tensor files. Predictions a re stored as csv files.
70
+ inference chain-embedding --src-file data/structures.csv --output-path results/chain_embeddings --batch-size 4
71
+
72
+ # 4. Compute assembly embeddings: Calculate assembly embeddings from residue level embeddings stored as torch tensor files. Predictions are stored as csv files.
73
+ inference assembly-embedding --src-file data/structures.csv --res-embedding-location results/residue_embeddings --output-path results/assembly_embeddings
74
+
75
+ ### Python API
76
+
77
+ from rcsb_embedding_model import RcsbStructureEmbedding
78
+
79
+ model = RcsbStructureEmbedding()
80
+
81
+ # Compute per-residue embeddings
82
+ res_emb = model.residue_embedding(
83
+ src_structure="examples/1abc.cif",
84
+ src_format="mmcif",
85
+ chain_id="A"
86
+ )
87
+
88
+ # Aggregate to structure-level embedding
89
+ struct_emb = model.aggregator_embedding(res_emb)
90
+
91
+ See the examples and tests directories for more use cases.
92
+
93
+ ---
94
+
95
+ ## Model Architecture
96
+
97
+ The embedding model is trained to predict structural similarity by approximating TM-scores using cosine distances between embeddings. It consists of two main components:
98
+
99
+ - **Protein Language Model (PLM)**: Computes residue-level embeddings from a given 3D structure.
100
+ - **Residue Embedding Aggregator**: A transformer-based neural network that aggregates these residue-level embeddings into a single vector.
101
+
102
+ ![Embedding model architecture](assets/embedding-model-architecture.png)
103
+
104
+ ### **Protein Language Model (PLM)**
105
+ Residue-wise embeddings of protein structures are computed using the [ESM3](https://www.evolutionaryscale.ai/) generative protein language model.
106
+
107
+ ### **Residue Embedding Aggregator**
108
+ The aggregation component consists of six transformer encoder layers, each with a 3,072-neuron feedforward layer and ReLU activations. After processing through these layers, a summation pooling operation is applied, followed by 12 fully connected residual layers that refine the embeddings into a single 1,536-dimensional vector.
109
+
110
+ ---
111
+
112
+ ## Development
113
+
114
+ git clone https://github.com/rcsb/rcsb-embedding-model.git
115
+ cd rcsb-embedding-model
116
+ pip install -e .
117
+ pytest
118
+
119
+ ---
120
+
121
+ ## Citation
122
+
123
+ Segura, J., Bittrich, S., et al. (2024). *Multi-scale structural similarity embedding search across entire proteomes*. bioRxiv. (Preprint: https://www.biorxiv.org/content/10.1101/2025.02.28.640875v1)
124
+
125
+ ---
126
+
127
+ ## License
128
+
129
+ This project is licensed under the BSD 3-Clause License. See [LICENSE.md](LICENSE.md) for details.
@@ -0,0 +1,111 @@
1
+ # RCSB Embedding Model
2
+
3
+ **Version** 0.0.8
4
+
5
+
6
+ ## Overview
7
+
8
+ RCSB Embedding Model is a neural network architecture designed to encode macromolecular 3D structures into fixed-length vector embeddings for efficient large-scale structure similarity search.
9
+
10
+ Preprint: [Multi-scale structural similarity embedding search across entire proteomes](https://www.biorxiv.org/content/10.1101/2025.02.28.640875v1).
11
+
12
+ A web-based implementation using this model for structure similarity search is available at [rcsb-embedding-search](http://embedding-search.rcsb.org).
13
+
14
+ If you are interested in training the model with a new dataset, visit the [rcsb-embedding-search repository](https://github.com/bioinsilico/rcsb-embedding-search), which provides scripts and documentation for training.
15
+
16
+
17
+ ## Features
18
+
19
+ - **Residue-level embeddings** computed using the ESM3 protein language model
20
+ - **Structure-level embeddings** aggregated via a transformer-based aggregator network
21
+ - **Command-line interface** implemented with Typer for high-throughput inference workflows
22
+ - **Python API** for interactive embedding computation and integration into analysis pipelines
23
+ - **High-performance inference** leveraging PyTorch Lightning, with multi-node and multi-GPU support
24
+
25
+ ---
26
+
27
+ ## Installation
28
+
29
+ pip install rcsb-embedding-model
30
+
31
+ **Requirements:**
32
+
33
+ - Python ≥ 3.10
34
+ - ESM ≥ 3.2.0
35
+ - PyTorch ≥ 2.2.0
36
+ - Lightning ≥ 2.5.0
37
+ - Typer ≥ 0.15.0
38
+
39
+ ---
40
+
41
+ ## Quick Start
42
+
43
+ ### CLI
44
+
45
+ # 1. Compute residue embeddings: Calculate residue level embeddings of protein structures using ESM3. Predictions are stored as torch tensor files.
46
+ inference residue-embedding --src-file data/structures.csv --output-path results/residue_embeddings --structure-format mmcif --batch-size 8 --devices auto
47
+
48
+ # 2. Compute structure embeddings: Calculate single-chain protein embeddings from structural files. Predictions are stored in a single pandas DataFrame file.
49
+ inference structure-embedding --src-file data/structures.csv --output-path results/residue_embeddings --out-df-name df-res-embeddings --batch-size 4 --devices 0 --devives 1
50
+
51
+ # 3. Compute chain embeddings: Calculate single-chain protein embeddings from residue level embeddings stored as torch tensor files. Predictions a re stored as csv files.
52
+ inference chain-embedding --src-file data/structures.csv --output-path results/chain_embeddings --batch-size 4
53
+
54
+ # 4. Compute assembly embeddings: Calculate assembly embeddings from residue level embeddings stored as torch tensor files. Predictions are stored as csv files.
55
+ inference assembly-embedding --src-file data/structures.csv --res-embedding-location results/residue_embeddings --output-path results/assembly_embeddings
56
+
57
+ ### Python API
58
+
59
+ from rcsb_embedding_model import RcsbStructureEmbedding
60
+
61
+ model = RcsbStructureEmbedding()
62
+
63
+ # Compute per-residue embeddings
64
+ res_emb = model.residue_embedding(
65
+ src_structure="examples/1abc.cif",
66
+ src_format="mmcif",
67
+ chain_id="A"
68
+ )
69
+
70
+ # Aggregate to structure-level embedding
71
+ struct_emb = model.aggregator_embedding(res_emb)
72
+
73
+ See the examples and tests directories for more use cases.
74
+
75
+ ---
76
+
77
+ ## Model Architecture
78
+
79
+ The embedding model is trained to predict structural similarity by approximating TM-scores using cosine distances between embeddings. It consists of two main components:
80
+
81
+ - **Protein Language Model (PLM)**: Computes residue-level embeddings from a given 3D structure.
82
+ - **Residue Embedding Aggregator**: A transformer-based neural network that aggregates these residue-level embeddings into a single vector.
83
+
84
+ ![Embedding model architecture](assets/embedding-model-architecture.png)
85
+
86
+ ### **Protein Language Model (PLM)**
87
+ Residue-wise embeddings of protein structures are computed using the [ESM3](https://www.evolutionaryscale.ai/) generative protein language model.
88
+
89
+ ### **Residue Embedding Aggregator**
90
+ The aggregation component consists of six transformer encoder layers, each with a 3,072-neuron feedforward layer and ReLU activations. After processing through these layers, a summation pooling operation is applied, followed by 12 fully connected residual layers that refine the embeddings into a single 1,536-dimensional vector.
91
+
92
+ ---
93
+
94
+ ## Development
95
+
96
+ git clone https://github.com/rcsb/rcsb-embedding-model.git
97
+ cd rcsb-embedding-model
98
+ pip install -e .
99
+ pytest
100
+
101
+ ---
102
+
103
+ ## Citation
104
+
105
+ Segura, J., Bittrich, S., et al. (2024). *Multi-scale structural similarity embedding search across entire proteomes*. bioRxiv. (Preprint: https://www.biorxiv.org/content/10.1101/2025.02.28.640875v1)
106
+
107
+ ---
108
+
109
+ ## License
110
+
111
+ This project is licensed under the BSD 3-Clause License. See [LICENSE.md](LICENSE.md) for details.
@@ -0,0 +1,23 @@
1
+ import argparse
2
+
3
+ from rcsb_embedding_model import RcsbStructureEmbedding
4
+
5
+ if __name__ == "__main__":
6
+
7
+ parser = argparse.ArgumentParser()
8
+ parser.add_argument('--file', type=str, required=True)
9
+ parser.add_argument('--file_format', type=str)
10
+ parser.add_argument('--chain', type=str)
11
+ args = parser.parse_args()
12
+
13
+ model = RcsbStructureEmbedding()
14
+ res_embedding = model.residue_embedding(
15
+ src_structure=args.file,
16
+ src_format=args.file_format,
17
+ chain_id=args.chain
18
+ )
19
+ structure_embedding = model.aggregator_embedding(
20
+ res_embedding
21
+ )
22
+
23
+ print(res_embedding.shape, structure_embedding.shape)
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "rcsb-embedding-model"
3
- version = "0.0.6"
3
+ version = "0.0.8"
4
4
  authors = [
5
5
  { name="Joan Segura", email="joan.segura@rcsb.org" },
6
6
  ]
@@ -1,6 +1,4 @@
1
1
 
2
- from enum import Enum
3
-
4
2
 
5
3
  def arg_devices(devices):
6
4
  if len(devices) == 1:
@@ -0,0 +1,271 @@
1
+ import sys
2
+ from typing import Annotated, List
3
+
4
+ import typer
5
+
6
+ from rcsb_embedding_model.cli.args_utils import arg_devices
7
+ from rcsb_embedding_model.types.api_types import StructureFormat, Accelerator, SrcLocation, SrcProteinFrom, \
8
+ StructureLocation, SrcAssemblyFrom
9
+
10
+ app = typer.Typer(
11
+ add_completion=False
12
+ )
13
+
14
+
15
+ @app.command(
16
+ name="residue-embedding",
17
+ help="Calculate residue level embeddings of protein structures using ESM3. Predictions are stored as torch tensor files."
18
+ )
19
+ def residue_embedding(
20
+ src_file: Annotated[typer.FileText, typer.Option(
21
+ exists=True,
22
+ file_okay=True,
23
+ dir_okay=False,
24
+ resolve_path=True,
25
+ help='CSV file 4 (or 3) columns: Structure Name | Structure File Path | Chain Id (asym_i for cif files. This field is required if src-from=chain) | Output Embedding Name.'
26
+ )],
27
+ output_path: Annotated[typer.FileText, typer.Option(
28
+ exists=True,
29
+ file_okay=False,
30
+ dir_okay=True,
31
+ resolve_path=True,
32
+ help='Output path to store predictions. Embeddings are stored as torch tensor files.'
33
+ )],
34
+ src_from: Annotated[SrcProteinFrom, typer.Option(
35
+ help='Use specific chains or all chains in a structure.'
36
+ )] = SrcProteinFrom.chain,
37
+ structure_location: Annotated[StructureLocation, typer.Option(
38
+ help='Structure file location.'
39
+ )] = StructureLocation.local,
40
+ structure_format: Annotated[StructureFormat, typer.Option(
41
+ help='Structure file format.'
42
+ )] = StructureFormat.mmcif,
43
+ min_res_n: Annotated[int, typer.Option(
44
+ help='When using all chains in a structure, consider only chains with more than <min_res_n> residues.'
45
+ )] = 0,
46
+ batch_size: Annotated[int, typer.Option(
47
+ help='Number of samples processed together in one iteration.'
48
+ )] = 1,
49
+ num_workers: Annotated[int, typer.Option(
50
+ help='Number of subprocesses to use for data loading.'
51
+ )] = 0,
52
+ num_nodes: Annotated[int, typer.Option(
53
+ help='Number of nodes to use for inference.'
54
+ )] = 1,
55
+ accelerator: Annotated[Accelerator, typer.Option(
56
+ help='Device used for inference.'
57
+ )] = Accelerator.auto,
58
+ devices: Annotated[List[str], typer.Option(
59
+ help='The devices to use. Can be set to a positive number or "auto". Repeat this argument to indicate multiple indices of devices. "auto" for automatic selection based on the chosen accelerator.'
60
+ )] = tuple(['auto'])
61
+ ):
62
+ from rcsb_embedding_model.inference.esm_inference import predict
63
+ predict(
64
+ src_stream=src_file,
65
+ src_location=SrcLocation.local,
66
+ src_from=src_from,
67
+ structure_location=structure_location,
68
+ structure_format=structure_format,
69
+ min_res_n=min_res_n,
70
+ batch_size=batch_size,
71
+ num_workers=num_workers,
72
+ num_nodes=num_nodes,
73
+ accelerator=accelerator,
74
+ devices=arg_devices(devices),
75
+ out_path=output_path
76
+ )
77
+
78
+
79
+ @app.command(
80
+ name="structure-embedding",
81
+ help="Calculate single-chain protein embeddings from structural files. Predictions are stored in a single pandas DataFrame file."
82
+ )
83
+ def structure_embedding(
84
+ src_file: Annotated[typer.FileText, typer.Option(
85
+ exists=True,
86
+ file_okay=True,
87
+ dir_okay=False,
88
+ resolve_path=True,
89
+ help='CSV file 4 (or 3) columns: Structure Name | Structure File Path | Chain Id (asym_i for cif files. This field is required if src-from=chain) | Output Embedding Name.'
90
+ )],
91
+ output_path: Annotated[typer.FileText, typer.Option(
92
+ exists=True,
93
+ file_okay=False,
94
+ dir_okay=True,
95
+ resolve_path=True,
96
+ help='Output path to store predictions. Embeddings are stored as a single DataFrame file (see out-df-name).'
97
+ )],
98
+ out_df_name: Annotated[str, typer.Option(
99
+ help='File name (without extension) for storing embeddings as a pandas DataFrame pickle (.pkl). The DataFrame contains 2 columns: Id | Embedding'
100
+ )],
101
+ src_from: Annotated[SrcProteinFrom, typer.Option(
102
+ help='Use specific chains or all chains in a structure.'
103
+ )] = SrcProteinFrom.chain,
104
+ structure_location: Annotated[StructureLocation, typer.Option(
105
+ help='Source input location.'
106
+ )] = StructureLocation.local,
107
+ structure_format: Annotated[StructureFormat, typer.Option(
108
+ help='Structure file format.'
109
+ )] = StructureFormat.mmcif,
110
+ min_res_n: Annotated[int, typer.Option(
111
+ help='When using all chains in a structure, consider only chains with more than <min_res_n> residues.'
112
+ )] = 0,
113
+ batch_size: Annotated[int, typer.Option(
114
+ help='Number of samples processed together in one iteration.'
115
+ )] = 1,
116
+ num_workers: Annotated[int, typer.Option(
117
+ help='Number of subprocesses to use for data loading.'
118
+ )] = 0,
119
+ num_nodes: Annotated[int, typer.Option(
120
+ help='Number of nodes to use for inference.'
121
+ )] = 1,
122
+ accelerator: Annotated[Accelerator, typer.Option(
123
+ help='Device used for inference.'
124
+ )] = Accelerator.auto,
125
+ devices: Annotated[List[str], typer.Option(
126
+ help='The devices to use. Can be set to a positive number or "auto". Repeat this argument to indicate multiple indices of devices. "auto" for automatic selection based on the chosen accelerator.'
127
+ )] = tuple(['auto'])
128
+ ):
129
+ from rcsb_embedding_model.inference.structure_inference import predict
130
+ predict(
131
+ src_stream=src_file,
132
+ src_location=SrcLocation.local,
133
+ src_from=src_from,
134
+ structure_location=structure_location,
135
+ structure_format=structure_format,
136
+ min_res_n=min_res_n,
137
+ batch_size=batch_size,
138
+ num_workers=num_workers,
139
+ num_nodes=num_nodes,
140
+ accelerator=accelerator,
141
+ devices=arg_devices(devices),
142
+ out_path=output_path,
143
+ out_df_name=out_df_name
144
+ )
145
+
146
+
147
+ @app.command(
148
+ name="chain-embedding",
149
+ help="Calculate single-chain protein embeddings from residue level embeddings stored as torch tensor files. Predictions are stored as csv files."
150
+ )
151
+ def chain_embedding(
152
+ src_file: Annotated[typer.FileText, typer.Option(
153
+ exists=True,
154
+ file_okay=True,
155
+ dir_okay=False,
156
+ resolve_path=True,
157
+ help='CSV file 2 columns: Residue embedding torch tensor file | Output embedding name.'
158
+ )],
159
+ output_path: Annotated[typer.FileText, typer.Option(
160
+ exists=True,
161
+ file_okay=False,
162
+ dir_okay=True,
163
+ resolve_path=True,
164
+ help='Output path to store predictions. Embeddings are stored as csv files.'
165
+ )],
166
+ batch_size: Annotated[int, typer.Option(
167
+ help='Number of samples processed together in one iteration.'
168
+ )] = 1,
169
+ num_workers: Annotated[int, typer.Option(
170
+ help='Number of subprocesses to use for data loading.'
171
+ )] = 0,
172
+ num_nodes: Annotated[int, typer.Option(
173
+ help='Number of nodes to use for inference.'
174
+ )] = 1,
175
+ accelerator: Annotated[Accelerator, typer.Option(
176
+ help='Device used for inference.'
177
+ )] = Accelerator.auto,
178
+ devices: Annotated[List[str], typer.Option(
179
+ help='The devices to use. Can be set to a positive number or "auto". Repeat this argument to indicate multiple indices of devices. "auto" for automatic selection based on the chosen accelerator.'
180
+ )] = tuple(['auto'])
181
+ ):
182
+ from rcsb_embedding_model.inference.chain_inference import predict
183
+ predict(
184
+ src_stream=src_file,
185
+ src_location=SrcLocation.local,
186
+ batch_size=batch_size,
187
+ num_workers=num_workers,
188
+ num_nodes=num_nodes,
189
+ accelerator=accelerator,
190
+ devices=arg_devices(devices),
191
+ out_path=output_path
192
+ )
193
+
194
+ @app.command(
195
+ name="assembly-embedding",
196
+ help="Calculate assembly embeddings from residue level embeddings stored as torch tensor files. Predictions are stored as csv files."
197
+ )
198
+ def assembly_embedding(
199
+ src_file: Annotated[typer.FileText, typer.Option(
200
+ exists=True,
201
+ file_okay=True,
202
+ dir_okay=False,
203
+ resolve_path=True,
204
+ help='CSV file 4 columns: Structure Name | Structure File Path | Assembly Id | Output embedding name.'
205
+ )],
206
+ res_embedding_location: Annotated[typer.FileText, typer.Option(
207
+ exists=True,
208
+ file_okay=False,
209
+ dir_okay=True,
210
+ resolve_path=True,
211
+ help='Path where residue level embeddings for single chains are located.'
212
+ )],
213
+ output_path: Annotated[typer.FileText, typer.Option(
214
+ exists=True,
215
+ file_okay=False,
216
+ dir_okay=True,
217
+ resolve_path=True,
218
+ help='Output path to store predictions. Embeddings are stored as csv files.'
219
+ )],
220
+ src_from: Annotated[SrcAssemblyFrom, typer.Option(
221
+ help='Use specific assembly or all assemblies in a structure.'
222
+ )] = SrcAssemblyFrom.assembly,
223
+ structure_location: Annotated[StructureLocation, typer.Option(
224
+ help='Source input location.'
225
+ )] = StructureLocation.local,
226
+ structure_format: Annotated[StructureFormat, typer.Option(
227
+ help='Structure file format.'
228
+ )] = StructureFormat.mmcif,
229
+ min_res_n: Annotated[int, typer.Option(
230
+ help='Consider only assembly chains with more than <min_res_n> residues.'
231
+ )] = 0,
232
+ max_res_n: Annotated[int, typer.Option(
233
+ help='Stop adding assembly chains when number of residues is greater than <max_res_n> residues.'
234
+ )] = sys.maxsize,
235
+ batch_size: Annotated[int, typer.Option(
236
+ help='Number of samples processed together in one iteration.'
237
+ )] = 1,
238
+ num_workers: Annotated[int, typer.Option(
239
+ help='Number of subprocesses to use for data loading.'
240
+ )] = 0,
241
+ num_nodes: Annotated[int, typer.Option(
242
+ help='Number of nodes to use for inference.'
243
+ )] = 1,
244
+ accelerator: Annotated[Accelerator, typer.Option(
245
+ help='Device used for inference.'
246
+ )] = Accelerator.auto,
247
+ devices: Annotated[List[str], typer.Option(
248
+ help='The devices to use. Can be set to a positive number or "auto". Repeat this argument to indicate multiple indices of devices. "auto" for automatic selection based on the chosen accelerator.'
249
+ )] = tuple(['auto'])
250
+ ):
251
+ from rcsb_embedding_model.inference.assembly_inferece import predict
252
+ predict(
253
+ src_stream=src_file,
254
+ res_embedding_location=res_embedding_location,
255
+ src_location=SrcLocation.local,
256
+ src_from=src_from,
257
+ structure_location=structure_location,
258
+ structure_format=structure_format,
259
+ min_res_n=min_res_n,
260
+ max_res_n=max_res_n,
261
+ batch_size=batch_size,
262
+ num_workers=num_workers,
263
+ num_nodes=num_nodes,
264
+ accelerator=accelerator,
265
+ devices=arg_devices(devices),
266
+ out_path=output_path
267
+ )
268
+
269
+
270
+ if __name__ == "__main__":
271
+ app()
@@ -0,0 +1,102 @@
1
+ import argparse
2
+
3
+ import torch
4
+ from biotite.structure import chain_iter
5
+ from esm.models.esm3 import ESM3
6
+ from esm.sdk.api import ESMProtein, SamplingConfig
7
+ from esm.utils.constants.models import ESM3_OPEN_SMALL
8
+ from esm.utils.structure.protein_chain import ProteinChain
9
+ from torch.utils.data import Dataset, DataLoader
10
+ import pandas as pd
11
+
12
+ from rcsb_embedding_model.types.api_types import StructureFormat, StructureLocation, SrcLocation
13
+ from rcsb_embedding_model.utils.data import stringio_from_url
14
+ from rcsb_embedding_model.utils.structure_parser import rename_atom_ch
15
+ from rcsb_embedding_model.utils.structure_provider import StructureProvider
16
+
17
+
18
+ class EsmProtFromChain(Dataset):
19
+
20
+ STREAM_NAME_ATTR = 'stream_name'
21
+ STREAM_ATTR = 'stream'
22
+ CH_ATTR = 'chain_id'
23
+ ITEM_NAME_ATTR = 'item_name'
24
+
25
+ COLUMNS = [STREAM_NAME_ATTR, STREAM_ATTR, CH_ATTR, ITEM_NAME_ATTR]
26
+
27
+ def __init__(
28
+ self,
29
+ src_stream,
30
+ src_location=SrcLocation.local,
31
+ structure_location=StructureLocation.local,
32
+ structure_format=StructureFormat.mmcif,
33
+ structure_provider=StructureProvider()
34
+ ):
35
+ super().__init__()
36
+ self.__structure_provider = structure_provider
37
+ self.src_location = src_location
38
+ self.structure_location = structure_location
39
+ self.structure_format = structure_format
40
+ self.data = pd.DataFrame()
41
+ self.__load_stream(src_stream)
42
+
43
+ def __load_stream(self, src_stream):
44
+ self.data = pd.DataFrame(
45
+ src_stream,
46
+ dtype=str,
47
+ columns=EsmProtFromChain.COLUMNS
48
+ ) if self.src_location == SrcLocation.stream else pd.read_csv(
49
+ src_stream,
50
+ header=None,
51
+ index_col=None,
52
+ dtype=str,
53
+ names=EsmProtFromChain.COLUMNS
54
+ )
55
+
56
+ def __len__(self):
57
+ return len(self.data)
58
+
59
+ def __getitem__(self, idx):
60
+ src_name = self.data.loc[idx, EsmProtFromChain.STREAM_NAME_ATTR]
61
+ src_structure = self.data.loc[idx, EsmProtFromChain.STREAM_ATTR]
62
+ chain_id = self.data.loc[idx, EsmProtFromChain.CH_ATTR]
63
+ item_name = self.data.loc[idx, EsmProtFromChain.ITEM_NAME_ATTR]
64
+ structure = self.__structure_provider.get_structure(
65
+ src_name=src_name,
66
+ src_structure=stringio_from_url(src_structure) if self.structure_location == StructureLocation.remote else src_structure,
67
+ structure_format=self.structure_format,
68
+ chain_id=chain_id
69
+ )
70
+ for atom_ch in chain_iter(structure):
71
+ protein_chain = ProteinChain.from_atomarray(rename_atom_ch(atom_ch))
72
+ return ESMProtein.from_protein_chain(protein_chain), item_name
73
+
74
+
75
+ if __name__ == '__main__':
76
+
77
+ parser = argparse.ArgumentParser()
78
+ parser.add_argument('--file_list', type=argparse.FileType('r'), required=True)
79
+ args = parser.parse_args()
80
+
81
+ dataset = EsmProtFromChain(
82
+ args.file_list
83
+ )
84
+
85
+ esm3 = ESM3.from_pretrained(
86
+ ESM3_OPEN_SMALL,
87
+ torch.device("cpu")
88
+ )
89
+
90
+ dataloader = DataLoader(
91
+ dataset,
92
+ batch_size=2,
93
+ collate_fn=lambda _: _
94
+ )
95
+
96
+ for _batch in dataloader:
97
+ for esm_prot, prot_name in _batch:
98
+ protein_tensor = esm3.encode(esm_prot)
99
+ embeddings = esm3.forward_and_sample(
100
+ protein_tensor, SamplingConfig(return_per_residue_embeddings=True)
101
+ ).per_residue_embedding
102
+ print(prot_name, embeddings.shape)