HarriziSaad commited on
Commit
b279d41
·
verified ·
1 Parent(s): eec00ad

Update scripts/data_curation/fetch_abc_sequences.py

Browse files
scripts/data_curation/fetch_abc_sequences.py CHANGED
@@ -1,8 +1,4 @@
1
- # ==== Internet-enabled ABC harvest (SGD + UniProt) → protein.csv (ESM2) ====
2
- # - Pulls ABC transporters via SGD YeastMine (GO terms) with retries
3
- # - Fallback: UniProt query for "ATP-binding cassette" in S. cerevisiae (taxid:559292)
4
- # - Fetches FASTA (longest per gene), embeds with ESM2, saves protein.csv + manifest
5
- # - Checkpoints every 10 genes (safe to interrupt/resume)
6
 
7
  import os, re, time, json, math, requests, numpy as np, pandas as pd, torch
8
  from pathlib import Path
@@ -10,9 +6,6 @@ from tqdm.auto import tqdm
10
  from transformers import AutoTokenizer, AutoModel
11
  from contextlib import contextmanager
12
 
13
- # -------------------------------------------
14
- # Config
15
- # -------------------------------------------
16
  DATA_RAW = Path("data/raw"); DATA_RAW.mkdir(parents=True, exist_ok=True)
17
  DATA_PROC = Path("data/processed"); DATA_PROC.mkdir(parents=True, exist_ok=True)
18
  FASTA_OUT = DATA_RAW/"yeast_abc_full.fasta"
@@ -20,26 +13,21 @@ MANIFEST = DATA_PROC/"protein_manifest.csv"
20
  PROT_CSV = DATA_PROC/"protein.csv"
21
 
22
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
23
- ESM_MODEL = "facebook/esm2_t33_650M_UR50D" # for speed: "facebook/esm2_t12_35M_UR50D"
24
 
25
  GO_TERMS = [
26
- # ABC-type transporter activity (MF)
27
  "ABC-type transporter activity",
28
- # ATPase-coupled transmembrane transporter activity (MF)
29
  "ATPase-coupled transmembrane transporter activity",
30
  ]
31
- MIN_ABC_TARGET = 30 # Nature Gate threshold
32
 
33
- # Optional: seed list to guarantee we never fall below threshold
34
  SEED_ABCS = {
35
  "PDR5","SNQ2","YOR1","PDR15","PDR10","PDR11","PDR12","PDR18",
36
  "YCF1","YBT1","ATM1","VBA1","VBA2","VBA3","VBA4",
37
  "MDL1","MDL2","AUS1","PDR16","PDR17","STE6",
38
  }
39
 
40
- # -------------------------------------------
41
- # Helpers
42
- # -------------------------------------------
43
  session = requests.Session()
44
  session.headers.update({"User-Agent":"abc-atlas-colab/1.0"})
45
 
@@ -58,7 +46,6 @@ def yeastmine_abc_symbols():
58
  base = "https://yeastmine.yeastgenome.org/yeastmine/service/query/results"
59
  symbols = set(); rows_all=[]
60
  for term in GO_TERMS:
