ProximileAdmin commited on
Commit
fe96401
·
verified ·
1 Parent(s): bcfccda

Update create_diffusion_dataset.py

Browse files
Files changed (1) hide show
  1. create_diffusion_dataset.py +578 -37
create_diffusion_dataset.py CHANGED
@@ -1,24 +1,330 @@
1
  import pandas as pd
2
  import numpy as np
3
  import networkx as nx
4
- from typing import List, Dict, Tuple, Set
5
  import json
6
  import random
7
  from collections import defaultdict, Counter
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
- LIMIT_CANDIDATE_PROTEINS = 5000
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
  class ProteinNetworkConversationDataset:
12
- def __init__(self, filename: str):
13
  """
14
  Create conversational dataset for protein network prediction using diffusion models
15
  """
16
  self.filename = filename
 
17
  self.df = None
18
  self.graph = nx.Graph()
19
  self.protein_to_id = {}
20
  self.id_to_protein = {}
21
  self.interactions_by_protein = defaultdict(list)
 
 
22
 
23
  def load_and_parse_biogrid(self):
24
  """Load and parse BioGRID data"""
@@ -102,14 +408,95 @@ class ProteinNetworkConversationDataset:
102
 
103
  print(f"Found {len(candidate_proteins)} proteins with degree {min_connections}-{max_connections}")
104
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  neighborhoods = []
106
- for protein in candidate_proteins[:LIMIT_CANDIDATE_PROTEINS]: # Limit for processing
107
- neighborhood = self.extract_neighborhood(protein, interactions, max_size=10)
108
- if len(neighborhood['proteins']) >= 3: # Minimum viable network
109
- neighborhoods.append(neighborhood)
 
 
 
 
110
 
111
  return neighborhoods
112
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  def extract_neighborhood(self, center_protein, interactions, max_size=10):
114
  """
115
  Extract neighborhood around a protein
@@ -145,45 +532,50 @@ class ProteinNetworkConversationDataset:
145
 
146
  def create_conversation_examples(self, neighborhoods):
147
  """
148
- Create different types of conversation examples for diffusion training
149
  """
150
- conversations = []
151
 
152
- for neighborhood in neighborhoods:
153
- # Task 1: Complete protein network given protein list
154
- conversations.extend(self.create_protein_list_to_network_examples(neighborhood))
155
-
156
- # Task 2: Predict interactions for new protein
157
- conversations.extend(self.create_new_protein_prediction_examples(neighborhood))
158
-
159
- # Task 3: Complete partial network
160
- conversations.extend(self.create_partial_network_completion_examples(neighborhood))
 
161
 
162
- # Task 4: Network property prediction
163
- conversations.extend(self.create_network_property_examples(neighborhood))
 
164
 
165
  return conversations
166
 
167
  def create_protein_list_to_network_examples(self, neighborhood):
168
  """
169
- Context: List of proteins
170
  Generation: Complete interaction network
171
  """
172
  examples = []
173
  proteins = neighborhood['proteins']
174
  interactions = neighborhood['interactions']
175
 
176
- # Create network representation
177
- network_text = self.format_network_as_text(proteins, interactions)
178
 
179
  system_msg = {
180
  "role": "system",
181
- "content": "You are a protein interaction prediction system. Given a list of proteins, predict all likely interactions between them based on biological knowledge."
182
  }
183
 
 
 
 
184
  user_msg = {
185
  "role": "user",
186
- "content": f"Predict the protein interaction network for these proteins: {', '.join(proteins)}"
187
  }
188
 
189
  assistant_msg = {
@@ -198,7 +590,7 @@ class ProteinNetworkConversationDataset:
198
 
199
  def create_new_protein_prediction_examples(self, neighborhood):
200
  """
201
- Context: Known network + new protein
202
  Generation: Interactions for the new protein
203
  """
204
  examples = []
@@ -227,17 +619,21 @@ class ProteinNetworkConversationDataset:
227
  if not target_interactions:
228
  return examples
229
 
230
- known_network_text = self.format_network_as_text(remaining_proteins, known_interactions)
231
  target_network_text = self.format_interactions_as_text(target_interactions)
232
 
 
 
 
 
233
  system_msg = {
234
  "role": "system",
235
- "content": "You are a protein interaction prediction system. Given a known protein network and a new protein, predict which proteins in the network the new protein will interact with."
236
  }
237
 
238
  user_msg = {
239
  "role": "user",
240
- "content": f"Known protein network:\n{known_network_text}\n\nNew protein to integrate: {target_protein}\n\nPredict the interactions for {target_protein}:"
241
  }
242
 
243
  assistant_msg = {
@@ -372,6 +768,88 @@ class ProteinNetworkConversationDataset:
372
  result += f"NETWORK SUMMARY: {len(proteins)} proteins, {total_interactions} unique interactions"
373
  return result.strip()
374
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
375
  def format_interactions_as_text(self, interactions):
376
  """
