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
 
5ce3f7b
a26b74a
 
 
 
 
5ce3f7b
a26b74a
 
 
 
 
 
 
fe96401
a26b74a
fe96401
 
a26b74a
fe96401
 
a26b74a
fe96401
 
 
 
 
 
a26b74a
fe96401
 
 
 
 
 
 
 
 
 
a26b74a
fe96401
 
 
a26b74a
 
fe96401
 
a26b74a
fe96401
 
a26b74a
 
fe96401
a26b74a
 
 
 
 
 
fe96401
 
 
 
 
 
a26b74a
fe96401
 
a26b74a
 
 
fe96401
a26b74a
 
fe96401
a26b74a
 
 
 
 
fe96401
 
 
 
 
 
 
 
a26b74a
fe96401
 
a26b74a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe96401
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
import pandas as pd
import numpy as np
import networkx as nx
from typing import List, Dict, Tuple, Set, Optional
import json
import random
from collections import defaultdict, Counter
import multiprocessing as mp
from functools import partial
import time
import requests
from urllib.parse import quote
import xml.etree.ElementTree as ET
from time import sleep
import re
import os
import fcntl
import tempfile
import shutil

# Global configuration
MAX_PROTEINS_TO_PROCESS = 1000
TRUNCATE_MIDDLE_ABOVE_THIS = 120

