karina-zadorozhny commited on
Commit
d5fe9b8
·
verified ·
1 Parent(s): ae8c027

Upload process_atomica.py

Browse files
Files changed (1) hide show
  1. process_atomica.py +240 -0
process_atomica.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import tempfile
3
+ import logging
4
+ import requests
5
+ import pandas as pd
6
+ from tqdm import tqdm
7
+ from rdkit import Chem
8
+ import pooch
9
+ from concurrent.futures import ThreadPoolExecutor, as_completed
10
+ from lobster.data import upload_to_s3
11
+
12
+ logging.basicConfig(level=logging.INFO)
13
+ logger = logging.getLogger(__name__)
14
+
15
+ S3_BASE_URI = os.environ["S3_BASE_URI"]
16
+ S3_RAW = f"{S3_BASE_URI}/raw"
17
+ S3_PROCESSED = f"{S3_BASE_URI}/pre-processed"
18
+
19
+ MAX_WORKERS = 16 # for threading
20
+
21
+ MODALITY_MAPPING = {
22
+ "polypeptide(L)": "amino_acid",
23
+ "polynucleotide": "nucleotide",
24
+ "polyribonucleotide": "nucleotide",
25
+ "polynucleotide (RNA)": "nucleotide",
26
+ "polynucleotide (DNA)": "nucleotide",
27
+ "polydeoxyribonucleotide": "nucleotide",
28
+ "polydeoxyribonucleotide/polyribonucleotide hybrid ": "nucleotide",
29
+ "smiles": "smiles",
30
+ }
31
+
32
+ IDENTIFIERS = {
33
+ "protein-peptide": "11033993",
34
+ "protein-rna": "11033983",
35
+ "protein-protein": "11033984",
36
+ "rna-small_molecule": "11033985",
37
+ "protein-small_molecule": "11033996",
38
+ "protein-ion": "11033989",
39
+ "protein-dna": "11033982",
40
+ "small_molecule-small_molecule": "11033997",
41
+ }
42
+
43
+ def upload_raw_datasets_to_s3() -> None:
44
+ for fname, identifier in IDENTIFIERS.items():
45
+ with tempfile.TemporaryDirectory() as tmpdir:
46
+ local_path = pooch.retrieve(
47
+ f"https://dataverse.harvard.edu/api/access/datafile/{identifier}",
48
+ fname=f"{fname}.csv",
49
+ known_hash=None,
50
+ path=tmpdir,
51
+ progressbar=True,
52
+ )
53
+ upload_to_s3(
54
+ s3_uri=f"{S3_RAW}/{fname}.csv",
55
+ local_filepath=local_path,
56
+ )
57
+
58
+
59
+ def _canonicalize_smiles(smiles: str) -> str | None:
60
+ """Canonicalize SMILES string."""
61
+ mol = Chem.MolFromSmiles(smiles)
62
+ return Chem.MolToSmiles(mol, canonical=True) if mol else None
63
+
64
+
65
+ def _fetch_pdb_data(pdb_id: str) -> list[dict]:
66
+ """Fetch molecular data from PDBe API for a given PDB ID."""
67
+ res = requests.get(f"https://www.ebi.ac.uk/pdbe/api/pdb/entry/molecules/{pdb_id}")
68
+
69
+ if res.status_code != 200:
70
+ raise Exception(f"Failed to fetch data for {pdb_id}: {res.status_code}")
71
+
72
+ return res.json().get(pdb_id.lower(), [])
73
+
74
+
75
+ def _fetch_smiles_data(ligand_id: str) -> str | None:
76
+ """Fetch SMILES string for ligand from PDBe."""
77
+ try:
78
+ res = requests.get(f"https://www.ebi.ac.uk/pdbe/api/pdb/compound/summary/{ligand_id.lower()}")
79
+
80
+ if res.status_code != 200:
81
+ raise Exception(f"Failed to fetch data for {ligand_id}: {res.status_code}")
82
+
83
+ ligand_data = res.json().get(ligand_id)[0]
84
+ ligand_data = iter(ligand_data["smiles"])
85
+ while True:
86
+ try:
87
+ smiles = next(ligand_data)["name"]
88
+ return _canonicalize_smiles(smiles)
89
+ except StopIteration:
90
+ break
91
+ except Exception:
92
+ continue
93
+ except Exception as e:
94
+ raise Exception(f"Failed to fetch SMILES for {ligand_id}") from e
95
+
96
+
97
+ def _safe_extract(row_id: str, sequence_extractor: callable) -> dict | None:
98
+ """Safely extract sequences and modalities given a row ID and extractor."""
99
+ try:
100
+ sequences, modalities = sequence_extractor(row_id)
101
+ except Exception as e:
102
+ logger.info(f"Error processing {row_id}: {e}")
103
+ return None
104
+
105
+ combined = list(zip(sequences, modalities))
106
+ combined.sort(key=lambda x: x[1] != "polypeptide(L)")
107
+ sequences, modalities = zip(*combined) if combined else ([], [])
108
+
109
+ sequences = (list(sequences) + [None] * 5)[:5]
110
+ modalities = (list(modalities) + [None] * 5)[:5]
111
+
112
+ return {
113
+ "id": row_id,
114
+ **{f"sequence{i + 1}": sequences[i] for i in range(5)},
115
+ **{f"modality{i + 1}": modalities[i] for i in range(5)},
116
+ }
117
+
118
+
119
+ def process_rows(df: pd.DataFrame, sequence_extractor: callable, debug: bool = False) -> pd.DataFrame:
120
+ """
121
+ Process rows in the dataframe to extract sequence and modality information.
122
+
123
+ Parameters
124
+ ----------
125
+ df : pd.DataFrame
126
+ Input dataframe with 'id' column.
127
+ sequence_extractor : callable
128
+ Function to extract sequences and modalities given a row id.
129
+ debug : bool, optional
130
+ If True, only processes first 10 rows.
131
+
132
+ Returns
133
+ -------
134
+ pd.DataFrame
135
+ Dataframe with sequence and modality columns.
136
+ """
137
+ row_ids = df["id"].tolist()[:10] if debug else df["id"].tolist()
138
+ results = []
139
+ with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
140
+ futures = {executor.submit(_safe_extract, rid, sequence_extractor): rid for rid in row_ids}
141
+ for future in tqdm(as_completed(futures), total=len(futures)):
142
+ result = future.result()
143
+ if result:
144
+ results.append(result)
145
+ return pd.DataFrame(results).replace(MODALITY_MAPPING)
146
+
147
+
148
+
149
+ def extract_protein_nucleotide(row_id: str) -> tuple[list[str], list[str]]:
150
+ """Example ID: 3adi_1.pdb_3adi_1_RNA_D&E.pdb"""
151
+ pdb_id = row_id.split("_")[0]
152
+ pdb_data = _fetch_pdb_data(pdb_id)
153
+ sequences, types = (
154
+ zip(*[(m["sequence"], m["molecule_type"]) for m in pdb_data if "sequence" in m]) if pdb_data else ([], [])
155
+ )
156
+ return list(sequences), list(types)
157
+
158
+
159
+ def extract_protein_small_molecule(row_id: str) -> tuple[list[str], list[str]]:
160
+ """Example ID: 4h4e_1.pdb_4h4e_1_10G_D.pdb"""
161
+ parts = row_id.split("_")
162
+ pdb_id, ligand_id = parts[2], parts[4]
163
+ pdb_data = _fetch_pdb_data(pdb_id)
164
+ sequences, types = (
165
+ zip(*[(m["sequence"], m["molecule_type"]) for m in pdb_data if "sequence" in m]) if pdb_data else ([], [])
166
+ )
167
+ ligand = _fetch_smiles_data(ligand_id)
168
+ if ligand:
169
+ sequences += (ligand,)
170
+ types += ("smiles",)
171
+ return list(sequences), list(types)
172
+
173
+
174
+ def extract_interacting_chains(row_id: str) -> tuple[list[str], list[str]]:
175
+ """Example ID: 2uxq_2_A_B"""
176
+ pdb_id, _, chain_a, chain_b = row_id.split("_")
177
+ chains_of_interest = {chain_a, chain_b}
178
+ molecules = _fetch_pdb_data(pdb_id)
179
+ chain_map = {}
180
+ for m in molecules:
181
+ if "sequence" not in m or "in_chains" not in m:
182
+ continue
183
+ for chain in m["in_chains"]:
184
+ if chain in chains_of_interest:
185
+ chain_map[chain] = (m["sequence"], m["molecule_type"])
186
+ sequences, types = [], []
187
+ for chain in [chain_a, chain_b]:
188
+ if chain in chain_map:
189
+ seq, mol_type = chain_map[chain]
190
+ sequences.append(seq)
191
+ types.append(mol_type)
192
+ else:
193
+ sequences.append(None)
194
+ types.append(None)
195
+ return sequences, types
196
+
197
+
198
+ def process_protein_nucleotide(debug: bool = False) -> None:
199
+ df = pd.read_csv(f"{S3_RAW}/protein-dna.csv", sep="\t")
200
+ df_out = process_rows(df, extract_protein_nucleotide, debug=debug)
201
+ df_out = df_out.drop_duplicates().reset_index(drop=True)
202
+ df_out.to_parquet(f"{S3_PROCESSED}/protein-dna.parquet", index=False)
203
+
204
+ df = pd.read_csv(f"{S3_RAW}/protein-rna.csv", sep="\t")
205
+ df_out = process_rows(df, extract_protein_nucleotide, debug=debug)
206
+ df_out = df_out.drop_duplicates().reset_index(drop=True)
207
+ df_out.to_parquet(f"{S3_PROCESSED}/protein-rna.parquet", index=False)
208
+
209
+
210
+ def process_protein_protein(debug: bool = False) -> None:
211
+ df = pd.read_csv(f"{S3_RAW}/protein-protein.csv", sep="\t")
212
+ df_out = process_rows(df, extract_interacting_chains, debug=debug)
213
+ df_out = df_out.drop_duplicates().reset_index(drop=True)
214
+ df_out.to_parquet(f"{S3_PROCESSED}/protein-protein.parquet", index=False)
215
+
216
+
217
+ def process_protein_small_molecule(debug: bool = False) -> None:
218
+ df = pd.read_csv(f"{S3_RAW}/protein-small_molecule.csv", sep="\t")
219
+ df_out = process_rows(df, extract_protein_small_molecule, debug=debug)
220
+ df_out = df_out.dropna(how="all", axis=1).drop_duplicates().reset_index(drop=True)
221
+ df_out.to_parquet(f"{S3_PROCESSED}/protein-small_molecule.parquet", index=False)
222
+
223
+
224
+ def process_smiles_smiles() -> None:
225
+ df = pd.read_csv(f"{S3_RAW}/small_molecule-small_molecule.csv")
226
+ df = df["id"].str.split("_", expand=True)
227
+ df.columns = ["id", "sequence1", "num_1", "sequence2", "num_2"]
228
+ df = df[df["sequence1"] != df["sequence2"]][["sequence1", "sequence2"]]
229
+ df.insert(1, "modality1", "smiles")
230
+ df.insert(3, "modality2", "smiles")
231
+ df = df.drop_duplicates().reset_index(drop=True)
232
+ df.to_parquet(f"{S3_PROCESSED}/small_molecule-small_molecule.parquet", index=False)
233
+
234
+
235
+ if __name__ == "__main__":
236
+ upload_raw_datasets_to_s3()
237
+ process_protein_nucleotide(debug=False)
238
+ process_protein_protein(debug=False)
239
+ process_protein_small_molecule(debug=False)
240
+ process_smiles_smiles()