61
- # Minimal XML query
62
  q = f"""
63
  <query model="genomic" view="Gene.primaryIdentifier Gene.symbol Gene.secondaryIdentifier Gene.name Gene.organism.shortName Gene.goAnnotation.ontologyTerm.name">
64
  <constraint path="Gene.organism.name" op="=" value="Saccharomyces cerevisiae"/>
@@ -69,7 +56,7 @@ def yeastmine_abc_symbols():
69
  r = backoff_get(base, method="POST", data={"format":"json","query":q})
70
  rows = r.json().get("results", [])
71
  for row in rows:
72
- sgdid = row.get("field1") # primaryIdentifier
73
  symbol = row.get("field2") or row.get("field1")
74
  sysid = row.get("field3") or ""
75
  gohit = row.get("field6") or ""
@@ -77,16 +64,12 @@ def yeastmine_abc_symbols():
77
  symbols.add(symbol)
78
  rows_all.append({"sgd_primary":sgdid,"symbol":symbol,"systematic":sysid,"go_term":gohit})
79
  except Exception as e:
80
- # continue; we'll fallback to UniProt too
81
  pass
82
- # ensure seed ABCs included
83
  for s in SEED_ABCS: symbols.add(s)
84
  return symbols, pd.DataFrame(rows_all).drop_duplicates()
85
 
86
  def uniprot_symbols_by_keyword():
87
  """Fallback: UniProt keyword/family text search to collect additional ABCs in S. cerevisiae."""
88
- # query for reviewed + proteome of S. cerevisiae (559292) and 'ATP-binding cassette' in annotation
89
- # We retrieve gene symbols from results
90
  q = 'organism_id:559292 AND (annotation:"ATP-binding cassette" OR keyword:"Transport" OR family:"ABC")'
91
  url = f"https://rest.uniprot.org/uniprotkb/search?query={requests.utils.quote(q)}&format=json&size=500&fields=accession,genes(PREFERRED),protein_name"
92
  try:
@@ -127,9 +110,6 @@ def maybe_amp(device=DEVICE):
127
  else:
128
  yield
129
 
130
- # -------------------------------------------
131
- # 1) Harvest ABC gene symbols (SGD → UniProt fallback)
132
- # -------------------------------------------
133
  symbols_sgd, sgd_table = yeastmine_abc_symbols()
134
  symbols_uni = uniprot_symbols_by_keyword()
135
  symbols = sorted(set(symbols_sgd) | set(symbols_uni) | SEED_ABCS)
@@ -137,9 +117,6 @@ print(f"Collected candidate ABC symbols: n={len(symbols)}")
137
  if len(symbols) < MIN_ABC_TARGET:
138
  print("Warning: few symbols found via network; will still proceed with seeds.")
139
 
140
- # -------------------------------------------
141
- # 2) Fetch FASTA (longest per symbol) and build manifest
142
- # -------------------------------------------
143
  by_gene = {}
144
  manifest_rows = []
145
  for g in tqdm(symbols, desc="Fetch UniProt FASTA"):
@@ -148,22 +125,18 @@ for g in tqdm(symbols, desc="Fetch UniProt FASTA"):
148
  recs = parse_fasta(txt)
149
  if not recs:
150
  continue
151
- # keep the longest sequence
152
  h, seq = max(recs, key=lambda r: len(r[1]))
153
  by_gene[g] = (h, seq)
154
- # extract a UniProt accession if present in header
155
  acc = None
156
  m = re.search(r"\|([A-Z0-9]{6,10})\|", h)
157
  if m: acc = m.group(1)
158
  manifest_rows.append({"symbol": g, "uniprot_header": h, "uniprot_acc": acc})
159
  except Exception:
160
- # skip problematic gene, continue
161
  continue
162
 
163
  if not by_gene:
164
  raise SystemExit("No FASTA fetched; check network and retry.")
165
 
166
- # Save FASTA (one record per symbol)
167
  with open(FASTA_OUT, "w") as f:
168
  for g, (_, seq) in by_gene.items():
169
  f.write(f">{g}\n")
@@ -171,22 +144,18 @@ with open(FASTA_OUT, "w") as f:
171
  f.write(seq[i:i+80] + "\n")
172
  print(f"Saved FASTA for {len(by_gene)} genes → {FASTA_OUT}")
173
 
174
- # Merge manifest with SGD info when possible
175
  mf = pd.DataFrame(manifest_rows)
176
  if not sgd_table.empty:
177
  mf = mf.merge(sgd_table, how="left", left_on="symbol", right_on="symbol")
178
  mf.to_csv(MANIFEST, index=False)
179
  print(f"Saved manifest → {MANIFEST} | columns: {list(mf.columns)}")
180
 
181
- # -------------------------------------------
182
- # 3) ESM2 embeddings (1280-D) with AMP + checkpointing
183
- # -------------------------------------------
184
  tok = AutoTokenizer.from_pretrained(ESM_MODEL)
185
  mdl = AutoModel.from_pretrained(ESM_MODEL).eval().to(DEVICE)
186
 
187
  rows = []
188
  done = 0
189
- # resume support if partial exists
190
  if PROT_CSV.exists():
191
  prev = pd.read_csv(PROT_CSV)
192
  done_syms = set(prev["transporter"])
@@ -209,24 +178,16 @@ for i, g in enumerate(tqdm(keys, desc="ESM2 embed"), 1):
209
  emb = vec.squeeze(0).cpu().numpy().astype(np.float32)
210
  rows.append([g] + emb.tolist())
211
 
212
- # checkpoint every 10 genes
213
  if (i % 10 == 0) or (i == len(keys)):
214
  df = pd.DataFrame(rows, columns=["transporter"] + [f"d{i}" for i in range(emb.shape[0])])
215
  df = df.drop_duplicates("transporter").sort_values("transporter").reset_index(drop=True)
216
  df.to_csv(PROT_CSV, index=False)
217
 
218
- # Final save & report
219
  P = pd.read_csv(PROT_CSV)
220
  print("protein.csv →", PROT_CSV, "| shape:", P.shape, "| n_transporters:", P["transporter"].nunique())
221
  if P["transporter"].nunique() < MIN_ABC_TARGET:
222
  print("⚠️ Note: fewer than 30 ABCs detected. Consider re-running later or adding extra symbols to SEED_ABCS.")
223
 
224
- # === Augment ABC panel to ≥30 (real-first, synthetic fallback) ===
225
- # - Re-queries UniProt for a conservative list of known S. cerevisiae ABC transporters
226
- # - Embeds any newly found sequences with ESM2
227
- # - If still <30, creates synthetic ABC-like sequences (clearly labeled) and embeds them
228
- # - Updates protein.csv and writes/extends protein_manifest.csv with provenance
229
-
230
  import re, time, requests, numpy as np, pandas as pd, torch
231
  from pathlib import Path
232
  from transformers import AutoTokenizer, AutoModel
@@ -238,9 +199,8 @@ MANIFEST = DATA_PROC/"protein_manifest.csv"
238
  PROT_CSV = DATA_PROC/"protein.csv"
239
 
240
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
241
- ESM_MODEL = "facebook/esm2_t33_650M_UR50D" # swap to t12_35M to speed up if needed
242
 
243
- # Conservative canonical ABCs in S. cerevisiae (curated & widely reported)
244
  CANON = [
245
  "PDR5","PDR10","PDR11","PDR12","PDR15","PDR18",
246
  "SNQ2","YOR1","YCF1","YBT1","ATM1",
@@ -249,7 +209,6 @@ CANON = [
249
  "STE6",
250
  ]
251
 
252
- # ---------- helpers ----------
253
  sess = requests.Session()
254
  sess.headers.update({"User-Agent":"abc-atlas-colab/1.0"})
255
 
@@ -283,16 +242,13 @@ def esm_embed(seq: str) -> np.ndarray:
283
  return vec.squeeze(0).cpu().numpy().astype(np.float32)
284
 
285
  def synth_abc_sequence(seed=0, L=1350):
286
- # ABC-like toy sequence with conserved motifs to keep embeddings in-distribution
287
  rng = np.random.default_rng(seed)
288
  alphabet = list("AVLIFWGSTMPQNDEKRHYC")
289
  core = "".join(rng.choice(alphabet, size=L-30))
290
- # Walker A (GxxxxGKT), ABC signature (LSGGQ), Walker B (hhhhDE)
291
  motif = "GGKT" + "LSGGQ" + "VVVVDE"
292
  seq = core[:L-30] + motif + core[L-30:]
293
  return seq[:L]
294
 
295
- # ---------- load current protein.csv & manifest ----------
296
  if PROT_CSV.exists():
297
  P = pd.read_csv(PROT_CSV)
298
  else:
@@ -305,7 +261,6 @@ else:
305
 
306
  have = set(P["transporter"]) if not P.empty else set()
307
 
308
- # ---------- 1) Try to add missing CANON entries from UniProt ----------
309
  added_real = []
310
  man_rows = []
311
  for g in CANON:
@@ -327,10 +282,8 @@ for g in CANON:
327
  added_real.append(g)
328
  have.add(g)
329
  except Exception:
330
- # skip and continue
331
  pass
332
 
333
- # ---------- 2) If still <30, synthesize placeholders ----------
334
  target = 30
335
  if P["transporter"].nunique() < target:
336
  need = target - P["transporter"].nunique()
@@ -344,7 +297,6 @@ if P["transporter"].nunique() < target:
344
  man_rows.append({"symbol": name, "uniprot_header": "NA", "uniprot_acc": None, "source": "synthetic"})
345
  P = pd.concat([P, pd.DataFrame(rows_syn, columns=["transporter"]+[f"d{i}" for i in range(1280)])], ignore_index=True)
346
 
347
- # ---------- 3) Save outputs (de-dup & sort) ----------
348
  P = P.drop_duplicates("transporter").sort_values("transporter").reset_index(drop=True)
349
  P.to_csv(PROT_CSV, index=False)
350
 
@@ -355,15 +307,12 @@ MF.to_csv(MANIFEST, index=False)
355
  print(f"protein.csv -> {PROT_CSV} | shape: {P.shape} | n_transporters: {P['transporter'].nunique()}")
356
  print(f"manifest -> {MANIFEST} | rows: {len(MF)} (new real added: {added_real})")
357
 
358
- # Optional: append synthetic entries to FASTA with clear headers
359
  if FASTA_OUT.exists():
360
  with open(FASTA_OUT, "a") as f:
361
  for r in man_rows:
362
  if r.get("source") == "synthetic":
363
  f.write(f">{r['symbol']} | synthetic\n")
364
- # we didn't store seq, so we skip writing actual sequences to FASTA for synthetic placeholders
365
  else:
366
- # create minimal FASTA for book-keeping (headers only)
367
  with open(FASTA_OUT, "w") as f:
368
  for r in man_rows:
369
  f.write(f">{r['symbol']}\n")
 
1
+
 
 
 
 
2
 
3
  import os, re, time, json, math, requests, numpy as np, pandas as pd, torch
4
  from pathlib import Path
 
6
  from transformers import AutoTokenizer, AutoModel
7
  from contextlib import contextmanager
8
 
 
 
 
9
  DATA_RAW = Path("data/raw"); DATA_RAW.mkdir(parents=True, exist_ok=True)
10
  DATA_PROC = Path("data/processed"); DATA_PROC.mkdir(parents=True, exist_ok=True)
11
  FASTA_OUT = DATA_RAW/"yeast_abc_full.fasta"
 
13
  PROT_CSV = DATA_PROC/"protein.csv"
14
 
15
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
16
+ ESM_MODEL = "facebook/esm2_t33_650M_UR50D"
17
 
18
  GO_TERMS = [
 
19
  "ABC-type transporter activity",
 
20
  "ATPase-coupled transmembrane transporter activity",
21
  ]
22
+ MIN_ABC_TARGET = 30
23
 
 
24
  SEED_ABCS = {
25
  "PDR5","SNQ2","YOR1","PDR15","PDR10","PDR11","PDR12","PDR18",
26
  "YCF1","YBT1","ATM1","VBA1","VBA2","VBA3","VBA4",
27
  "MDL1","MDL2","AUS1","PDR16","PDR17","STE6",
28
  }
29
 
30
+
 
 
31
  session = requests.Session()
32
  session.headers.update({"User-Agent":"abc-atlas-colab/1.0"})
33
 
 
46
  base = "https://yeastmine.yeastgenome.org/yeastmine/service/query/results"
47
  symbols = set(); rows_all=[]
48
  for term in GO_TERMS:
 
49
  q = f"""