377
  Format just interactions as text
@@ -402,41 +880,83 @@ class ProteinNetworkConversationDataset:
402
 
403
  def save_conversation_dataset(self, output_file="processed_dataset.json"):
404
  """
405
- Create and save the full conversation dataset
406
  """
 
 
407
  # Load and process data
 
 
408
  interactions, proteins = self.load_and_parse_biogrid()
 
 
 
 
 
 
409
  neighborhoods = self.build_network_neighborhoods(interactions, proteins)
 
 
 
 
 
 
 
 
 
 
410
 
411
- print(f"Built {len(neighborhoods)} protein neighborhoods")
 
 
412
 
413
  # Create conversation examples
 
 
414
  conversations = self.create_conversation_examples(neighborhoods)
415
-
416
- print(f"Created {len(conversations)} conversation examples")
417
 
418
  # Shuffle the dataset
 
419
  random.shuffle(conversations)
420
 
421
  # Save dataset
422
  with open(output_file, 'w') as f:
423
  json.dump(conversations, f, indent=2)
424
 
 
 
 
 
 
 
425
  print(f"Saved dataset to {output_file}")
 
 
426
 
427
  # Show examples
428
  print("\n=== Example Conversations ===")
429
- for i, conv in enumerate(conversations[:3]):
430
  print(f"\n--- Example {i+1} ---")
431
  for msg in conv["updated"]:
432
- print(f"{msg['role'].upper()}: {msg['content'][:200]}...")
433
 
434
  return conversations
435
 
436
  # Usage
437
  if __name__ == "__main__":
 
 
 
 
 
 
 
 
438
  creator = ProteinNetworkConversationDataset(
439
- "./unzipped/BIOGRID-ALL-4.4.246.tab3/BIOGRID-ALL-4.4.246.tab3.txt"
 
440
  )
441
 
442
  conversations = creator.save_conversation_dataset("processed_dataset.json")
@@ -459,4 +979,25 @@ if __name__ == "__main__":
459
 
460
  print("\nTask distribution:")
461
  for task, count in task_types.items():