class ProteinDataEnricher:
    """
    Handles fetching and caching protein sequence and structural data with thread-safe persistent cache
    """
    def __init__(self, cache_dir: str = "protein_cache"):
        self.cache_dir = cache_dir
        self.uniprot_cache = {}
        self.alphafold_cache = {}
        self.session = requests.Session()
        self.session.headers.update({'User-Agent': 'ProteinNetworkDataset/1.0'})
        
        # Create cache directory if it doesn't exist
        os.makedirs(cache_dir, exist_ok=True)
        
        # Load existing caches
        self._load_caches()
        
    def _get_cache_files(self):
        """Get cache file paths"""
        uniprot_cache_file = os.path.join(self.cache_dir, "uniprot_cache.json")
        alphafold_cache_file = os.path.join(self.cache_dir, "alphafold_cache.json")
        return uniprot_cache_file, alphafold_cache_file
        
    def _load_caches(self):
        """Load existing caches from disk"""
        uniprot_cache_file, alphafold_cache_file = self._get_cache_files()
        
        # Load UniProt cache
        if os.path.exists(uniprot_cache_file):
            try:
                with open(uniprot_cache_file, 'r') as f:
                    self.uniprot_cache = json.load(f)
                print(f"Loaded UniProt cache with {len(self.uniprot_cache)} entries")
            except Exception as e:
                print(f"Error loading UniProt cache: {e}")
                self.uniprot_cache = {}
        
        # Load AlphaFold cache
        if os.path.exists(alphafold_cache_file):
            try:
                with open(alphafold_cache_file, 'r') as f:
                    self.alphafold_cache = json.load(f)
                print(f"Loaded AlphaFold cache with {len(self.alphafold_cache)} entries")
            except Exception as e:
                print(f"Error loading AlphaFold cache: {e}")
                self.alphafold_cache = {}
    
    def _safe_merge_and_save_cache(self, cache_type: str, new_data: Dict):
        """
        Safely merge new cache data with existing cache using file locking
        """
        if cache_type == "uniprot":
            cache_file = os.path.join(self.cache_dir, "uniprot_cache.json")
        elif cache_type == "alphafold":
            cache_file = os.path.join(self.cache_dir, "alphafold_cache.json")
        else:
            raise ValueError(f"Unknown cache type: {cache_type}")
        
        # Create lock file
        lock_file = cache_file + ".lock"
        
        try:
            # Acquire lock
            with open(lock_file, 'w') as lock:
                fcntl.flock(lock.fileno(), fcntl.LOCK_EX)
                
                # Load current cache from file
                current_cache = {}
                if os.path.exists(cache_file):
                    try:
                        with open(cache_file, 'r') as f:
                            current_cache = json.load(f)
                    except Exception as e:
                        print(f"Error loading {cache_type} cache for merge: {e}")
                        current_cache = {}
                
                # Merge new data with current cache
                current_cache.update(new_data)
                
                # Atomic write: write to temp file then rename
                temp_file = cache_file + ".tmp"
                with open(temp_file, 'w') as f:
                    json.dump(current_cache, f, indent=2)
                
                # Atomic rename
                shutil.move(temp_file, cache_file)
                
                print(f"Merged and saved {cache_type} cache: {len(current_cache)} total entries")
                
        except Exception as e:
            print(f"Error saving {cache_type} cache: {e}")
        finally:
            # Clean up lock file
            try:
                os.remove(lock_file)
            except:
                pass
    
    def get_uniprot_info(self, protein_name: str) -> Optional[Dict]:
        """
        Fetch UniProt information for a protein
        """
        if protein_name in self.uniprot_cache:
            return self.uniprot_cache[protein_name]
        
        try:
            # Search UniProt for the protein
            search_url = f"https://rest.uniprot.org/uniprotkb/search"
            params = {
                'query': f'gene_exact:{protein_name} OR protein_name:{protein_name}',
                'format': 'json',
                'size': 1
            }
            
            response = self.session.get(search_url, params=params, timeout=10)
            if response.status_code == 200:
                data = response.json()
                if data.get('results'):
                    entry = data['results'][0]
                    uniprot_info = {
                        'uniprot_id': entry.get('primaryAccession'),
                        'protein_name': entry.get('proteinDescription', {}).get('recommendedName', {}).get('fullName', {}).get('value'),
                        'gene_names': [gn.get('geneName', {}).get('value') for gn in entry.get('genes', []) if gn.get('geneName')],
                        'organism': entry.get('organism', {}).get('scientificName'),
                        'sequence': entry.get('sequence', {}).get('value'),
                        'sequence_length': entry.get('sequence', {}).get('length'),
                        'function': entry.get('comments', [{}])[0].get('texts', [{}])[0].get('value') if entry.get('comments') else None
                    }
                    self.uniprot_cache[protein_name] = uniprot_info
                    return uniprot_info
                    
        except Exception as e:
            print(f"Error fetching UniProt data for {protein_name}: {e}")
        
        self.uniprot_cache[protein_name] = None
        return None
    
    def get_alphafold_info(self, uniprot_id: str) -> Optional[Dict]:
        """
        Fetch AlphaFold structural information for a UniProt ID
        """
        if not uniprot_id:
            return None
            
        cache_key = uniprot_id
        if cache_key in self.alphafold_cache:
            return self.alphafold_cache[cache_key]
        
        try:
            # Check if AlphaFold structure exists
            af_url = f"https://alphafold.ebi.ac.uk/api/prediction/{uniprot_id}"
            response = self.session.get(af_url, timeout=10)
            
            if response.status_code == 200:
                af_data = response.json()
                if af_data:
                    entry = af_data[0] if isinstance(af_data, list) else af_data
                    
                    alphafold_info = {
                        'alphafold_id': entry.get('entryId'),
                        'model_confidence': entry.get('modelConfidence'),
                        'model_url': entry.get('pdbUrl'),
                        'confidence_score': entry.get('modelConfidence'),
                        'structure_coverage': f"{entry.get('uniprotStart', 1)}-{entry.get('uniprotEnd', 'end')}",
                        'has_structure': True
                    }
                    self.alphafold_cache[cache_key] = alphafold_info
                    return alphafold_info
                    
        except Exception as e:
            print(f"Error fetching AlphaFold data for {uniprot_id}: {e}")
        
        self.alphafold_cache[cache_key] = {'has_structure': False}
        return {'has_structure': False}
    
    def get_protein_enriched_data(self, protein_name: str) -> Dict:
        """
        Get combined UniProt and AlphaFold data for a protein
        """
        enriched_data = {'protein_name': protein_name}
        
        # Get UniProt info
        uniprot_info = self.get_uniprot_info(protein_name)
        if uniprot_info:
            enriched_data.update(uniprot_info)
            
            # Get AlphaFold info if we have a UniProt ID
            if uniprot_info.get('uniprot_id'):
                alphafold_info = self.get_alphafold_info(uniprot_info['uniprot_id'])
                if alphafold_info:
                    enriched_data.update(alphafold_info)
        
        # Add rate limiting
        sleep(0.1)  # Small delay to be respectful to APIs
        return enriched_data
    
    def save_cache(self):
        """Save caches using safe merge strategy"""
        # Only save entries that are not None/empty
        uniprot_to_save = {k: v for k, v in self.uniprot_cache.items() if v is not None}
        alphafold_to_save = {k: v for k, v in self.alphafold_cache.items() if v is not None}
        
        if uniprot_to_save:
            self._safe_merge_and_save_cache("uniprot", uniprot_to_save)
        
        if alphafold_to_save:
            self._safe_merge_and_save_cache("alphafold", alphafold_to_save)