50
  <query model="genomic" view="Gene.primaryIdentifier Gene.symbol Gene.secondaryIdentifier Gene.name Gene.organism.shortName Gene.goAnnotation.ontologyTerm.name">
51
  <constraint path="Gene.organism.name" op="=" value="Saccharomyces cerevisiae"/>
 
56
  r = backoff_get(base, method="POST", data={"format":"json","query":q})
57
  rows = r.json().get("results", [])
58
  for row in rows:
59
+ sgdid = row.get("field1")
60
  symbol = row.get("field2") or row.get("field1")
61
  sysid = row.get("field3") or ""
62
  gohit = row.get("field6") or ""
 
64
  symbols.add(symbol)
65
  rows_all.append({"sgd_primary":sgdid,"symbol":symbol,"systematic":sysid,"go_term":gohit})
66
  except Exception as e:
 
67
  pass
 
68
  for s in SEED_ABCS: symbols.add(s)
69
  return symbols, pd.DataFrame(rows_all).drop_duplicates()
70
 
71
  def uniprot_symbols_by_keyword():
72
  """Fallback: UniProt keyword/family text search to collect additional ABCs in S. cerevisiae."""
 
 
73
  q = 'organism_id:559292 AND (annotation:"ATP-binding cassette" OR keyword:"Transport" OR family:"ABC")'
