-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathccd_sync.py
More file actions
2400 lines (2081 loc) · 119 KB
/
ccd_sync.py
File metadata and controls
2400 lines (2081 loc) · 119 KB
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
#!/usr/bin/env python3
"""
Script to compare mmCIF files from two sources:
- Set 1: HTTP at https://files.wwpdb.org/pub/pdb/data/monomers/components.cif.gz (downloaded and split)
- Set 2: GitHub at https://github.com/MonomerLibrary/monomers/tree/master/
Optional dependency: tqdm (for progress bars)
Install with: pip install tqdm
"""
import argparse
import csv
import os
import re
import sys
from collections import defaultdict
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Set, Tuple, Optional, Any
from urllib.parse import urljoin, urlparse
from urllib.request import urlopen, Request
import json
from multiprocessing import Pool, cpu_count
try:
from tqdm import tqdm
TQDM_AVAILABLE = True
except ImportError:
# Fallback if tqdm is not installed
TQDM_AVAILABLE = False
def tqdm(iterable, desc=None, total=None, unit=None, **kwargs):
if desc:
print(f"{desc}...")
return iterable
class mmCIFParser:
"""Parser for mmCIF files."""
def __init__(self, file_path: str = None, content: str = None):
"""Initialize parser with either a file path or content string.
Args:
file_path: Path to mmCIF file (if content is None)
content: mmCIF file content as string (if file_path is None)
"""
self.file_path = file_path
self.data = {}
self.loops = {}
self._parse(content)
def _parse(self, content: Optional[str] = None):
"""Parse the mmCIF file."""
if content is not None:
# Parse from content string
lines = content.splitlines(keepends=True)
else:
# Parse from file
with open(self.file_path, 'r', encoding='utf-8', errors='ignore') as f:
lines = f.readlines()
i = 0
in_multiline = False
multiline_key = None
multiline_value = []
while i < len(lines):
line = lines[i].rstrip('\n\r')
original_line = line
line = line.strip()
# Handle multi-line values (semicolon blocks)
if line.startswith(';') and not in_multiline:
# Start of multiline value
in_multiline = True
# Get the key from previous line
if i > 0:
prev_line = lines[i-1].strip()
match = re.match(r'^_(\S+)\s*$', prev_line)
if match:
multiline_key = match.group(1)
multiline_value = []
# Capture content after semicolon on the same line
if len(line) > 1:
content_after_semicolon = line[1:].strip()
if content_after_semicolon:
multiline_value.append(content_after_semicolon)
i += 1
continue
elif in_multiline:
if line == ';':
# End of multiline value
if multiline_key:
self.data[multiline_key] = '\n'.join(multiline_value)
in_multiline = False
multiline_key = None
multiline_value = []
else:
multiline_value.append(line)
i += 1
continue
if not line or line.startswith('#'):
i += 1
continue
# Parse single-value items (non-loop)
# Pattern: _key followed by whitespace and value
if line.startswith('_'):
# Split on whitespace, but keep the value together
parts = line.split(None, 1) # Split on whitespace, max 1 split
if len(parts) == 2:
key = parts[0]
value = parts[1].strip()
# Remove quotes if present
if value.startswith('"') and value.endswith('"'):
value = value[1:-1]
elif value.startswith("'") and value.endswith("'"):
value = value[1:-1]
# Handle '?' as empty
if value == '?':
value = ''
self.data[key] = value
i += 1
continue
# Parse loop_ blocks
if line == 'loop_':
i += 1
# Read headers
headers = []
while i < len(lines):
header_line = lines[i].strip()
if not header_line or header_line.startswith('#'):
i += 1
continue
if header_line.startswith('_'):
headers.append(header_line)
i += 1
else:
break
if not headers:
continue
# Read data rows
rows = []
while i < len(lines):
data_line = lines[i].strip()
if not data_line or data_line.startswith('#'):
i += 1
continue
if data_line == 'loop_' or (data_line.startswith('_') and ' ' not in data_line and '\t' not in data_line):
# Next loop or single item (header without value)
break
# Split the line - CIF format uses whitespace separation
# But we need to handle quoted values
values = self._split_cif_line(data_line)
if len(values) >= len(headers):
# Take only the number of values matching headers
rows.append(values[:len(headers)])
elif len(values) > 0:
# Partial row, pad with empty strings
while len(values) < len(headers):
values.append('')
rows.append(values)
i += 1
if rows:
# Store as list of dicts
loop_data = []
for row in rows:
row_dict = {}
for j, header in enumerate(headers):
value = row[j] if j < len(row) else ''
# Remove quotes
if value.startswith('"') and value.endswith('"'):
value = value[1:-1]
elif value.startswith("'") and value.endswith("'"):
value = value[1:-1]
row_dict[header] = value
loop_data.append(row_dict)
# Store under first header's category
category = headers[0].split('.')[0]
self.loops[category] = {
'headers': headers,
'data': loop_data
}
continue
i += 1
def _split_cif_line(self, line: str) -> List[str]:
"""Split a CIF line handling quoted values and multiple spaces."""
values = []
current = ''
in_quotes = False
quote_char = None
i = 0
while i < len(line):
char = line[i]
if char in ['"', "'"]:
if not in_quotes:
in_quotes = True
quote_char = char
current += char
elif char == quote_char:
in_quotes = False
quote_char = None
current += char
else:
current += char
elif char.isspace() and not in_quotes:
if current:
values.append(current)
current = ''
# Skip multiple spaces
while i + 1 < len(line) and line[i + 1].isspace():
i += 1
else:
current += char
i += 1
if current:
values.append(current)
return values
def get_value(self, key: str) -> Optional[str]:
"""Get a single value by key."""
return self.data.get(key)
def get_loop_data(self, category: str) -> List[Dict[str, str]]:
"""Get loop data for a category."""
# Try with and without underscore prefix
if category in self.loops:
return self.loops[category].get('data', [])
elif f'_{category}' in self.loops:
return self.loops[f'_{category}'].get('data', [])
return []
def get_loop_headers(self, category: str) -> List[str]:
"""Get loop headers for a category."""
# Try with and without underscore prefix
if category in self.loops:
return self.loops[category].get('headers', [])
elif f'_{category}' in self.loops:
return self.loops[f'_{category}'].get('headers', [])
return []
class FileDownloader:
"""Handle downloading files from HTTP/HTTPS and GitHub."""
@staticmethod
def download_and_split_components(show_progress: bool = True, output_dir: str = None) -> List[str]:
"""Download components.cif.gz, extract it, and split into individual CCD files.
Downloads the gzipped components file from wwpdb.org, extracts it, and splits it
into individual CCD files in the proper directory structure.
Args:
show_progress: Whether to show progress messages
output_dir: Directory where individual CCD files should be saved
Returns:
List of file paths (relative to output_dir) for each CCD file
"""
import gzip
import shutil
# URL for the gzipped components file
components_gz_url = "https://files.wwpdb.org/pub/pdb/data/monomers/components.cif.gz"
components_cif_name = "Components-rel-alt.cif"
if output_dir is None:
output_dir = "set1_files"
os.makedirs(output_dir, exist_ok=True)
# Paths for downloaded and extracted files
gz_path = os.path.join(output_dir, "components.cif.gz")
cif_path = os.path.join(output_dir, components_cif_name)
# Check if we already have split files (resume support)
# Need to recursively find all .cif files to check for existing ones
existing_files = set()
if os.path.exists(output_dir):
for root, dirs, files in os.walk(output_dir):
for f in files:
if f.endswith('.cif') and f != components_cif_name:
rel_path = os.path.relpath(os.path.join(root, f), output_dir)
# Normalize path separators for cross-platform compatibility
rel_path = rel_path.replace('\\', '/')
existing_files.add(rel_path)
# If we have a reasonable number of existing files, assume we're done
# (typical CCD count is ~30,000+)
if len(existing_files) > 1000:
if show_progress:
print(f"Found {len(existing_files)} existing CCD files. Skipping download.")
return sorted([f for f in existing_files])
if show_progress:
print("Downloading components.cif.gz from wwpdb.org...")
# Download the gzipped file (skip if already exists)
try:
skip_download = os.path.exists(gz_path) and os.path.exists(cif_path)
if not skip_download:
req = Request(components_gz_url)
req.add_header('User-Agent', 'Mozilla/5.0')
with urlopen(req, timeout=300) as response: # Large file, longer timeout
total_size = int(response.headers.get('Content-Length', 0))
if show_progress:
print(f" File size: {total_size / (1024*1024):.1f} MB")
with open(gz_path, 'wb') as f:
if show_progress and total_size > 0:
downloaded = 0
chunk_size = 8192
with tqdm(total=total_size, unit='B', unit_scale=True, desc="Downloading") as pbar:
while True:
chunk = response.read(chunk_size)
if not chunk:
break
f.write(chunk)
downloaded += len(chunk)
pbar.update(len(chunk))
else:
shutil.copyfileobj(response, f)
if show_progress:
print(" Download complete. Extracting...")
# Extract the gzipped file
with gzip.open(gz_path, 'rb') as f_in:
with open(cif_path, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
elif skip_download and show_progress:
print(" Using existing downloaded files.")
if not os.path.exists(cif_path):
if show_progress:
print(" Extracting...")
# Extract the gzipped file
with gzip.open(gz_path, 'rb') as f_in:
with open(cif_path, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
if show_progress:
print(" Extraction complete. Splitting into individual CCD files...")
if existing_files and show_progress:
print(f" Found {len(existing_files)} existing CCD files. Will only create missing ones...")
def get_file_path(code: str) -> str:
"""Get the file path based on code length.
For 3-char (or less): {last_char}/{first_two}/{code}.cif
For 5-char: {last_char}/{code}/{code}.cif
"""
code_len = len(code)
if code_len <= 3:
# 3-char or less: {last_char}/{first_two}/{code}.cif
last_char = code[-1] if code_len > 0 else '0'
first_two = code[:-1] if code_len > 1 else '00'
# Pad first_two to 2 characters if needed
if len(first_two) == 0:
first_two = '00'
elif len(first_two) == 1:
first_two = '0' + first_two
return f"{last_char}/{first_two}/{code}.cif"
elif code_len == 5:
# 5-char: {last_char}/{code}/{code}.cif
last_char = code[-1]
return f"{last_char}/{code}/{code}.cif"
else:
# Fallback for other lengths: just use the code
return f"{code}.cif"
# Parse and split the file
file_list = []
current_code = None
current_lines = []
files_to_create = []
with open(cif_path, 'r', encoding='utf-8', errors='ignore') as f:
for line_num, line in enumerate(f, 1):
# Check if this is a data_ line (start of a new CCD)
if line.startswith('data_'):
# Save previous CCD if we have one
if current_code is not None and current_lines:
file_path = get_file_path(current_code)
file_list.append(file_path)
# Only write if file doesn't exist (resume support)
if file_path not in existing_files:
files_to_create.append((file_path, current_lines))
elif show_progress and len(file_list) % 1000 == 0:
print(f" Processed {len(file_list)} CCDs (skipping existing)...", end='\r')
# Start new CCD
current_code = line.strip()[5:].strip() # Remove 'data_' prefix
current_lines = [line]
if show_progress and len(file_list) % 100 == 0 and len(file_list) < 1000:
print(f" Processed {len(file_list)} CCDs...", end='\r')
else:
# Continue current CCD
if current_code is not None:
current_lines.append(line)
# Don't forget the last CCD
if current_code is not None and current_lines:
file_path = get_file_path(current_code)
file_list.append(file_path)
# Only write if file doesn't exist (resume support)
if file_path not in existing_files:
files_to_create.append((file_path, current_lines))
# Write files that need to be created
if files_to_create:
if show_progress:
print(f"\n Creating {len(files_to_create)} new CCD files...")
for file_path, lines in tqdm(files_to_create, desc="Writing files", disable=not show_progress, unit="file"):
output_file = os.path.join(output_dir, file_path)
# Create directory if it doesn't exist
os.makedirs(os.path.dirname(output_file), exist_ok=True)
with open(output_file, 'w', encoding='utf-8') as out_f:
out_f.writelines(lines)
else:
if show_progress:
print(f"\n All {len(file_list)} CCD files already exist.")
if show_progress:
print(f"\n Split complete. Created {len(file_list)} individual CCD files.")
print(f" Cleaning up temporary files...")
# Clean up the large files (keep individual CCDs)
try:
os.remove(gz_path)
os.remove(cif_path)
except:
pass # Don't fail if cleanup doesn't work
return file_list
except Exception as e:
if show_progress:
print(f" Error: {e}")
return []
@staticmethod
def get_http_file_list_old(base_url: str, show_progress: bool = True) -> List[str]:
"""Get list of all .cif files from HTTP/HTTPS server by parsing directory listings.
Recursively scans directories to find all .cif files.
OLD METHOD - kept for reference but not used for Set 1 anymore.
"""
import html.parser
from html.parser import HTMLParser
import re
files = []
if show_progress:
print("Getting directory listing from HTTP server...")
print(f" URL: {base_url}")
class DirectoryListingParser(HTMLParser):
"""Parse HTML directory listings to find files and subdirectories."""
def __init__(self):
super().__init__()
self.items = [] # Both files and directories
def handle_starttag(self, tag, attrs):
if tag == 'a':
for attr_name, attr_value in attrs:
if attr_name == 'href' and attr_value:
href = attr_value
# Skip parent directory links and root
if href in ['../', '..', '/', './', '']:
continue
# Remove query strings and fragments
if '?' in href:
href = href.split('?')[0]
if '#' in href:
href = href.split('#')[0]
# Remove leading slash if present
if href.startswith('/'):
href = href[1:]
# Remove trailing slash (we'll determine if it's a directory later)
if href.endswith('/'):
href = href.rstrip('/')
# Skip if empty after processing
if not href:
continue
# Add to items list (both files and directories)
if href not in self.items: # Avoid duplicates
self.items.append(href)
def get_directory_listing(url: str, is_root: bool = False) -> Tuple[List[str], List[str]]:
"""Try to get directory listing from a URL.
Args:
url: URL to get directory listing from
is_root: True if this is the root directory (for debug output)
Returns:
Tuple of (directories, files)
"""
directories = []
file_list = []
try:
req = Request(url)
req.add_header('User-Agent', 'Mozilla/5.0')
with urlopen(req, timeout=10) as response:
if response.getcode() == 200:
content = response.read().decode('utf-8', errors='ignore')
# Debug: print first 500 chars to see what we're getting
if show_progress and is_root:
print(f" Debug: Response length: {len(content)} chars")
print(f" Debug: First 500 chars: {content[:500]}")
# Check if this looks like a directory listing
# Try multiple patterns - some servers use different HTML structures
if '<a href' in content.lower() or '<A HREF' in content or '<a ' in content.lower() or 'href=' in content.lower():
parser = DirectoryListingParser()
try:
parser.feed(content)
except Exception as parse_error:
if show_progress and is_root:
print(f" Debug: HTML parsing error: {parse_error}")
if show_progress and is_root:
print(f" Debug: Parser found {len(parser.items)} items: {parser.items[:10] if parser.items else 'none'}")
# Determine which are directories vs files
for item in parser.items:
# Check if it's a .cif file
if item.endswith('.cif'):
file_list.append(item)
# Everything else that doesn't look like a file is a directory
# Common file extensions to exclude
elif not any(item.endswith(ext) for ext in ['.html', '.txt', '.xml', '.json', '.pdf', '.zip', '.gz', '.tar', '.md', '.readme', '.cif']):
# Assume it's a directory - try to scan it recursively
directories.append(item)
# Also: items with no extension are likely directories
elif '.' not in item:
if item not in directories: # Avoid duplicates
directories.append(item)
except Exception as e:
if show_progress and is_root:
print(f" Debug: Error getting directory listing: {e}")
return directories, file_list
def test_directory_exists(dir_url: str) -> bool:
"""Test if a directory exists by trying to access it or a test file."""
try:
# Try accessing the directory URL
req = Request(dir_url)
req.add_header('User-Agent', 'Mozilla/5.0')
with urlopen(req, timeout=5) as response:
# If we get a response (even 403/404 might mean it exists, just no listing)
# Try a different approach: test if we can access a common file pattern
return True
except:
return False
def test_file_exists(file_url: str) -> bool:
"""Test if a file exists by trying to access it."""
try:
req = Request(file_url)
req.add_header('User-Agent', 'Mozilla/5.0')
with urlopen(req, timeout=2) as response:
return response.getcode() == 200
except:
return False
def scan_directory_recursive(current_path: str, depth: int = 0, max_depth: int = 5) -> List[str]:
"""Recursively scan directories to find .cif files.
Since directory listings return 403/404, we use the known file structure
to test if directories exist by checking for files in them.
"""
found_files = []
if depth > max_depth:
return found_files
if show_progress:
if depth == 0:
print(f" Scanning directories using known structure (no directory listings available)...")
elif depth <= 2:
print(f" Scanning {current_path}...")
# Try to get directory listing first (in case it works sometimes)
dir_url = base_url.rstrip('/') + '/' + current_path if current_path else base_url.rstrip('/')
if not dir_url.endswith('/'):
dir_url += '/'
directories, files_in_dir = get_directory_listing(dir_url, is_root=(depth == 0))
# Add .cif files found via directory listing
for file_name in files_in_dir:
file_path = f"{current_path}/{file_name}" if current_path else file_name
found_files.append(file_path)
if show_progress and len(found_files) % 100 == 0:
print(f" Found {len(found_files)} .cif files so far...", end='\r')
# If directory listing worked, use it
if directories:
for directory in directories:
sub_path = f"{current_path}/{directory}" if current_path else directory
sub_files = scan_directory_recursive(sub_path, depth + 1, max_depth)
found_files.extend(sub_files)
return found_files
# Directory listing not available - use known structure patterns
# For root level (depth 0): try directories 0-9, a-z, A-Z (last character)
if depth == 0:
# Check if this is EBI (flat structure) - test a few known files
test_codes = ['001', '000', '002', 'A1A15']
ebi_files_found = 0
for test_code in test_codes:
test_url = base_url.rstrip('/') + '/' + f"{test_code}.cif"
if test_file_exists(test_url):
ebi_files_found += 1
if ebi_files_found > 0:
# This is EBI flat structure - scan all possible codes
if show_progress:
print(" Detected EBI flat structure - scanning all possible codes...")
# For EBI: just {code}.cif in root
# Try 3-char codes: 000-999, AAA-ZZZ
char_set = [str(i) for i in range(10)] + [chr(i) for i in range(ord('a'), ord('z')+1)] + [chr(i) for i in range(ord('A'), ord('Z')+1)]
for char1 in tqdm(char_set, desc="3-char codes", disable=not show_progress, unit="code"):
for char2 in char_set:
for char3 in char_set:
code = char1 + char2 + char3
test_url = base_url.rstrip('/') + '/' + f"{code}.cif"
if test_file_exists(test_url):
found_files.append(f"{code}.cif")
if show_progress and len(found_files) % 100 == 0:
print(f" Found {len(found_files)} .cif files so far...", end='\r')
# Try 5-char codes
for char1 in tqdm(char_set, desc="5-char codes", disable=not show_progress, unit="code"):
for char2 in char_set:
for char3 in char_set:
for char4 in char_set:
for char5 in char_set:
code = char1 + char2 + char3 + char4 + char5
test_url = base_url.rstrip('/') + '/' + f"{code}.cif"
if test_file_exists(test_url):
found_files.append(f"{code}.cif")
if show_progress and len(found_files) % 100 == 0:
print(f" Found {len(found_files)} .cif files so far...", end='\r')
return found_files
# This is wwpdb nested structure
if show_progress:
print(" Detected wwpdb nested structure - scanning directories...")
char_set = [str(i) for i in range(10)] + [chr(i) for i in range(ord('a'), ord('z')+1)] + [chr(i) for i in range(ord('A'), ord('Z')+1)]
for last_char in tqdm(char_set, desc="Scanning top-level dirs", disable=not show_progress, unit="dir"):
# Test if this directory exists by trying multiple sample files
# Try different patterns: 000, 001, 00A, etc.
test_patterns = [
f"{last_char}/00/00{last_char}.cif", # 000, 001, etc. (code = first_two + last_char)
f"{last_char}/01/01{last_char}.cif", # 010, 011, etc.
f"{last_char}/10/10{last_char}.cif", # 100, 101, etc.
f"{last_char}/A0/A0{last_char}.cif", # A05 (user's example: 5/A0/A05.cif)
f"{last_char}/0A/0A{last_char}.cif", # 0A0, 0A1, etc.
]
dir_exists = False
for test_file in test_patterns:
test_url = base_url.rstrip('/') + '/' + test_file
if test_file_exists(test_url):
dir_exists = True
break
if dir_exists:
# Directory exists, scan it
sub_files = scan_directory_recursive(last_char, depth + 1, max_depth)
found_files.extend(sub_files)
# For depth 1: we're in a directory like "5" (last character)
# Try subdirectories: first_two_chars for 3-char codes
elif depth == 1:
last_char = current_path
char_set = [str(i) for i in range(10)] + [chr(i) for i in range(ord('a'), ord('z')+1)] + [chr(i) for i in range(ord('A'), ord('Z')+1)]
for char1 in char_set:
for char2 in char_set:
first_two = char1 + char2
# Test if subdirectory exists by checking for a file
# Pattern: {last_char}/{first_two}/{code}.cif where code = first_two + last_char
code = first_two + last_char
test_file = f"{last_char}/{first_two}/{code}.cif"
test_url = base_url.rstrip('/') + '/' + test_file
if test_file_exists(test_url):
# Subdirectory exists, scan it for all files
sub_path = f"{last_char}/{first_two}"
sub_files = scan_directory_recursive(sub_path, depth + 1, max_depth)
found_files.extend(sub_files)
# Also check for 5-char codes: {last_char}/{code}/{code}.cif
# This requires trying many combinations, but let's do it more efficiently
# by testing if the directory exists first
for char1 in char_set:
for char2 in char_set:
for char3 in char_set:
for char4 in char_set:
code = char1 + char2 + char3 + char4 + last_char
test_file = f"{last_char}/{code}/{code}.cif"
test_url = base_url.rstrip('/') + '/' + test_file
if test_file_exists(test_url):
# Found a 5-char code directory
file_path = f"{last_char}/{code}/{code}.cif"
found_files.append(file_path)
if show_progress and len(found_files) % 100 == 0:
print(f" Found {len(found_files)} .cif files so far...", end='\r')
# For depth 2: we're in a directory like "5/A05" (last_char/first_two)
# Files should be: {last_char}/{first_two}/{code}.cif where code = first_two + last_char
elif depth == 2:
parts = current_path.split('/')
if len(parts) == 2:
last_char, first_two = parts
code = first_two + last_char
file_path = f"{last_char}/{first_two}/{code}.cif"
test_url = base_url.rstrip('/') + '/' + file_path
if test_file_exists(test_url):
found_files.append(file_path)
if show_progress and len(found_files) % 100 == 0:
print(f" Found {len(found_files)} .cif files so far...", end='\r')
return found_files
# Start recursive scanning
files = scan_directory_recursive('', max_depth=5)
if show_progress:
print(f"\nScanning complete. Found {len(files)} .cif files.")
return files
@staticmethod
def download_http_file(base_url: str, file_path: str, local_path: str, skip_existing: bool = True):
"""Download a file from HTTP/HTTPS, preserving directory structure.
Args:
base_url: Base URL for the file
file_path: Relative path to the file
local_path: Local path where file should be saved
skip_existing: If True, skip download if file already exists (resume support)
"""
# Skip if file already exists (resume support)
if skip_existing and os.path.exists(local_path):
return
# Construct full URL
full_url = base_url.rstrip('/') + '/' + file_path
try:
# Create local directory structure
os.makedirs(os.path.dirname(local_path), exist_ok=True)
req = Request(full_url)
req.add_header('User-Agent', 'Mozilla/5.0')
with urlopen(req, timeout=30) as response:
if response.getcode() == 200:
with open(local_path, 'wb') as f:
f.write(response.read())
else:
print(f"Error downloading {file_path}: HTTP {response.getcode()}")
except Exception as e:
print(f"Error downloading {file_path}: {e}")
@staticmethod
def get_github_file_list(repo_url: str, show_progress: bool = True, github_token: Optional[str] = None) -> List[str]:
"""Get list of all .cif files from GitHub using API.
Args:
repo_url: GitHub repository URL
show_progress: Whether to show progress messages
github_token: Optional GitHub personal access token for higher rate limits
"""
# Convert GitHub web URL to API URL
# https://github.com/MonomerLibrary/monomers/tree/master/
# -> https://api.github.com/repos/MonomerLibrary/monomers/contents/
api_url = repo_url.replace('https://github.com/', 'https://api.github.com/repos/')
api_url = api_url.replace('/tree/master/', '/contents/')
if not api_url.endswith('/'):
api_url += '/'
files = []
dirs_processed = 0
def get_files_recursive(url: str):
"""Recursively get files from GitHub API."""
nonlocal dirs_processed
try:
req = Request(url)
req.add_header('Accept', 'application/vnd.github.v3+json')
req.add_header('User-Agent', 'Mozilla/5.0')
if github_token:
req.add_header('Authorization', f'token {github_token}')
with urlopen(req, timeout=30) as response:
if response.getcode() == 403:
error_msg = response.read().decode('utf-8')
if show_progress:
print(f"\nError accessing {url}: HTTP Error 403: rate limit exceeded")
if not github_token:
print("Tip: Use --github-token to increase rate limits. Get a token at https://github.com/settings/tokens")
return
items = json.loads(response.read().decode('utf-8'))
if not isinstance(items, list):
return
for item in items:
if item.get('type') == 'file' and item.get('name', '').endswith('.cif'):
files.append(item['path'])
if show_progress and len(files) % 100 == 0:
print(f" Found {len(files)} .cif files so far...", end='\r')
elif item.get('type') == 'dir':
dirs_processed += 1
if show_progress and dirs_processed % 10 == 0:
print(f" Scanning directories... Found {len(files)} .cif files so far...", end='\r')
get_files_recursive(item['url'])
except Exception as e:
error_str = str(e).lower()
if '403' in error_str or 'rate limit' in error_str:
if show_progress:
print(f"\nError accessing {url}: HTTP Error 403: rate limit exceeded")
if not github_token:
print("Tip: Use --github-token to increase rate limits. Get a token at https://github.com/settings/tokens")
elif show_progress:
print(f"\nError accessing {url}: {e}")
if show_progress:
print("Connecting to GitHub API...")
get_files_recursive(api_url)
if show_progress:
print(f"\nScanning complete. Found {len(files)} .cif files.")
return files
@staticmethod
def download_github_file(repo_url: str, file_path: str, local_path: str, skip_existing: bool = True):
"""Download a file from GitHub, preserving directory structure.
Args:
repo_url: GitHub repository URL
file_path: Relative path to the file in the repo
local_path: Local path where file should be saved
skip_existing: If True, skip download if file already exists (resume support)
"""
# Skip if file already exists (resume support)
if skip_existing and os.path.exists(local_path):
return
# Convert to raw content URL
raw_url = repo_url.replace('https://github.com/', 'https://raw.githubusercontent.com/')
raw_url = raw_url.replace('/tree/master/', '/master/')
if not raw_url.endswith('/'):
raw_url += '/'
raw_url += file_path
try:
with urlopen(raw_url, timeout=30) as response:
if response.getcode() == 200:
os.makedirs(os.path.dirname(local_path), exist_ok=True)
with open(local_path, 'wb') as f:
f.write(response.read())
else:
print(f"Error downloading {raw_url}: HTTP {response.getcode()}")
except Exception as e:
print(f"Error downloading {file_path}: {e}")
@staticmethod
def get_http_file_content(base_url: str, file_path: str) -> Optional[str]:
"""Get file content from HTTP/HTTPS without saving to disk."""
try:
file_url = base_url.rstrip('/') + '/' + file_path
req = Request(file_url)
req.add_header('User-Agent', 'Mozilla/5.0')
with urlopen(req, timeout=30) as response:
if response.getcode() == 200:
return response.read().decode('utf-8', errors='ignore')
else:
return None
except Exception as e:
return None
@staticmethod
def get_github_file_content(repo_url: str, file_path: str) -> Optional[str]:
"""Get file content from GitHub without saving to disk."""
# Convert to raw content URL
raw_url = repo_url.replace('https://github.com/', 'https://raw.githubusercontent.com/')
raw_url = raw_url.replace('/tree/master/', '/master/')
if not raw_url.endswith('/'):
raw_url += '/'
raw_url += file_path
try:
req = Request(raw_url)
req.add_header('User-Agent', 'Mozilla/5.0')
with urlopen(req, timeout=30) as response:
if response.getcode() == 200:
return response.read().decode('utf-8', errors='ignore')
else:
return None
except Exception as e:
return None
class ComparisonEngine:
"""Engine for comparing mmCIF files."""
def __init__(self, correlation_table_path: str):
self.correlations = self._load_correlation_table(correlation_table_path)
def _load_correlation_table(self, csv_path: str) -> List[Tuple[List[str], List[str], bool]]:
"""Load correlation table from CSV.
Returns list of tuples: (set1_items, set2_items, same_name)
"""
correlations = []
with open(csv_path, 'r') as f:
reader = csv.DictReader(f)
for row in reader:
set1_item = row['wwpdbccd'].strip()
set2_item = row['ccp4monomerlibrary'].strip()
same_name = row.get('same_name', 'N').strip().upper() == 'Y'
if set1_item and set2_item:
correlations.append(([set1_item], [set2_item], same_name))
return correlations
def _group_correlations_by_category(self, correlations: List[Tuple[List[str], List[str], bool]]) -> Dict[str, List[Tuple[List[str], List[str], bool]]]:
"""Group correlations by category for grouped comparisons."""
grouped = defaultdict(list)
for set1_items, set2_items, same_name in correlations:
# Get category from first item
category = set1_items[0].split('.')[0]
grouped[category].append((set1_items, set2_items, same_name))
return grouped
def _normalize_value(self, value: str) -> str:
"""Normalize a value for comparison."""
if value is None:
return ''
value = str(value).strip()
# Remove quotes
if value.startswith('"') and value.endswith('"'):
value = value[1:-1]
elif value.startswith("'") and value.endswith("'"):
value = value[1:-1]
# Remove newlines (they're formatting artifacts, not actual content)
# This handles multi-line values where newlines split words
value = value.replace('\r\n', '').replace('\n', '').replace('\r', '')
# Convert to lowercase
value = value.lower()
return value
def _normalize_bond_order(self, value: str) -> str:
"""Normalize bond order values (SING/DOUB vs SINGLE/DOUBLE)."""
value = self._normalize_value(value)
if value == 'sing':
return 'single'
elif value == 'doub':
return 'double'
return value
def _get_item_value(self, parser: mmCIFParser, item_path: str) -> Optional[str]:
"""Get value for an item path like '_chem_comp.name' or from loop data."""
# Check single values first (with underscore)
value = parser.get_value(item_path)
if value is not None and value != '':
return value
# Try without leading underscore (for multi-line values stored without underscore)
item_path_no_underscore = item_path.lstrip('_')
if item_path_no_underscore != item_path:
value = parser.get_value(item_path_no_underscore)
if value is not None and value != '':
return value
# Check loop data - try with and without underscore prefix
category = item_path.split('.')[0]