def enrich_proteins_worker(args):
    """
    Worker function to enrich a batch of proteins with sequence/structure data
    """
    protein_names_batch, cache_dir, worker_id = args
    enricher = ProteinDataEnricher(cache_dir)
    enriched_proteins = {}
    
    print(f"Worker {worker_id}: Processing {len(protein_names_batch)} proteins")
    
    for i, protein_name in enumerate(protein_names_batch):
        enriched_proteins[protein_name] = enricher.get_protein_enriched_data(protein_name)
        
        # Save cache every 25 proteins to avoid losing work
        if (i + 1) % 25 == 0:
            enricher.save_cache()
            print(f"Worker {worker_id}: Saved cache after {i + 1} proteins")
    
    # Final save
    enricher.save_cache()
    print(f"Worker {worker_id}: Completed batch, final cache save")
    
    return enriched_proteins

def extract_neighborhood_worker(args):
    """
    Worker function for parallel neighborhood extraction
    """
    center_protein, interactions_by_protein, all_interactions, max_size = args
    
    # Get direct neighbors
    neighbors = set()
    relevant_interactions = []
    
    for interaction in interactions_by_protein[center_protein]:
        other_protein = (interaction['protein_b'] if interaction['protein_a'] == center_protein 
                       else interaction['protein_a'])
        neighbors.add(other_protein)
        relevant_interactions.append(interaction)
    
    # Limit neighborhood size
    if len(neighbors) > max_size - 1:
        neighbors = set(random.sample(list(neighbors), max_size - 1))
    
    # Get all interactions within this neighborhood
    neighborhood_proteins = {center_protein} | neighbors
    neighborhood_interactions = []
    
    for interaction in all_interactions:
        if (interaction['protein_a'] in neighborhood_proteins and 
            interaction['protein_b'] in neighborhood_proteins):
            neighborhood_interactions.append(interaction)
    
    return {
        'center_protein': center_protein,
        'proteins': sorted(list(neighborhood_proteins)),
        'interactions': neighborhood_interactions
    }

def create_conversation_examples_worker(args):
    """
    Worker function for parallel conversation creation
    """
    neighborhood, enriched_proteins = args
    creator = ProteinNetworkConversationDataset("")  # Dummy instance for methods
    creator.enriched_proteins = enriched_proteins  # Set the enriched protein data
    conversations = []
    
    # Task 1: Complete protein network given protein list
    conversations.extend(creator.create_protein_list_to_network_examples(neighborhood))
    
    # Task 2: Predict interactions for new protein
    conversations.extend(creator.create_new_protein_prediction_examples(neighborhood))
    
    # Task 3: Complete partial network
    conversations.extend(creator.create_partial_network_completion_examples(neighborhood))
    
    # Task 4: Network property prediction
    conversations.extend(creator.create_network_property_examples(neighborhood))
    
    return conversations