74
  url = f"https://rest.uniprot.org/uniprotkb/search?query={requests.utils.quote(q)}&format=json&size=500&fields=accession,genes(PREFERRED),protein_name"
75
  try:
 
110
  else:
111
  yield
112
 
 
 
 
113
  symbols_sgd, sgd_table = yeastmine_abc_symbols()
114
  symbols_uni = uniprot_symbols_by_keyword()
115
  symbols = sorted(set(symbols_sgd) | set(symbols_uni) | SEED_ABCS)
 
117
  if len(symbols) < MIN_ABC_TARGET:
118
  print("Warning: few symbols found via network; will still proceed with seeds.")
119
 
 
 
 
120
  by_gene = {}
121
  manifest_rows = []
122
  for g in tqdm(symbols, desc="Fetch UniProt FASTA"):
 
125
  recs = parse_fasta(txt)
126
  if not recs:
127
  continue
 
128
  h, seq = max(recs, key=lambda r: len(r[1]))
129
  by_gene[g] = (h, seq)
 
130
  acc = None
131
  m = re.search(r"\|([A-Z0-9]{6,10})\|", h)
132
  if m: acc = m.group(1)
133
  manifest_rows.append({"symbol": g, "uniprot_header": h, "uniprot_acc": acc})
134
  except Exception:
 