462
- print(f" {task}: {count}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import pandas as pd
2
  import numpy as np
3
  import networkx as nx
4
+ from typing import List, Dict, Tuple, Set, Optional
5
  import json
6
  import random
7
  from collections import defaultdict, Counter
8
+ import multiprocessing as mp
9
+ from functools import partial
10
+ import time
11
+ import requests
12
+ from urllib.parse import quote
13
+ import xml.etree.ElementTree as ET
14
+ from time import sleep
15
+ import re
16
+ import os
17
+ import fcntl
18
+ import tempfile
19
+ import shutil
20
 
21
+ # Global configuration
22
+ MAX_PROTEINS_TO_PROCESS = 500
23
+
24
+ class ProteinDataEnricher:
25
+ """
26
+ Handles fetching and caching protein sequence and structural data with thread-safe persistent cache
27
+ """
28
+ def __init__(self, cache_dir: str = "protein_cache"):
29
+ self.cache_dir = cache_dir
30
+ self.uniprot_cache = {}
31
+ self.alphafold_cache = {}
32
+ self.session = requests.Session()
33
+ self.session.headers.update({'User-Agent': 'ProteinNetworkDataset/1.0'})
34
+
35
+ # Create cache directory if it doesn't exist
36
+ os.makedirs(cache_dir, exist_ok=True)
37
+
38
+ # Load existing caches
39
+ self._load_caches()
40
+
41
+ def _get_cache_files(self):
42
+ """Get cache file paths"""
43
+ uniprot_cache_file = os.path.join(self.cache_dir, "uniprot_cache.json")
44
+ alphafold_cache_file = os.path.join(self.cache_dir, "alphafold_cache.json")
45
+ return uniprot_cache_file, alphafold_cache_file
46
+
47
+ def _load_caches(self):
48
+ """Load existing caches from disk"""
49
+ uniprot_cache_file, alphafold_cache_file = self._get_cache_files()
50
+
51
+ # Load UniProt cache
52
+ if os.path.exists(uniprot_cache_file):
53
+ try:
54
+ with open(uniprot_cache_file, 'r') as f:
55
+ self.uniprot_cache = json.load(f)
56
+ print(f"Loaded UniProt cache with {len(self.uniprot_cache)} entries")
57
+ except Exception as e:
58
+ print(f"Error loading UniProt cache: {e}")
59
+ self.uniprot_cache = {}
60
+
61
+ # Load AlphaFold cache
62
+ if os.path.exists(alphafold_cache_file):
63
+ try:
64
+ with open(alphafold_cache_file, 'r') as f:
65
+ self.alphafold_cache = json.load(f)
66
+ print(f"Loaded AlphaFold cache with {len(self.alphafold_cache)} entries")
67
+ except Exception as e:
68
+ print(f"Error loading AlphaFold cache: {e}")
69
+ self.alphafold_cache = {}
70
+
71
+ def _safe_merge_and_save_cache(self, cache_type: str, new_data: Dict):
72
+ """
73
+ Safely merge new cache data with existing cache using file locking
74
+ """
75
+ if cache_type == "uniprot":
76
+ cache_file = os.path.join(self.cache_dir, "uniprot_cache.json")
77
+ elif cache_type == "alphafold":
78
+ cache_file = os.path.join(self.cache_dir, "alphafold_cache.json")
79
+ else:
80
+ raise ValueError(f"Unknown cache type: {cache_type}")
81
+
82
+ # Create lock file
83
+ lock_file = cache_file + ".lock"
84
+
85
+ try:
86
+ # Acquire lock
87
+ with open(lock_file, 'w') as lock:
88
+ fcntl.flock(lock.fileno(), fcntl.LOCK_EX)
89
+
90
+ # Load current cache from file
91
+ current_cache = {}
92
+ if os.path.exists(cache_file):
93
+ try:
94
+ with open(cache_file, 'r') as f:
95
+ current_cache = json.load(f)
96
+ except Exception as e:
97
+ print(f"Error loading {cache_type} cache for merge: {e}")
98
+ current_cache = {}
99
+
100
+ # Merge new data with current cache
101
+ current_cache.update(new_data)
102
+
103
+ # Atomic write: write to temp file then rename
104
+ temp_file = cache_file + ".tmp"
105
+ with open(temp_file, 'w') as f:
106
+ json.dump(current_cache, f, indent=2)
107
+
108
+ # Atomic rename
109
+ shutil.move(temp_file, cache_file)
110
+
111
+ print(f"Merged and saved {cache_type} cache: {len(current_cache)} total entries")
112
+
113
+ except Exception as e:
114
+ print(f"Error saving {cache_type} cache: {e}")
115
+ finally:
116
+ # Clean up lock file
117
+ try:
118
+ os.remove(lock_file)
119
+ except:
120
+ pass
121
+
122
+ def get_uniprot_info(self, protein_name: str) -> Optional[Dict]:
123
+ """
124
+ Fetch UniProt information for a protein
125
+ """
126
+ if protein_name in self.uniprot_cache:
127
+ return self.uniprot_cache[protein_name]
128
+
129
+ try:
130
+ # Search UniProt for the protein
131
+ search_url = f"https://rest.uniprot.org/uniprotkb/search"
132
+ params = {
133
+ 'query': f'gene_exact:{protein_name} OR protein_name:{protein_name}',
134
+ 'format': 'json',
135
+ 'size': 1
136
+ }
137
+
138
+ response = self.session.get(search_url, params=params, timeout=10)
139
+ if response.status_code == 200:
140
+ data = response.json()
141
+ if data.get('results'):
142
+ entry = data['results'][0]
143
+ uniprot_info = {
144
+ 'uniprot_id': entry.get('primaryAccession'),
145
+ 'protein_name': entry.get('proteinDescription', {}).get('recommendedName', {}).get('fullName', {}).get('value'),
146
+ 'gene_names': [gn.get('geneName', {}).get('value') for gn in entry.get('genes', []) if gn.get('geneName')],
147
+ 'organism': entry.get('organism', {}).get('scientificName'),
148
+ 'sequence': entry.get('sequence', {}).get('value'),
149
+ 'sequence_length': entry.get('sequence', {}).get('length'),
150
+ 'function': entry.get('comments', [{}])[0].get('texts', [{}])[0].get('value') if entry.get('comments') else None
151
+ }
152
+ self.uniprot_cache[protein_name] = uniprot_info
153
+ return uniprot_info
154
+
155
+ except Exception as e:
156
+ print(f"Error fetching UniProt data for {protein_name}: {e}")
157
+
158
+ self.uniprot_cache[protein_name] = None
159
+ return None
160
+
161
+ def get_alphafold_info(self, uniprot_id: str) -> Optional[Dict]:
162
+ """
163
+ Fetch AlphaFold structural information for a UniProt ID
164
+ """
165
+ if not uniprot_id:
166
+ return None
167
+
168
+ cache_key = uniprot_id
169
+ if cache_key in self.alphafold_cache:
170
+ return self.alphafold_cache[cache_key]
171
+
172
+ try:
173
+ # Check if AlphaFold structure exists
174
+ af_url = f"https://alphafold.ebi.ac.uk/api/prediction/{uniprot_id}"
175
+ response = self.session.get(af_url, timeout=10)
176
+
177
+ if response.status_code == 200:
178
+ af_data = response.json()
179
+ if af_data:
180
+ entry = af_data[0] if isinstance(af_data, list) else af_data
181
+
182
+ alphafold_info = {
183
+ 'alphafold_id': entry.get('entryId'),
184
+ 'model_confidence': entry.get('modelConfidence'),
185
+ 'model_url': entry.get('pdbUrl'),
186
+ 'confidence_score': entry.get('modelConfidence'),
187
+ 'structure_coverage': f"{entry.get('uniprotStart', 1)}-{entry.get('uniprotEnd', 'end')}",
188
+ 'has_structure': True
189
+ }
190
+ self.alphafold_cache[cache_key] = alphafold_info
191
+ return alphafold_info
192
+
193
+ except Exception as e:
194
+ print(f"Error fetching AlphaFold data for {uniprot_id}: {e}")
195
+
196
+ self.alphafold_cache[cache_key] = {'has_structure': False}
197
+ return {'has_structure': False}
198
+
199
+ def get_protein_enriched_data(self, protein_name: str) -> Dict:
200
+ """
201
+ Get combined UniProt and AlphaFold data for a protein
202
+ """
203
+ enriched_data = {'protein_name': protein_name}
204
+
205
+ # Get UniProt info
206
+ uniprot_info = self.get_uniprot_info(protein_name)
207
+ if uniprot_info:
208
+ enriched_data.update(uniprot_info)
209
+
210
+ # Get AlphaFold info if we have a UniProt ID
211
+ if uniprot_info.get('uniprot_id'):
212
+ alphafold_info = self.get_alphafold_info(uniprot_info['uniprot_id'])
213
+ if alphafold_info:
214
+ enriched_data.update(alphafold_info)
215
+
216
+ # Add rate limiting
217
+ sleep(0.1) # Small delay to be respectful to APIs
218
+ return enriched_data
219
+
220
+ def save_cache(self):
221
+ """Save caches using safe merge strategy"""
222
+ # Only save entries that are not None/empty
223
+ uniprot_to_save = {k: v for k, v in self.uniprot_cache.items() if v is not None}
224
+ alphafold_to_save = {k: v for k, v in self.alphafold_cache.items() if v is not None}
225
+
226
+ if uniprot_to_save:
227
+ self._safe_merge_and_save_cache("uniprot", uniprot_to_save)
228
+
229
+ if alphafold_to_save:
230
+ self._safe_merge_and_save_cache("alphafold", alphafold_to_save)
231
+
232
+ def enrich_proteins_worker(args):
233
+ """
234
+ Worker function to enrich a batch of proteins with sequence/structure data
235
+ """
236
+ protein_names_batch, cache_dir, worker_id = args
237
+ enricher = ProteinDataEnricher(cache_dir)
238
+ enriched_proteins = {}
239
+
240
+ print(f"Worker {worker_id}: Processing {len(protein_names_batch)} proteins")
241
+
242
+ for i, protein_name in enumerate(protein_names_batch):
243
+ enriched_proteins[protein_name] = enricher.get_protein_enriched_data(protein_name)
244
+
245
+ # Save cache every 25 proteins to avoid losing work
246
+ if (i + 1) % 25 == 0:
247
+ enricher.save_cache()
248
+ print(f"Worker {worker_id}: Saved cache after {i + 1} proteins")
249
+
250
+ # Final save
251
+ enricher.save_cache()
252
+ print(f"Worker {worker_id}: Completed batch, final cache save")
253
+
254
+ return enriched_proteins
255
+
256
+ def extract_neighborhood_worker(args):
257
+ """
258
+ Worker function for parallel neighborhood extraction
259
+ """
260
+ center_protein, interactions_by_protein, all_interactions, max_size = args
261
+
262
+ # Get direct neighbors
263
+ neighbors = set()
264
+ relevant_interactions = []
265
+
266
+ for interaction in interactions_by_protein[center_protein]:
267
+ other_protein = (interaction['protein_b'] if interaction['protein_a'] == center_protein
268
+ else interaction['protein_a'])
269
+ neighbors.add(other_protein)
270
+ relevant_interactions.append(interaction)
271
+
272
+ # Limit neighborhood size
273
+ if len(neighbors) > max_size - 1:
274
+ neighbors = set(random.sample(list(neighbors), max_size - 1))
275
+
276
+ # Get all interactions within this neighborhood
277
+ neighborhood_proteins = {center_protein} | neighbors
278
+ neighborhood_interactions = []
279
+
280
+ for interaction in all_interactions:
281
+ if (interaction['protein_a'] in neighborhood_proteins and
282
+ interaction['protein_b'] in neighborhood_proteins):
283
+ neighborhood_interactions.append(interaction)
284
+
285
+ return {
286
+ 'center_protein': center_protein,
287
+ 'proteins': sorted(list(neighborhood_proteins)),
288
+ 'interactions': neighborhood_interactions
289
+ }
290
+
291
+ def create_conversation_examples_worker(args):
292
+ """
293
+ Worker function for parallel conversation creation
294
+ """
295
+ neighborhood, enriched_proteins = args
296
+ creator = ProteinNetworkConversationDataset("") # Dummy instance for methods
297
+ creator.enriched_proteins = enriched_proteins # Set the enriched protein data
298
+ conversations = []
299
+
300
+ # Task 1: Complete protein network given protein list
301
+ conversations.extend(creator.create_protein_list_to_network_examples(neighborhood))
302
+
303
+ # Task 2: Predict interactions for new protein
304
+ conversations.extend(creator.create_new_protein_prediction_examples(neighborhood))
305
+
306
+ # Task 3: Complete partial network
307
+ conversations.extend(creator.create_partial_network_completion_examples(neighborhood))
308
+
309
+ # Task 4: Network property prediction
310
+ conversations.extend(creator.create_network_property_examples(neighborhood))
311
+
312
+ return conversations
313
 
314
  class ProteinNetworkConversationDataset:
315
+ def __init__(self, filename: str, cache_dir: str = "protein_cache"):
316
  """
317
  Create conversational dataset for protein network prediction using diffusion models
318
  """
319
  self.filename = filename
320
+ self.cache_dir = cache_dir
321
  self.df = None
322
  self.graph = nx.Graph()
323
  self.protein_to_id = {}
324
  self.id_to_protein = {}
325
  self.interactions_by_protein = defaultdict(list)
326
+ self.enriched_proteins = {} # Cache for enriched protein data
327
+ self.enricher = ProteinDataEnricher(cache_dir)
328
 
329
  def load_and_parse_biogrid(self):
330
  """Load and parse BioGRID data"""
 
408
 
409
  print(f"Found {len(candidate_proteins)} proteins with degree {min_connections}-{max_connections}")
410
 
411
+ # Limit candidate proteins for processing
412
+ limited_proteins = candidate_proteins[:MAX_PROTEINS_TO_PROCESS]
413
+ print(f"Processing {len(limited_proteins)} proteins with multiprocessing...")
414
+
415
+ # Prepare arguments for parallel processing
416
+ worker_args = [
417
+ (protein, self.interactions_by_protein, interactions, 10)
418
+ for protein in limited_proteins
419
+ ]
420
+
421
+ # Use multiprocessing to extract neighborhoods in parallel
422
+ num_processes = min(int(mp.cpu_count()/2), len(limited_proteins))
423
+ print(f"Using {num_processes} processes")
424
+
425
  neighborhoods = []
426
+ with mp.Pool(processes=num_processes) as pool:
427
+ results = pool.map(extract_neighborhood_worker, worker_args)
428
+
429
+ # Filter neighborhoods with minimum viable size
430
+ neighborhoods = [
431
+ neighborhood for neighborhood in results
432
+ if len(neighborhood['proteins']) >= 3
433
+ ]
434
 
435
  return neighborhoods
436
 
437
+ def enrich_proteins_with_data(self, proteins: List[str]):
438
+ """
439
+ Enrich proteins with UniProt and AlphaFold data using multiprocessing with thread-safe persistent cache
440
+ """
441
+ print(f"Enriching {len(proteins)} proteins with sequence and structural data...")
442
+
443
+ # Check how many proteins are already cached
444
+ cached_count = 0
445
+ proteins_to_fetch = []
446
+
447
+ for protein in proteins:
448
+ # Check if protein is already in enricher's cache
449
+ if (protein in self.enricher.uniprot_cache):
450
+ cached_count += 1
451
+ # Use cached data
452
+ self.enriched_proteins[protein] = self.enricher.get_protein_enriched_data(protein)
453
+ else:
454
+ proteins_to_fetch.append(protein)
455
+
456
+ print(f"Found {cached_count} proteins in cache, need to fetch {len(proteins_to_fetch)} new proteins")
457
+
458
+ if not proteins_to_fetch:
459
+ print("All proteins found in cache!")
460
+ return self.enriched_proteins
461
+
462
+ # Split proteins to fetch into batches for parallel processing
463
+ batch_size = 25 # Smaller batch size for better cache management
464
+ protein_batches = [proteins_to_fetch[i:i+batch_size] for i in range(0, len(proteins_to_fetch), batch_size)]
465
+
466
+ # Prepare arguments with cache directory and worker IDs
467
+ worker_args = [(batch, self.cache_dir, i) for i, batch in enumerate(protein_batches)]
468
+
469
+ # Use multiprocessing to enrich proteins
470
+ num_processes = min(int(mp.cpu_count()/2), len(protein_batches))
471
+ print(f"Using {num_processes} processes for protein enrichment with thread-safe caching")
472
+
473
+ enrichment_start = time.time()
474
+ with mp.Pool(processes=num_processes) as pool:
475
+ results = pool.map(enrich_proteins_worker, worker_args)
476
+
477
+ # Combine results
478
+ for batch_result in results:
479
+ self.enriched_proteins.update(batch_result)
480
+
481
+ # Reload the main enricher's cache to get all the merged data
482
+ print("Reloading cache to get all merged data...")
483
+ self.enricher._load_caches()
484
+
485
+ # Fill in any cached data we might have missed
486
+ for protein in proteins:
487
+ if protein not in self.enriched_proteins and protein in self.enricher.uniprot_cache:
488
+ self.enriched_proteins[protein] = self.enricher.get_protein_enriched_data(protein)
489
+
490
+ enrichment_time = time.time() - enrichment_start
491
+ successful_enrichments = sum(1 for data in self.enriched_proteins.values()
492
+ if data.get('uniprot_id') is not None)
493
+
494
+ print(f"Protein enrichment completed in {enrichment_time:.2f} seconds")
495
+ print(f"Successfully enriched {successful_enrichments}/{len(proteins)} proteins")
496
+ print(f"Final cache sizes - UniProt: {len(self.enricher.uniprot_cache)}, AlphaFold: {len(self.enricher.alphafold_cache)}")
497
+
498
+ return self.enriched_proteins
499
+
500
  def extract_neighborhood(self, center_protein, interactions, max_size=10):
501
  """
502
  Extract neighborhood around a protein
 
532
 
533
  def create_conversation_examples(self, neighborhoods):
534
  """
535
+ Create different types of conversation examples for diffusion training (parallelized)
536
  """
537
+ print(f"Creating conversation examples for {len(neighborhoods)} neighborhoods using multiprocessing...")
538
 
539
+ # Prepare arguments for parallel processing (include enriched protein data)
540
+ worker_args = [(neighborhood, self.enriched_proteins) for neighborhood in neighborhoods]
541
+
542
+ # Use multiprocessing to create conversation examples in parallel
543
+ num_processes = min(int(mp.cpu_count()/2), len(neighborhoods))
544
+ print(f"Using {num_processes} processes for conversation creation")
545
+
546
+ conversations = []
547
+ with mp.Pool(processes=num_processes) as pool:
548
+ results = pool.map(create_conversation_examples_worker, worker_args)
549
 
550
+ # Flatten the results
551
+ for result in results:
552
+ conversations.extend(result)
553
 
554
  return conversations
555
 
556
  def create_protein_list_to_network_examples(self, neighborhood):
557
  """
558
+ Context: List of proteins with sequence/structure info
559
  Generation: Complete interaction network
560
  """
561
  examples = []
562
  proteins = neighborhood['proteins']
563
  interactions = neighborhood['interactions']
564
 
565
+ # Create enriched network representation
566
+ network_text = self.format_enriched_network_as_text(proteins, interactions)
567
 
568
  system_msg = {
569
  "role": "system",
570
+ "content": "You are a protein interaction prediction system. Given a list of proteins with their sequence and structural information, predict all likely interactions between them based on biological knowledge, sequence similarity, and structural compatibility."
571
  }
572
 
573
+ # Create enriched protein context
574
+ protein_context = self.format_proteins_with_context(proteins)
575
+
576
  user_msg = {
577
  "role": "user",
578
+ "content": f"Predict the protein interaction network for these proteins:\n\n{protein_context}"
579
  }
580
 
581
  assistant_msg = {
 
590
 
591
  def create_new_protein_prediction_examples(self, neighborhood):
592
  """
593
+ Context: Known network + new protein with sequence/structure info
594
  Generation: Interactions for the new protein
595
  """
596
  examples = []
 
619
  if not target_interactions:
620
  return examples
621
 
622
+ known_network_text = self.format_enriched_network_as_text(remaining_proteins, known_interactions)
623
  target_network_text = self.format_interactions_as_text(target_interactions)
624
 
625
+ # Get enriched info for target protein
626
+ target_enriched_data = self.enriched_proteins.get(target_protein, {})
627
+ target_context = self.format_proteins_with_context([target_protein])
628
+
629
  system_msg = {
630
  "role": "system",
631
+ "content": "You are a protein interaction prediction system. Given a known protein network and a new protein with sequence and structural information, predict which proteins in the network the new protein will interact with based on sequence similarity, structural compatibility, and functional relationships."
632
  }
633
 
634
  user_msg = {
635
  "role": "user",
636
+ "content": f"Known protein network:\n{known_network_text}\n\nNew protein to integrate:\n{target_context}\n\nPredict the interactions for {target_protein} based on its sequence, structure, and function:"
637
  }
638
 
639
  assistant_msg = {
 
768
  result += f"NETWORK SUMMARY: {len(proteins)} proteins, {total_interactions} unique interactions"
769
  return result.strip()
770
 
771
+ def format_proteins_with_context(self, proteins: List[str]) -> str:
772
+ """
773
+ Format proteins with their enriched sequence and structural context
774
+ """
775
+ protein_contexts = []
776
+
777
+ for protein in sorted(proteins):
778
+ enriched_data = self.enriched_proteins.get(protein, {})
779
+
780
+ context_parts = [f"PROTEIN: {protein}"]
781
+
782
+ # Add UniProt information
783
+ if enriched_data.get('uniprot_id'):
784
+ context_parts.append(f" UniProt ID: {enriched_data['uniprot_id']}")
785
+
786
+ if enriched_data.get('protein_name'):
787
+ context_parts.append(f" Full Name: {enriched_data['protein_name']}")
788
+
789
+ if enriched_data.get('organism'):
790
+ context_parts.append(f" Organism: {enriched_data['organism']}")
791
+
792
+ # Add sequence information
793
+ if enriched_data.get('sequence_length'):
794
+ context_parts.append(f" Sequence Length: {enriched_data['sequence_length']} amino acids")
795
+
796
+ if enriched_data.get('sequence'):
797
+ # Show first 50 and last 20 amino acids
798
+ seq = enriched_data['sequence']
799
+ if len(seq) > 70:
800
+ seq_preview = f"{seq[:50]}...{seq[-20:]}"
801
+ else:
802
+ seq_preview = seq
803
+ context_parts.append(f" Sequence: {seq_preview}")
804
+
805
+ # Add structural information
806
+ if enriched_data.get('has_structure'):
807
+ context_parts.append(f" AlphaFold Structure: Available")
808
+ if enriched_data.get('model_confidence'):
809
+ context_parts.append(f" Structure Confidence: {enriched_data['model_confidence']}")
810
+ if enriched_data.get('structure_coverage'):
811
+ context_parts.append(f" Structure Coverage: residues {enriched_data['structure_coverage']}")
812
+ else:
813
+ context_parts.append(f" AlphaFold Structure: Not available")
814
+
815
+ # Add functional information
816
+ if enriched_data.get('function'):
817
+ func_text = enriched_data['function'][:200] + "..." if len(enriched_data['function']) > 200 else enriched_data['function']
818
+ context_parts.append(f" Function: {func_text}")
819
+
820
+ protein_contexts.append("\n".join(context_parts))
821
+
822
+ return "\n\n".join(protein_contexts)
823
+
824
+ def format_enriched_network_as_text(self, proteins, interactions):
825
+ """
826
+ Format network with enriched protein information
827
+ """
828
+ # First show the basic network
829
+ basic_network = self.format_network_as_text(proteins, interactions)
830
+
831
+ # Add enriched protein summaries
832
+ enriched_summary = "\n\nPROTEIN DETAILS:\n"
833
+
834
+ for protein in sorted(proteins):
835
+ enriched_data = self.enriched_proteins.get(protein, {})
836
+ details = [f"{protein}"]
837
+
838
+ if enriched_data.get('sequence_length'):
839
+ details.append(f"{enriched_data['sequence_length']}aa")
840
+
841
+ if enriched_data.get('has_structure'):
842
+ confidence = enriched_data.get('model_confidence', 'unknown')
843
+ details.append(f"AlphaFold({confidence})")
844
+
845
+ if enriched_data.get('organism'):
846
+ org = enriched_data['organism'].split()[0] if ' ' in enriched_data['organism'] else enriched_data['organism']
847
+ details.append(f"{org}")
848
+
849
+ enriched_summary += f" {' | '.join(details)}\n"
850
+
851
+ return basic_network + enriched_summary
852
+
853
  def format_interactions_as_text(self, interactions):
854
  """
855
  Format just interactions as text
 
880
 
881
  def save_conversation_dataset(self, output_file="processed_dataset.json"):
882
  """
883
+ Create and save the full conversation dataset with enriched protein data
884
  """
885
+ start_time = time.time()
886
+
887
  # Load and process data
888
+ print("Step 1: Loading and parsing data...")
889
+ load_start = time.time()
890
  interactions, proteins = self.load_and_parse_biogrid()
891
+ load_time = time.time() - load_start
892
+ print(f"Data loading completed in {load_time:.2f} seconds")
893
+
894
+ # Build neighborhoods
895
+ print("Step 2: Building protein neighborhoods...")
896
+ neighborhood_start = time.time()
897
  neighborhoods = self.build_network_neighborhoods(interactions, proteins)
898
+ neighborhood_time = time.time() - neighborhood_start
899
+ print(f"Built {len(neighborhoods)} protein neighborhoods in {neighborhood_time:.2f} seconds")
900
+
901
+ # Enrich proteins with sequence and structural data
902
+ print("Step 3: Enriching proteins with sequence and structural data...")
903
+ enrichment_start = time.time()
904
+ # Get unique proteins from neighborhoods
905
+ unique_proteins = set()
906
+ for neighborhood in neighborhoods:
907
+ unique_proteins.update(neighborhood['proteins'])
908
 
909
+ self.enrich_proteins_with_data(list(unique_proteins))
910
+ enrichment_time = time.time() - enrichment_start
911
+ print(f"Protein enrichment completed in {enrichment_time:.2f} seconds")
912
 
913
  # Create conversation examples
914
+ print("Step 4: Creating conversation examples...")
915
+ conversation_start = time.time()
916
  conversations = self.create_conversation_examples(neighborhoods)
917
+ conversation_time = time.time() - conversation_start
918
+ print(f"Created {len(conversations)} conversation examples in {conversation_time:.2f} seconds")
919
 
920
  # Shuffle the dataset
921
+ print("Step 5: Shuffling and saving dataset...")
922
  random.shuffle(conversations)
923
 
924
  # Save dataset
925
  with open(output_file, 'w') as f:
926
  json.dump(conversations, f, indent=2)
927
 
928
+ # Save enriched protein data separately for reference
929
+ enriched_data_file = output_file.replace('.json', '_protein_data.json')
930
+ with open(enriched_data_file, 'w') as f:
931
+ json.dump(self.enriched_proteins, f, indent=2)
932
+
933
+ total_time = time.time() - start_time
934
  print(f"Saved dataset to {output_file}")
935
+ print(f"Saved enriched protein data to {enriched_data_file}")
936
+ print(f"Total processing time: {total_time:.2f} seconds")
937
 
938
  # Show examples
939
  print("\n=== Example Conversations ===")
940
+ for i, conv in enumerate(conversations[:2]):
941
  print(f"\n--- Example {i+1} ---")
942
  for msg in conv["updated"]:
943
+ print(f"{msg['role'].upper()}: {msg['content'][:300]}...")
944
 
945
  return conversations
946
 
947
  # Usage
948
  if __name__ == "__main__":
949
+ # Set random seed for reproducibility
950
+ random.seed(42)
951
+ np.random.seed(42)
952
+
953
+ print(f"Configuration: Processing up to {MAX_PROTEINS_TO_PROCESS} proteins")
954
+ print(f"Available CPU cores: {int(mp.cpu_count()/2)}")
955
+ print(f"Cache directory: protein_cache/")
956
+
957
  creator = ProteinNetworkConversationDataset(
958
+ "./unzipped/BIOGRID-ALL-4.4.246.tab3/BIOGRID-ALL-4.4.246.tab3.txt",
959
+ cache_dir="protein_cache"
960
  )
961
 
962
  conversations = creator.save_conversation_dataset("processed_dataset.json")
 
979
 
980
  print("\nTask distribution:")
981
  for task, count in task_types.items():
982
+ print(f" {task}: {count}")
983
+
984
+ # Print enrichment statistics
985
+ print(f"\n=== Protein Enrichment Summary ===")
986
+ total_proteins = len(creator.enriched_proteins)
987
+ proteins_with_uniprot = sum(1 for data in creator.enriched_proteins.values()
988
+ if data.get('uniprot_id') is not None)
989
+ proteins_with_sequence = sum(1 for data in creator.enriched_proteins.values()
990
+ if data.get('sequence') is not None)
991
+ proteins_with_structure = sum(1 for data in creator.enriched_proteins.values()
992
+ if data.get('has_structure') == True)
993
+
994
+ print(f"Total proteins processed: {total_proteins}")
995
+ print(f"Proteins with UniProt data: {proteins_with_uniprot} ({proteins_with_uniprot/total_proteins*100:.1f}%)")
996
+ print(f"Proteins with sequences: {proteins_with_sequence} ({proteins_with_sequence/total_proteins*100:.1f}%)")
997
+ print(f"Proteins with AlphaFold structures: {proteins_with_structure} ({proteins_with_structure/total_proteins*100:.1f}%)")
998
+
999
+ # Print cache statistics
1000
+ print(f"\n=== Cache Statistics ===")
1001
+ print(f"UniProt cache entries: {len(creator.enricher.uniprot_cache)}")
1002
+ print(f"AlphaFold cache entries: {len(creator.enricher.alphafold_cache)}")
1003
+ print(f"Cache files location: {creator.cache_dir}/")