class ProteinNetworkConversationDataset:
    def __init__(self, filename: str, cache_dir: str = "protein_cache"):
        """
        Create conversational dataset for protein network prediction using diffusion models
        """
        self.filename = filename
        self.cache_dir = cache_dir
        self.df = None
        self.graph = nx.Graph()
        self.protein_to_id = {}
        self.id_to_protein = {}
        self.interactions_by_protein = defaultdict(list)
        self.enriched_proteins = {}  # Cache for enriched protein data
        self.enricher = ProteinDataEnricher(cache_dir)
        
    def load_and_parse_biogrid(self):
        """Load and parse BioGRID data"""
        print("Loading BioGRID data...")
        self.df = pd.read_csv(
            self.filename, 
            sep='\t', 
            comment='#',
            low_memory=False,
            dtype=str
        )
        
        # Based on your sample output - adjust column indices as needed
        protein_a_col = 7  # MAP2K4, MYPN, etc.
        protein_b_col = 8  # FLNC, etc.
        interaction_type_col = 11  # "Two-hybrid", "physical", etc.
        
        interactions = []
        protein_set = set()
        # Use set to track unique interactions and avoid duplicates
        seen_interactions = set()
        
        for idx, row in self.df.iterrows():
            try:
                protein_a = str(row.iloc[protein_a_col]).strip()
                protein_b = str(row.iloc[protein_b_col]).strip()
                interaction_type = str(row.iloc[interaction_type_col]).strip()
                
                if protein_a in ['-', 'nan', ''] or protein_b in ['-', 'nan', '']:
                    continue
                
                # Skip self-interactions
                if protein_a == protein_b:
                    continue
                    
                # Create canonical interaction key (sorted to avoid A-B vs B-A duplicates)
                interaction_key = tuple(sorted([protein_a, protein_b]) + [interaction_type])
                
                # Skip if we've already seen this exact interaction
                if interaction_key in seen_interactions:
                    continue
                    
                seen_interactions.add(interaction_key)
                protein_set.add(protein_a)
                protein_set.add(protein_b)
                
                interaction = {
                    'protein_a': protein_a,
                    'protein_b': protein_b,
                    'interaction_type': interaction_type
                }
                interactions.append(interaction)
                
                # Build protein interaction index
                self.interactions_by_protein[protein_a].append(interaction)
                self.interactions_by_protein[protein_b].append(interaction)
                
            except Exception:
                continue
        
        print(f"Extracted {len(interactions)} valid unique interactions")
        print(f"Found {len(protein_set)} unique proteins")
        
        return interactions, sorted(list(protein_set))
    
    def build_network_neighborhoods(self, interactions, proteins, min_connections=3, max_connections=15):
        """
        Build subnetworks around high-degree proteins for training examples
        """
        # Count protein degrees
        protein_degrees = Counter()
        for interaction in interactions:
            protein_degrees[interaction['protein_a']] += 1
            protein_degrees[interaction['protein_b']] += 1
        
        # Find proteins with moderate connectivity (good for examples)
        candidate_proteins = [
            protein for protein, degree in protein_degrees.items()
            if min_connections <= degree <= max_connections
        ]
        
        print(f"Found {len(candidate_proteins)} proteins with degree {min_connections}-{max_connections}")
        
        # Limit candidate proteins for processing
        limited_proteins = candidate_proteins[:MAX_PROTEINS_TO_PROCESS]
        print(f"Processing {len(limited_proteins)} proteins with multiprocessing...")
        
        # Prepare arguments for parallel processing
        worker_args = [
            (protein, self.interactions_by_protein, interactions, 10) 
            for protein in limited_proteins
        ]
        
        # Use multiprocessing to extract neighborhoods in parallel
        num_processes = min(int(mp.cpu_count()/2), len(limited_proteins))
        print(f"Using {num_processes} processes")
        
        neighborhoods = []
        with mp.Pool(processes=num_processes) as pool:
            results = pool.map(extract_neighborhood_worker, worker_args)
            
            # Filter neighborhoods with minimum viable size
            neighborhoods = [
                neighborhood for neighborhood in results 
                if len(neighborhood['proteins']) >= 3
            ]
        
        return neighborhoods
    
    def enrich_proteins_with_data(self, proteins: List[str]):
        """
        Enrich proteins with UniProt and AlphaFold data using multiprocessing with thread-safe persistent cache
        """
        print(f"Enriching {len(proteins)} proteins with sequence and structural data...")
        
        # Check how many proteins are already cached
        cached_count = 0
        proteins_to_fetch = []
        
        for protein in proteins:
            # Check if protein is already in enricher's cache
            if (protein in self.enricher.uniprot_cache):
                cached_count += 1
                # Use cached data
                self.enriched_proteins[protein] = self.enricher.get_protein_enriched_data(protein)
            else:
                proteins_to_fetch.append(protein)
        
        print(f"Found {cached_count} proteins in cache, need to fetch {len(proteins_to_fetch)} new proteins")
        
        if not proteins_to_fetch:
            print("All proteins found in cache!")
            return self.enriched_proteins
        
        # Split proteins to fetch into batches for parallel processing
        batch_size = 25  # Smaller batch size for better cache management
        protein_batches = [proteins_to_fetch[i:i+batch_size] for i in range(0, len(proteins_to_fetch), batch_size)]
        
        # Prepare arguments with cache directory and worker IDs
        worker_args = [(batch, self.cache_dir, i) for i, batch in enumerate(protein_batches)]
        
        # Use multiprocessing to enrich proteins
        num_processes = min(int(mp.cpu_count()/2), len(protein_batches))
        print(f"Using {num_processes} processes for protein enrichment with thread-safe caching")
        
        enrichment_start = time.time()
        with mp.Pool(processes=num_processes) as pool:
            results = pool.map(enrich_proteins_worker, worker_args)
        
        # Combine results
        for batch_result in results:
            self.enriched_proteins.update(batch_result)
        
        # Reload the main enricher's cache to get all the merged data
        print("Reloading cache to get all merged data...")
        self.enricher._load_caches()
        
        # Fill in any cached data we might have missed
        for protein in proteins:
            if protein not in self.enriched_proteins and protein in self.enricher.uniprot_cache:
                self.enriched_proteins[protein] = self.enricher.get_protein_enriched_data(protein)
        
        enrichment_time = time.time() - enrichment_start
        successful_enrichments = sum(1 for data in self.enriched_proteins.values() 
                                   if data.get('uniprot_id') is not None)
        
        print(f"Protein enrichment completed in {enrichment_time:.2f} seconds")
        print(f"Successfully enriched {successful_enrichments}/{len(proteins)} proteins")
        print(f"Final cache sizes - UniProt: {len(self.enricher.uniprot_cache)}, AlphaFold: {len(self.enricher.alphafold_cache)}")
        
        return self.enriched_proteins
    
    def extract_neighborhood(self, center_protein, interactions, max_size=10):
        """
        Extract neighborhood around a protein
        """
        # Get direct neighbors
        neighbors = set()
        relevant_interactions = []
        
        for interaction in self.interactions_by_protein[center_protein]:
            other_protein = (interaction['protein_b'] if interaction['protein_a'] == center_protein 
                           else interaction['protein_a'])
            neighbors.add(other_protein)
            relevant_interactions.append(interaction)
        
        # Limit neighborhood size
        if len(neighbors) > max_size - 1:
            neighbors = set(random.sample(list(neighbors), max_size - 1))
        
        # Get all interactions within this neighborhood
        neighborhood_proteins = {center_protein} | neighbors
        neighborhood_interactions = []
        
        for interaction in interactions:
            if (interaction['protein_a'] in neighborhood_proteins and 
                interaction['protein_b'] in neighborhood_proteins):
                neighborhood_interactions.append(interaction)
        
        return {
            'center_protein': center_protein,
            'proteins': sorted(list(neighborhood_proteins)),
            'interactions': neighborhood_interactions
        }
    
    def create_conversation_examples(self, neighborhoods):
        """
        Create different types of conversation examples for diffusion training (parallelized)
        """
        print(f"Creating conversation examples for {len(neighborhoods)} neighborhoods using multiprocessing...")
        
        # Prepare arguments for parallel processing (include enriched protein data)
        worker_args = [(neighborhood, self.enriched_proteins) for neighborhood in neighborhoods]
        
        # Use multiprocessing to create conversation examples in parallel
        num_processes = min(int(mp.cpu_count()/2), len(neighborhoods))
        print(f"Using {num_processes} processes for conversation creation")
        
        conversations = []
        with mp.Pool(processes=num_processes) as pool:
            results = pool.map(create_conversation_examples_worker, worker_args)
            
            # Flatten the results
            for result in results:
                conversations.extend(result)
        
        return conversations
    
    def create_protein_list_to_network_examples(self, neighborhood):
        """
        Context: List of proteins with sequence/structure info
        Generation: Complete interaction network
        """
        examples = []
        proteins = neighborhood['proteins']
        interactions = neighborhood['interactions']
        
        # Create enriched network representation
        network_text = self.format_enriched_network_as_text(proteins, interactions)
        
        system_msg = {
            "role": "system",
            "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."
        }
        
        # Create enriched protein context
        protein_context = self.format_proteins_with_context(proteins)
        
        user_msg = {
            "role": "user", 
            "content": f"Predict the protein interaction network for these proteins:\n\n{protein_context}"
        }
        
        assistant_msg = {
            "role": "assistant",
            "content": network_text
        }
        
        conversation = [system_msg, user_msg, assistant_msg]
        examples.append({"updated": conversation})
        
        return examples
    
    def create_new_protein_prediction_examples(self, neighborhood):
        """
        Context: Known network + new protein with sequence/structure info
        Generation: Interactions for the new protein
        """
        examples = []
        if len(neighborhood['proteins']) < 4:
            return examples
            
        proteins = neighborhood['proteins']
        interactions = neighborhood['interactions']
        
        # Remove one protein and its interactions for prediction
        target_protein = random.choice(proteins)
        remaining_proteins = [p for p in proteins if p != target_protein]
        
        # Known network (without target protein)
        known_interactions = [
            i for i in interactions 
            if target_protein not in [i['protein_a'], i['protein_b']]
        ]
        
        # Target interactions (what we want to predict)
        target_interactions = [
            i for i in interactions
            if target_protein in [i['protein_a'], i['protein_b']]
        ]
        
        if not target_interactions:
            return examples
        
        known_network_text = self.format_enriched_network_as_text(remaining_proteins, known_interactions)
        target_network_text = self.format_interactions_as_text(target_interactions)
        
        # Get enriched info for target protein
        target_enriched_data = self.enriched_proteins.get(target_protein, {})
        target_context = self.format_proteins_with_context([target_protein])
        
        system_msg = {
            "role": "system",
            "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."
        }
        
        user_msg = {
            "role": "user",
            "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:"
        }
        
        assistant_msg = {
            "role": "assistant", 
            "content": target_network_text
        }
        
        conversation = [system_msg, user_msg, assistant_msg]
        examples.append({"updated": conversation})
        
        return examples
    
    def create_partial_network_completion_examples(self, neighborhood):
        """
        Context: Partial network with some missing interactions
        Generation: Complete network
        """
        examples = []
        proteins = neighborhood['proteins']
        interactions = neighborhood['interactions']
        
        if len(interactions) < 3:
            return examples
        
        # Randomly hide some interactions
        n_hidden = max(1, len(interactions) // 3)
        hidden_interactions = random.sample(interactions, n_hidden)
        visible_interactions = [i for i in interactions if i not in hidden_interactions]
        
        partial_network_text = self.format_network_as_text(proteins, visible_interactions)
        complete_network_text = self.format_network_as_text(proteins, interactions)
        
        system_msg = {
            "role": "system",
            "content": "You are a protein interaction prediction system. Given a partial protein network, predict the complete network including missing interactions."
        }
        
        user_msg = {
            "role": "user",
            "content": f"Complete this partial protein network:\n{partial_network_text}"
        }
        
        assistant_msg = {
            "role": "assistant",
            "content": complete_network_text
        }
        
        conversation = [system_msg, user_msg, assistant_msg]
        examples.append({"updated": conversation})
        
        return examples
    
    def create_network_property_examples(self, neighborhood):
        """
        Context: Network properties and constraints
        Generation: Network that satisfies those properties
        """
        examples = []
        proteins = neighborhood['proteins']
        interactions = neighborhood['interactions']
        
        # Calculate network properties
        n_proteins = len(proteins)
        n_interactions = len(interactions)
        density = (2 * n_interactions) / (n_proteins * (n_proteins - 1)) if n_proteins > 1 else 0
        
        # Find hub proteins (high degree)
        protein_degrees = Counter()
        for interaction in interactions:
            protein_degrees[interaction['protein_a']] += 1
            protein_degrees[interaction['protein_b']] += 1
        
        hub_proteins = [p for p, degree in protein_degrees.most_common(2)]
        
        network_text = self.format_network_as_text(proteins, interactions)
        
        system_msg = {
            "role": "system",
            "content": "You are a protein interaction network generator. Given network constraints and properties, generate a biologically plausible protein network."
        }
        
        properties_text = (f"Generate a protein network with the following properties:\n"
                         f"- Proteins: {', '.join(proteins)}\n"
                         f"- Network density: approximately {density:.2f}\n"
                         f"- Hub proteins (highly connected): {', '.join(hub_proteins)}\n"
                         f"- Total interactions: approximately {n_interactions}")
        
        user_msg = {
            "role": "user",
            "content": properties_text
        }
        
        assistant_msg = {
            "role": "assistant",
            "content": network_text
        }
        
        conversation = [system_msg, user_msg, assistant_msg]
        examples.append({"updated": conversation})
        
        return examples
    
    def format_network_as_text(self, proteins, interactions):
        """
        Format network as structured text for the model to predict
        """
        # Sort for consistency
        proteins = sorted(proteins)
        
        # Group interactions by type and use sets to avoid duplicates
        interactions_by_type = defaultdict(set)
        for interaction in interactions:
            # Skip self-interactions
            if interaction['protein_a'] == interaction['protein_b']:
                continue
                
            int_type = interaction.get('interaction_type', 'physical')
            # Ensure consistent ordering
            p1, p2 = sorted([interaction['protein_a'], interaction['protein_b']])
            interactions_by_type[int_type].add(f"{p1}--{p2}")
        
        result = f"PROTEINS: {', '.join(proteins)}\n\n"
        
        for int_type, edges in interactions_by_type.items():
            if edges:
                result += f"{int_type.upper()} INTERACTIONS:\n"
                for edge in sorted(edges):  # Sort the set for consistent output
                    result += f"  {edge}\n"
                result += "\n"
        
        total_interactions = sum(len(edges) for edges in interactions_by_type.values())
        result += f"NETWORK SUMMARY: {len(proteins)} proteins, {total_interactions} unique interactions"
        return result.strip()
    
    def format_proteins_with_context(self, proteins: List[str]) -> str:
        """
        Format proteins with their enriched sequence and structural context
        """
        protein_contexts = []
        
        for protein in sorted(proteins):
            enriched_data = self.enriched_proteins.get(protein, {})
            
            context_parts = [f"PROTEIN: {protein}"]
            
            # Add UniProt information
            if enriched_data.get('uniprot_id'):
                context_parts.append(f"  UniProt ID: {enriched_data['uniprot_id']}")
            
            if enriched_data.get('protein_name'):
                context_parts.append(f"  Full Name: {enriched_data['protein_name']}")
            
            if enriched_data.get('organism'):
                context_parts.append(f"  Organism: {enriched_data['organism']}")
            
            # Add sequence information
            if enriched_data.get('sequence_length'):
                context_parts.append(f"  Sequence Length: {enriched_data['sequence_length']} amino acids")
            
            if enriched_data.get('sequence'):
                # Show first 50 and last 20 amino acids
                seq = enriched_data['sequence']
                if len(seq) > TRUNCATE_MIDDLE_ABOVE_THIS:
                    seq_preview = f"{seq[:int(TRUNCATE_MIDDLE_ABOVE_THIS*0.5)]}...{seq[-int(TRUNCATE_MIDDLE_ABOVE_THIS*0.2):]}"
                else:
                    seq_preview = seq
                context_parts.append(f"  Sequence: {seq_preview}")
            
            # Add structural information
            if enriched_data.get('has_structure'):
                context_parts.append(f"  AlphaFold Structure: Available")
                if enriched_data.get('model_confidence'):
                    context_parts.append(f"  Structure Confidence: {enriched_data['model_confidence']}")
                if enriched_data.get('structure_coverage'):
                    context_parts.append(f"  Structure Coverage: residues {enriched_data['structure_coverage']}")
            else:
                context_parts.append(f"  AlphaFold Structure: Not available")
            
            # Add functional information
            if enriched_data.get('function'):
                func_text = enriched_data['function'][:200] + "..." if len(enriched_data['function']) > 200 else enriched_data['function']
                context_parts.append(f"  Function: {func_text}")
            
            protein_contexts.append("\n".join(context_parts))
        
        return "\n\n".join(protein_contexts)
    
    def format_enriched_network_as_text(self, proteins, interactions):
        """
        Format network with enriched protein information
        """
        # First show the basic network
        basic_network = self.format_network_as_text(proteins, interactions)
        
        # Add enriched protein summaries
        enriched_summary = "\n\nPROTEIN DETAILS:\n"
        
        for protein in sorted(proteins):
            enriched_data = self.enriched_proteins.get(protein, {})
            details = [f"{protein}"]
            
            if enriched_data.get('sequence_length'):
                details.append(f"{enriched_data['sequence_length']}aa")
            
            if enriched_data.get('has_structure'):
                confidence = enriched_data.get('model_confidence', 'unknown')
                details.append(f"AlphaFold({confidence})")
            
            if enriched_data.get('organism'):
                org = enriched_data['organism'].split()[0] if ' ' in enriched_data['organism'] else enriched_data['organism']
                details.append(f"{org}")
            
            enriched_summary += f"  {' | '.join(details)}\n"
        
        return basic_network + enriched_summary
    
    def format_interactions_as_text(self, interactions):
        """
        Format just interactions as text
        """
        if not interactions:
            return "No interactions predicted."
        
        # Group interactions by type and use sets to avoid duplicates
        interactions_by_type = defaultdict(set)
        for interaction in interactions:
            # Skip self-interactions
            if interaction['protein_a'] == interaction['protein_b']:
                continue
                
            int_type = interaction.get('interaction_type', 'physical')
            p1, p2 = sorted([interaction['protein_a'], interaction['protein_b']])
            interactions_by_type[int_type].add(f"{p1}--{p2}")
        
        result = ""
        for int_type, edges in interactions_by_type.items():
            if edges:
                result += f"{int_type.upper()} INTERACTIONS:\n"
                for edge in sorted(edges):  # Sort the set for consistent output
                    result += f"  {edge}\n"
                result += "\n"
        
        return result.strip()
    
    def save_conversation_dataset(self, output_file="processed_dataset.json"):
        """
        Create and save the full conversation dataset with enriched protein data
        """
        start_time = time.time()
        
        # Load and process data
        print("Step 1: Loading and parsing data...")
        load_start = time.time()
        interactions, proteins = self.load_and_parse_biogrid()
        load_time = time.time() - load_start
        print(f"Data loading completed in {load_time:.2f} seconds")
        
        # Build neighborhoods
        print("Step 2: Building protein neighborhoods...")
        neighborhood_start = time.time()
        neighborhoods = self.build_network_neighborhoods(interactions, proteins)
        neighborhood_time = time.time() - neighborhood_start
        print(f"Built {len(neighborhoods)} protein neighborhoods in {neighborhood_time:.2f} seconds")
        
        # Enrich proteins with sequence and structural data
        print("Step 3: Enriching proteins with sequence and structural data...")
        enrichment_start = time.time()
        # Get unique proteins from neighborhoods
        unique_proteins = set()
        for neighborhood in neighborhoods:
            unique_proteins.update(neighborhood['proteins'])
        
        self.enrich_proteins_with_data(list(unique_proteins))
        enrichment_time = time.time() - enrichment_start
        print(f"Protein enrichment completed in {enrichment_time:.2f} seconds")
        
        # Create conversation examples
        print("Step 4: Creating conversation examples...")
        conversation_start = time.time()
        conversations = self.create_conversation_examples(neighborhoods)
        conversation_time = time.time() - conversation_start
        print(f"Created {len(conversations)} conversation examples in {conversation_time:.2f} seconds")
        
        # Shuffle the dataset
        print("Step 5: Shuffling and saving dataset...")
        random.shuffle(conversations)
        
        # Save dataset
        with open(output_file, 'w') as f:
            json.dump(conversations, f, indent=2)
        
        # Save enriched protein data separately for reference
        enriched_data_file = output_file.replace('.json', '_protein_data.json')
        with open(enriched_data_file, 'w') as f:
            json.dump(self.enriched_proteins, f, indent=2)
        
        total_time = time.time() - start_time
        print(f"Saved dataset to {output_file}")
        print(f"Saved enriched protein data to {enriched_data_file}")
        print(f"Total processing time: {total_time:.2f} seconds")
        
        # Show examples
        print("\n=== Example Conversations ===")
        for i, conv in enumerate(conversations[:2]):
            print(f"\n--- Example {i+1} ---")
            for msg in conv["updated"]:
                print(f"{msg['role'].upper()}: {msg['content'][:300]}...")
        
        return conversations

# Usage
if __name__ == "__main__":
    # Set random seed for reproducibility
    random.seed(42)
    np.random.seed(42)
    
    print(f"Configuration: Processing up to {MAX_PROTEINS_TO_PROCESS} proteins")
    print(f"Available CPU cores: {int(mp.cpu_count()/2)}")
    print(f"Cache directory: protein_cache/")
    
    creator = ProteinNetworkConversationDataset(
        "./unzipped/BIOGRID-ALL-4.4.246.tab3/BIOGRID-ALL-4.4.246.tab3.txt",
        cache_dir="protein_cache"
    )
    
    conversations = creator.save_conversation_dataset("processed_dataset.json")
    
    print(f"\n=== Dataset Summary ===")
    print(f"Total conversations: {len(conversations)}")
    
    # Count conversation types by system message content
    task_types = Counter()
    for conv in conversations:
        system_content = conv["updated"][0]["content"]
        if "list of proteins" in system_content:
            task_types["protein_list_to_network"] += 1
        elif "new protein" in system_content:
            task_types["new_protein_integration"] += 1
        elif "partial" in system_content:
            task_types["partial_completion"] += 1
        elif "properties" in system_content:
            task_types["property_based_generation"] += 1
    
    print("\nTask distribution:")
    for task, count in task_types.items():
        print(f"  {task}: {count}")
    
    # Print enrichment statistics
    print(f"\n=== Protein Enrichment Summary ===")
    total_proteins = len(creator.enriched_proteins)
    proteins_with_uniprot = sum(1 for data in creator.enriched_proteins.values() 
                               if data.get('uniprot_id') is not None)
    proteins_with_sequence = sum(1 for data in creator.enriched_proteins.values() 
                                if data.get('sequence') is not None)
    proteins_with_structure = sum(1 for data in creator.enriched_proteins.values() 
                                 if data.get('has_structure') == True)
    
    print(f"Total proteins processed: {total_proteins}")
    print(f"Proteins with UniProt data: {proteins_with_uniprot} ({proteins_with_uniprot/total_proteins*100:.1f}%)")
    print(f"Proteins with sequences: {proteins_with_sequence} ({proteins_with_sequence/total_proteins*100:.1f}%)")
    print(f"Proteins with AlphaFold structures: {proteins_with_structure} ({proteins_with_structure/total_proteins*100:.1f}%)")
    
    # Print cache statistics
    print(f"\n=== Cache Statistics ===")
    print(f"UniProt cache entries: {len(creator.enricher.uniprot_cache)}")
    print(f"AlphaFold cache entries: {len(creator.enricher.alphafold_cache)}")
    print(f"Cache files location: {creator.cache_dir}/")