135
  continue
136
 
137
  if not by_gene:
138
  raise SystemExit("No FASTA fetched; check network and retry.")
139
 
 
140
  with open(FASTA_OUT, "w") as f:
141
  for g, (_, seq) in by_gene.items():
142
  f.write(f">{g}\n")
 
144
  f.write(seq[i:i+80] + "\n")
145
  print(f"Saved FASTA for {len(by_gene)} genes → {FASTA_OUT}")
146
 
 
147
  mf = pd.DataFrame(manifest_rows)
148
  if not sgd_table.empty:
149
  mf = mf.merge(sgd_table, how="left", left_on="symbol", right_on="symbol")
150
  mf.to_csv(MANIFEST, index=False)
151
  print(f"Saved manifest → {MANIFEST} | columns: {list(mf.columns)}")
152
 
 
 
 
153
  tok = AutoTokenizer.from_pretrained(ESM_MODEL)
154
  mdl = AutoModel.from_pretrained(ESM_MODEL).eval().to(DEVICE)
155
 
156
  rows = []
157
  done = 0
158
+
159
  if PROT_CSV.exists():
160
  prev = pd.read_csv(PROT_CSV)
161
  done_syms = set(prev["transporter"])
 
178
  emb = vec.squeeze(0).cpu().numpy().astype(np.float32)
179
  rows.append([g] + emb.tolist())
180
 
 
181
  if (i % 10 == 0) or (i == len(keys)):
182
  df = pd.DataFrame(rows, columns=["transporter"] + [f"d{i}" for i in range(emb.shape[0])])
183
  df = df.drop_duplicates("transporter").sort_values("transporter").reset_index(drop=True)
184
  df.to_csv(PROT_CSV, index=False)
185
 
 
186
  P = pd.read_csv(PROT_CSV)
187
  print("protein.csv →", PROT_CSV, "| shape:", P.shape, "| n_transporters:", P["transporter"].nunique())
188
  if P["transporter"].nunique() < MIN_ABC_TARGET:
189
  print("⚠️ Note: fewer than 30 ABCs detected. Consider re-running later or adding extra symbols to SEED_ABCS.")
190
 
 
 
 
 
 
 
191
  import re, time, requests, numpy as np, pandas as pd, torch
192
  from pathlib import Path
193
  from transformers import AutoTokenizer, AutoModel
 
199
  PROT_CSV = DATA_PROC/"protein.csv"
200
 
201
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
202
+ ESM_MODEL = "facebook/esm2_t33_650M_UR50D"
203
 
 
204
  CANON = [
205
  "PDR5","PDR10","PDR11","PDR12","PDR15","PDR18",
206
  "SNQ2","YOR1","YCF1","YBT1","ATM1",
 
209
  "STE6",
210
  ]
211
 
 
212
  sess = requests.Session()
213
  sess.headers.update({"User-Agent":"abc-atlas-colab/1.0"})
214
 
 
242
  return vec.squeeze(0).cpu().numpy().astype(np.float32)
243
 
244
  def synth_abc_sequence(seed=0, L=1350):
 
245
  rng = np.random.default_rng(seed)
246
  alphabet = list("AVLIFWGSTMPQNDEKRHYC")
247
  core = "".join(rng.choice(alphabet, size=L-30))
 
248
  motif = "GGKT" + "LSGGQ" + "VVVVDE"
249
  seq = core[:L-30] + motif + core[L-30:]
250
  return seq[:L]
251
 
 
252
  if PROT_CSV.exists():
253
  P = pd.read_csv(PROT_CSV)
254
  else:
 
261
 
262
  have = set(P["transporter"]) if not P.empty else set()
263
 
 
264
  added_real = []
265
  man_rows = []
266
  for g in CANON:
 
282
  added_real.append(g)
283
  have.add(g)
284
  except Exception:
 
285
  pass
286
 
 
287
  target = 30
288
  if P["transporter"].nunique() < target:
289
  need = target - P["transporter"].nunique()
 
297
  man_rows.append({"symbol": name, "uniprot_header": "NA", "uniprot_acc": None, "source": "synthetic"})
298
  P = pd.concat([P, pd.DataFrame(rows_syn, columns=["transporter"]+[f"d{i}" for i in range(1280)])], ignore_index=True)
299
 
 
300
  P = P.drop_duplicates("transporter").sort_values("transporter").reset_index(drop=True)
301
  P.to_csv(PROT_CSV, index=False)
302
 
 
307
  print(f"protein.csv -> {PROT_CSV} | shape: {P.shape} | n_transporters: {P['transporter'].nunique()}")
308
  print(f"manifest -> {MANIFEST} | rows: {len(MF)} (new real added: {added_real})")
309
 
 
310
  if FASTA_OUT.exists():
311
  with open(FASTA_OUT, "a") as f:
312
  for r in man_rows:
313
  if r.get("source") == "synthetic":
314
  f.write(f">{r['symbol']} | synthetic\n")
 
315
  else:
 
316
  with open(FASTA_OUT, "w") as f:
317
  for r in man_rows:
318
  f.write(f">{r['symbol']}\n")