colbyago1 commited on
Commit
bb8455b
·
verified ·
1 Parent(s): ba24379

Upload 4 files

Browse files
src/add_nr_column.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import csv
3
+
4
+ summary_file = "sabdab_summary_all_with_paths.tsv"
5
+ nr_file = "all_nr.tsv"
6
+ output_file = "sabdab_summary_with_nr_flag.tsv"
7
+
8
+ # Read all pdb IDs from the non-redundant set
9
+ nr_pdbs = set()
10
+ with open(nr_file, newline="") as f:
11
+ reader = csv.DictReader(f, delimiter="\t")
12
+ for row in reader:
13
+ nr_pdbs.add(row["pdb"].strip().lower())
14
+
15
+ # Process the summary file and add the new column
16
+ with open(summary_file, newline="") as infile, open(output_file, "w", newline="") as outfile:
17
+ reader = csv.DictReader(infile, delimiter="\t")
18
+ fieldnames = reader.fieldnames + ["in_nr_set"]
19
+
20
+ writer = csv.DictWriter(outfile, fieldnames=fieldnames, delimiter="\t")
21
+ writer.writeheader()
22
+
23
+ for row in reader:
24
+ pdb = row["pdb"].strip().lower()
25
+ row["in_nr_set"] = str(pdb in nr_pdbs)
26
+ writer.writerow(row)
27
+
28
+ print(f"Output written to {output_file}")
src/add_paths_to_tsv.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ from pathlib import Path
3
+ import re
4
+
5
+ # Input
6
+ tsv_path = "sabdab_summary_all_sorted.tsv"
7
+ base_dir = Path("sabdab_dataset")
8
+
9
+ df = pd.read_csv(tsv_path, sep="\t")
10
+
11
+
12
+ def find_file(directory, pattern):
13
+ if not directory.exists():
14
+ return None
15
+
16
+ regex = re.compile(pattern, re.IGNORECASE)
17
+
18
+ for f in directory.iterdir():
19
+ if f.is_file() and regex.fullmatch(f.name):
20
+ # return actual existing path relative to sabdab_dataset
21
+ return str(f.relative_to(base_dir.parent))
22
+
23
+ return None
24
+
25
+
26
+ def get_paths(row):
27
+ pdb = str(row["pdb"])
28
+ H = str(row["Hchain"])
29
+ L = str(row["Lchain"])
30
+
31
+ pdb_dir = base_dir / pdb.lower()
32
+
33
+ return pd.Series({
34
+ "abangle": find_file(
35
+ pdb_dir / "abangle",
36
+ rf"{pdb}\.abangle"
37
+ ),
38
+
39
+ "annotation_H": find_file(
40
+ pdb_dir / "annotation",
41
+ rf"{pdb}_{H}_VH\.ann"
42
+ ),
43
+
44
+ "annotation_L": find_file(
45
+ pdb_dir / "annotation",
46
+ rf"{pdb}_{L}_VL\.ann"
47
+ ),
48
+
49
+ "imgt_H": find_file(
50
+ pdb_dir / "imgt",
51
+ rf"{pdb}_{H}_H\.ann"
52
+ ),
53
+
54
+ "imgt_L": find_file(
55
+ pdb_dir / "imgt",
56
+ rf"{pdb}_{L}_L\.ann"
57
+ ),
58
+
59
+ "sequence_raw": find_file(
60
+ pdb_dir / "sequence",
61
+ rf"{pdb}_raw\.pdb"
62
+ ),
63
+
64
+ "sequence_H": find_file(
65
+ pdb_dir / "sequence",
66
+ rf"{pdb}_{H}_VH\.fa"
67
+ ),
68
+
69
+ "sequence_L": find_file(
70
+ pdb_dir / "sequence",
71
+ rf"{pdb}_{L}_VL\.fa"
72
+ ),
73
+
74
+ "structure": find_file(
75
+ pdb_dir / "structure",
76
+ rf"{pdb}\.pdb"
77
+ ),
78
+
79
+ "structure_chothia": find_file(
80
+ pdb_dir / "structure" / "chothia",
81
+ rf"{pdb}\.pdb"
82
+ ),
83
+ })
84
+
85
+
86
+ # Apply row-wise
87
+ new_cols = df.apply(get_paths, axis=1)
88
+
89
+ df = pd.concat([df, new_cols], axis=1)
90
+
91
+ df.to_csv("sabdab_summary_all_with_paths.tsv", sep="\t", index=False)
src/multivariate_stratification.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+
4
+ # Load the data
5
+ df = pd.read_csv("~/Desktop/sabdab_summary_with_flags.tsv", sep="\t")
6
+
7
+ # Create the strata column
8
+ strata_cols = ["antigen_type", "heavy_species", "method", "scfv",
9
+ "engineered", "light_ctype", "in_nr_set", "curated_quality_dataset"]
10
+ df["strata"] = df[strata_cols].astype(str).agg("_".join, axis=1)
11
+
12
+ # Initialize split column
13
+ df["split"] = ""
14
+
15
+ # Define fractions
16
+ train_frac = 0.8
17
+ val_frac = 0.1
18
+ test_frac = 0.1
19
+
20
+ # Set random seed for reproducibility
21
+ np.random.seed(42)
22
+
23
+ # Get all unique strata
24
+ all_strata = df["strata"].unique()
25
+
26
+ for s in all_strata:
27
+ idx = df[df["strata"] == s].index.to_list()
28
+ np.random.shuffle(idx)
29
+ n = len(idx)
30
+ n_train = max(1, int(n * train_frac))
31
+ n_val = max(1, int(n * val_frac))
32
+ n_test = n - n_train - n_val # whatever remains
33
+
34
+ # Adjust in case rounding caused n_test < 1
35
+ if n_test < 1:
36
+ n_test = 1
37
+ if n_val > 1:
38
+ n_val -= 1
39
+ else:
40
+ n_train -= 1
41
+
42
+ # Assign
43
+ df.loc[idx[:n_train], "split"] = "train"
44
+ df.loc[idx[n_train:n_train+n_val], "split"] = "validation"
45
+ df.loc[idx[n_train+n_val:], "split"] = "test"
46
+
47
+ # Drop temporary strata column
48
+ df.drop(columns=["strata"], inplace=True)
49
+
50
+ # Check counts
51
+ print(df["split"].value_counts(normalize=True) * 100)
52
+
53
+ cols = ["antigen_type", "heavy_species", "method", "scfv",
54
+ "engineered", "light_ctype", "in_nr_set", "curated_quality_dataset"]
55
+
56
+ for col in cols:
57
+ print(f"\n=== {col} ===")
58
+ # Cross-tab of counts by split
59
+ ct = pd.crosstab(df[col], df["split"])
60
+ # Convert counts to percentages **row-wise** so each category sums to 100%
61
+ ct_percent = ct.div(ct.sum(axis=1), axis=0) * 100
62
+ print(ct_percent.round(1))
63
+
64
+ # Save to TSV
65
+ df.to_csv("~/Desktop/sabdab_summary_with_splits.tsv", sep="\t", index=False)
66
+ print("Saved updated DataFrame with split column to ~/Desktop/sabdab_summary_with_splits.tsv")
src/sabdab_downloader_fixed.py ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ description='''
2
+
3
+
4
+ SAbDab Download Script \\\ //
5
+ The OPIG Antibody Database \\\ //
6
+ Authors: James Dunbar and Konrad Krawczyk 2013. ||
7
+ Contributors: Jinwoo Leem ||
8
+ Supervisor: Charlotte Deane
9
+
10
+ Contact: opig@stats.ox.ac.uk
11
+
12
+ In collaboration with:
13
+ UCB: Jiye Shi, Terry Baker.
14
+ Roche: Angelika Fuchs, Guy Georges.
15
+
16
+
17
+ o This is a script that allows a user to download data from SAbDab.
18
+ o It requires a csv summary file downloaded from the website (opig.stats.ox.ac.uk/webapps/sabdab)
19
+
20
+ o This file should contain AT LEAST:
21
+
22
+ 1. A header line with tab-separated fields as "pdb Hchain Lchain model"
23
+ 2. The pdb identifier, heavy chain, light chain and model id on new lines e.g.
24
+
25
+ pdb Hchain Lchain model
26
+ 12e8 H L 0
27
+ 12e8 P M 0
28
+ 1ahw B A 0
29
+ 1ahw E D 0
30
+ . . . .
31
+ . . . .
32
+ . . . .
33
+
34
+ o Other fields will be ignored but may be included in the file.
35
+
36
+ o The user must provide a directory in which the data should be downloaded to.
37
+ o The type of data that should be downloaded should be specified using the command-line options.
38
+
39
+ o Example useage:
40
+ To run on a linux command line type:
41
+
42
+ python sabdab_downloader.py -s summary_file.csv -o path/to/output/ --original_pdb
43
+
44
+ This will create a directory in "path/to/output/" name sabdab_dataset.
45
+ It will contain a directory for each unique pdb code in the summary_file.csv .
46
+ The structure for each of these pdbs will be downloaded there.
47
+ '''
48
+
49
+ epilogue="""
50
+ Copyright (C) 2013 James Dunbar
51
+ """
52
+
53
+
54
+ import argparse, sys, os, urllib.request
55
+
56
+ def getpdb(pdb_entry, out_path):
57
+ """
58
+ Get the PDB file from sabdab.
59
+ Check that it has successfully downloaded.
60
+ """
61
+ out_file = os.path.join( out_path, "%s.pdb"%pdb_entry)
62
+ try:
63
+ urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/structure/%s.pdb"%(pdb_entry,pdb_entry), out_file)
64
+ except Exception as e:
65
+ print("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/structure/%s.pdb failed"%(pdb_entry,pdb_entry))
66
+ return False
67
+ if os.path.isfile(out_file):
68
+ Retrieved = open(out_file).read()
69
+ if not Retrieved.count("ATOM"):
70
+ print("Failed to retrieve PDB file from SAbDab")
71
+ os.remove(out_file)
72
+ return False
73
+ else:
74
+ return True
75
+ else:
76
+ return False
77
+
78
+ def getchothpdb(pdb_entry, out_path):
79
+ """
80
+ Get the chothia PDB file from sabdab.
81
+ Check that it has successfully downloaded.
82
+ """
83
+ out_file = os.path.join( out_path, "%s.pdb"%pdb_entry)
84
+ try:
85
+ urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/structure/chothia/%s.pdb"%(pdb_entry,pdb_entry), out_file)
86
+ except Exception as e:
87
+ print("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/structure/chothia/%s.pdb failed"%(pdb_entry,pdb_entry))
88
+ return False
89
+ if os.path.isfile(out_file):
90
+ Retrieved = open(out_file).read()
91
+ if not Retrieved.count("ATOM"):
92
+ print("Failed to retrieve PDB file from SAbDab")
93
+ os.remove(out_file)
94
+ return False
95
+ else:
96
+ return True
97
+ else:
98
+ return False
99
+
100
+ def getsequence(entry, fab_list, out_path):
101
+ """
102
+ Get the sequence files
103
+ Check that they successfully download
104
+ Put them into the directory
105
+ """
106
+
107
+ out_file = os.path.join( out_path, "%s_raw.pdb"%entry)
108
+ try:
109
+ urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/sequences/%s_raw.fa"%(entry,entry), out_file)
110
+ except Exception as e:
111
+ print("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/sequences/%s_raw.fa failed"%(entry,entry))
112
+ return False
113
+ if os.path.isfile(out_file):
114
+ Retrieved = open(out_file).read()
115
+ if not Retrieved.count(">%s"%entry):
116
+ print("Failed to retrieve sequence file from SAbDab.")
117
+ os.remove(out_file)
118
+ return False
119
+ else:
120
+ return False
121
+
122
+ for fab in fab_list:
123
+ Hchain = fab[1].upper()
124
+ if Hchain!="NA":
125
+ out_file = os.path.join( out_path, "%s_%s_VH.fa"%(entry,Hchain) )
126
+ try:
127
+ urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/sequences/%s_%s_VH.fa"%(entry,entry,Hchain), out_file)
128
+ except Exception as e:
129
+ Hchain = Hchain.lower()
130
+ out_file = os.path.join( out_path, "%s_%s_VH.fa"%(entry,Hchain) )
131
+ try:
132
+ urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/sequences/%s_%s_VH.fa"%(entry,entry,Hchain), out_file)
133
+ except Exception as e:
134
+ print("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/sequences/%s_%s_VH.fa failed"%(entry,entry,Hchain))
135
+ return False
136
+ if os.path.isfile(out_file):
137
+ Retrieved = open(out_file).read()
138
+ if not Retrieved.count(">%s"%entry):
139
+ print("Failed to retrieve sequence file from SAbDab.")
140
+ os.remove(out_file)
141
+ return False
142
+ else:
143
+ return False
144
+
145
+ Lchain = fab[2].upper()
146
+ if Lchain!="NA":
147
+ out_file = os.path.join( out_path, "%s_%s_VL.fa"%(entry,Lchain) )
148
+ try:
149
+ urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/sequences/%s_%s_VL.fa"%(entry,entry,Lchain), out_file)
150
+ except Exception as e:
151
+ Lchain = Lchain.lower()
152
+ out_file = os.path.join( out_path, "%s_%s_VL.fa"%(entry,Lchain) )
153
+ try:
154
+ urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/sequences/%s_%s_VL.fa"%(entry,entry,Lchain), out_file)
155
+ except Exception as e:
156
+ print("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/sequences/%s_%s_VL.fa failed"%(entry,entry,Lchain))
157
+ return False
158
+ if os.path.isfile(out_file):
159
+ Retrieved = open(out_file).read()
160
+ if not Retrieved.count(">%s"%entry):
161
+ print("Failed to retrieve sequence file from SAbDab.")
162
+ os.remove(out_file)
163
+ return False
164
+ else:
165
+ return False
166
+
167
+ return True
168
+
169
+ def getannotation(entry, fab_list, out_path):
170
+ """
171
+ Get the annotation files for the antibody sequences.
172
+ These are for the variable region of the sequences only.
173
+ """
174
+ for fab in fab_list:
175
+ Hchain = fab[1].upper()
176
+ if Hchain!="NA":
177
+ out_file = os.path.join( out_path, "%s_%s_VH.ann"%(entry,Hchain) )
178
+ try:
179
+ urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/annotation/%s_%s_VH.ann"%(entry,entry,Hchain), out_file)
180
+ except Exception as e:
181
+ Hchain = Hchain.lower()
182
+ out_file = os.path.join( out_path, "%s_%s_VH.ann"%(entry,Hchain) )
183
+ try:
184
+ urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/annotation/%s_%s_VH.ann"%(entry,entry,Hchain), out_file)
185
+ except Exception as e:
186
+ print("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/annotation/%s_%s_VH.ann failed"%(entry,entry,Hchain))
187
+ return False
188
+ if os.path.isfile(out_file):
189
+ Retrieved = open(out_file).read()
190
+ if not Retrieved.count("H3"):
191
+ print("Failed to retrieve annotation file from SAbDab.")
192
+ os.remove(out_file)
193
+ return False
194
+ else:
195
+ return False
196
+
197
+ Lchain = fab[2].upper()
198
+ if Lchain!="NA":
199
+ out_file = os.path.join( out_path, "%s_%s_VL.ann"%(entry,Lchain) )
200
+ try:
201
+ urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/annotation/%s_%s_VL.ann"%(entry,entry,Lchain), out_file)
202
+ except Exception as e:
203
+ Lchain = Lchain.lower()
204
+ out_file = os.path.join( out_path, "%s_%s_VL.ann"%(entry,Lchain) )
205
+ try:
206
+ urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/annotation/%s_%s_VL.ann"%(entry,entry,Lchain), out_file)
207
+ except Exception as e:
208
+ print("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/annotation/%s_%s_VL.ann failed"%(entry,entry,Lchain))
209
+ return False
210
+ if os.path.isfile(out_file):
211
+ Retrieved = open(out_file).read()
212
+ if not Retrieved.count("L3"):
213
+ print("Failed to retrieve annotation file from SAbDab.")
214
+ os.remove(out_file)
215
+ return False
216
+ else:
217
+ return False
218
+ return True
219
+
220
+ def getabangle(entry, fab_list, out_path):
221
+ """
222
+ Get the orientation angles for any of the fabs in the pdb.
223
+ A non-paired antibody chain e.g VHH will have NA as the other chain identifier.
224
+ """
225
+ for fab in fab_list:
226
+ if "NA" in fab:
227
+ continue
228
+ else:
229
+ out_file = os.path.join( out_path, "%s.abangle"%(entry) )
230
+ try:
231
+ urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/abangle/%s.abangle"%(entry,entry), out_file)
232
+ except Exception as e:
233
+ print("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/abangle/%s.abangle failed"%(entry,entry))
234
+ return False
235
+ if os.path.isfile(out_file):
236
+ Retrieved = open(out_file).read()
237
+ if not Retrieved.count(entry):
238
+ print("Failed to retrieve abangle file from SAbDab.")
239
+ os.remove(out_file)
240
+ return False
241
+ else:
242
+ return False
243
+ return True
244
+ return True
245
+
246
+ def getimgt(entry, fab_list, out_path):
247
+ """
248
+ Get the imgt files for the antibody sequences.
249
+ """
250
+ for fab in fab_list:
251
+ Hchain = fab[1].upper()
252
+ if Hchain!="NA":
253
+ out_file = os.path.join( out_path, "%s_%s_H.ann"%(entry,Hchain) )
254
+ try:
255
+ urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/imgt/%s_%s_H.imgt"%(entry,entry,Hchain), out_file)
256
+ except Exception as e:
257
+ Hchain = Hchain.lower()
258
+ out_file = os.path.join( out_path, "%s_%s_H.ann"%(entry,Hchain) )
259
+ try:
260
+ urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/imgt/%s_%s_H.imgt"%(entry,entry,Hchain), out_file)
261
+ except Exception as e:
262
+ print("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/imgt/%s_%s_H.imgt failed"%(entry,entry,Hchain))
263
+ return False
264
+
265
+ if os.path.isfile(out_file):
266
+ Retrieved = open(out_file).read()
267
+ if not Retrieved.count("gene_type"):
268
+ print("Failed to retrieve imgt file from SAbDab.")
269
+ os.remove(out_file)
270
+ return False
271
+ else:
272
+ return False
273
+
274
+ Lchain = fab[2].upper()
275
+ if Lchain!="NA":
276
+ out_file = os.path.join( out_path, "%s_%s_L.ann"%(entry,Lchain) )
277
+ try:
278
+ urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/imgt/%s_%s_L.imgt"%(entry,entry,Lchain), out_file)
279
+ except Exception as e:
280
+ Lchain = Lchain.lower()
281
+ out_file = os.path.join( out_path, "%s_%s_L.ann"%(entry,Lchain) )
282
+ try:
283
+ urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/imgt/%s_%s_L.imgt"%(entry,entry,Lchain), out_file)
284
+ except Exception as e:
285
+ print("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/imgt/%s_%s_L.imgt failed"%(entry,entry,Lchain))
286
+ return False
287
+ if os.path.isfile(out_file):
288
+ Retrieved = open(out_file).read()
289
+ if not Retrieved.count("gene_type"):
290
+ print("Failed to retrieve imgt file from SAbDab.")
291
+ os.remove(out_file)
292
+ return False
293
+ else:
294
+ return False
295
+
296
+ return True
297
+
298
+ if __name__ == "__main__":
299
+
300
+ parser = argparse.ArgumentParser(prog="sabdab_downloader", description=description, epilog=epilogue,formatter_class=argparse.RawDescriptionHelpFormatter)
301
+ parser.add_argument( '--summary_file','-s',type=str, help="A tab-separated csv downloaded from SAbDab - https://opig.stats.ox.ac.uk/webapps/sabdab-sabpred/sabdab.", dest="summary_file")
302
+ parser.add_argument( '--output_path','-o',type=str, help="The path to the output directory.", dest="output_path")
303
+ parser.add_argument( '--original_pdb',action="store_true", help="Download the pdb structure(s).", dest="original_pdb")
304
+ parser.add_argument( '--chothia_pdb', action="store_true", help="Download the chothia re-numbered pdb structure(s).", dest="chothia_pdb")
305
+ parser.add_argument( '--sequences',action="store_true", help="Download the sequence information.", dest="sequence")
306
+ parser.add_argument( '--annotation',action="store_true", help="Download the chothia numbered sequence information.", dest="annotation")
307
+ parser.add_argument( '--abangle',action="store_true", help="Download the abangle angles.", dest="abangle")
308
+ parser.add_argument( '--imgt',action="store_true", help="Download the imgt information for the structure.", dest="imgt")
309
+
310
+ args= parser.parse_args()
311
+
312
+ if len(sys.argv)<2:
313
+ parser.print_help()
314
+ sys.exit(0)
315
+
316
+ #####################
317
+ # Check the inputs #
318
+ #####################
319
+
320
+ if not args.summary_file:
321
+ print("No summary file found.")
322
+ sys.exit(1)
323
+ if not args.output_path:
324
+ print("No output path given.")
325
+ sys.exit(1)
326
+
327
+ if not (args.original_pdb or args.chothia_pdb or args.sequence or args.annotation or args.abangle or args.imgt):
328
+ print("No requested data type given. Please choose at least one.")
329
+
330
+ if not os.path.exists(args.output_path):
331
+ print("Output path does not exist.")
332
+ sys.exit(1)
333
+
334
+ if not os.path.isdir(args.output_path):
335
+ print("Output path is not a directory.")
336
+ sys.exit(1)
337
+
338
+ if not os.access(args.output_path, os.W_OK):
339
+ print("Output path is not writable.")
340
+ sys.exit(1)
341
+
342
+ # Set up output directory
343
+ output_path = os.path.join(args.output_path,"sabdab_dataset")
344
+ try:
345
+ os.mkdir(output_path)
346
+ except OSError:
347
+ print("A 'sabdab_dataset' already exists in the output directory. Please rename it or provide a new output directory.")
348
+ sys.exit(1)
349
+
350
+ # Get the summary data
351
+ try:
352
+ with open(args.summary_file,'r') as input_file:
353
+ lines = input_file.readlines()
354
+ header = lines[0].strip().split("\t")[:4]
355
+ if header != ["pdb", "Hchain", "Lchain", "model"]:
356
+ raise IndexError
357
+ data={}
358
+ for line in lines[1:]:
359
+ if not line.strip(): continue
360
+ entry = line.strip().split("\t")[:4]
361
+ if len(entry) < 4 and not entry[0].isalnum():
362
+ raise IndexError
363
+ try:
364
+ data[entry[0].lower()].append(entry)
365
+ except KeyError:
366
+ data[entry[0].lower()] = [entry]
367
+ except IOError:
368
+ print("Could not open summary file.")
369
+ sys.exit(1)
370
+ except IndexError:
371
+ print("Summary file in incorrect format.")
372
+ sys.exit(1)
373
+
374
+ for pdb_entry in data:
375
+ print("Getting data for %s"%pdb_entry)
376
+ got_data=False
377
+ pdb_entry_dir = os.path.join(output_path, pdb_entry)
378
+ os.mkdir(pdb_entry_dir)
379
+ if args.original_pdb or args.chothia_pdb:
380
+ struc_out_path = os.path.join(pdb_entry_dir,"structure")
381
+ os.mkdir(struc_out_path)
382
+ if args.original_pdb:
383
+ if getpdb(pdb_entry, struc_out_path):
384
+ got_data=True
385
+ else:
386
+ print(f"removed {struc_out_path}")
387
+ # os.rmdir(struc_out_path)
388
+
389
+ if args.chothia_pdb:
390
+ choth_struc_out_path = os.path.join(struc_out_path,"chothia")
391
+ os.mkdir(choth_struc_out_path)
392
+ if getchothpdb(pdb_entry, choth_struc_out_path):
393
+ got_data=True
394
+ else:
395
+ print(f"removed {choth_struc_out_path}")
396
+ # os.rmdir(choth_struc_out_path)
397
+
398
+ if args.sequence:
399
+ seq_out_path = os.path.join(pdb_entry_dir,"sequence")
400
+ os.mkdir(seq_out_path)
401
+ if getsequence(pdb_entry, data[pdb_entry] , seq_out_path):
402
+ got_data=True
403
+ else:
404
+ print(f"removed {seq_out_path}")
405
+ # os.rmdir(seq_out_path)
406
+
407
+ if args.annotation:
408
+ annotation_out_path = os.path.join(pdb_entry_dir,"annotation")
409
+ os.mkdir(annotation_out_path)
410
+ if getannotation(pdb_entry, data[pdb_entry] , annotation_out_path):
411
+ got_data=True
412
+ else:
413
+ print(f"removed {annotation_out_path}")
414
+ # os.rmdir(annotation_out_path)
415
+
416
+ if args.abangle:
417
+ abangle_out_path = os.path.join(pdb_entry_dir,"abangle")
418
+ os.mkdir(abangle_out_path)
419
+ if getabangle(pdb_entry, data[pdb_entry] , abangle_out_path):
420
+ got_data=True
421
+ else:
422
+ print(f"removed {abangle_out_path}")
423
+ # os.rmdir(abangle_out_path)
424
+
425
+ if args.imgt:
426
+ imgt_out_path = os.path.join(pdb_entry_dir,"imgt")
427
+ os.mkdir(imgt_out_path)
428
+ if getimgt(pdb_entry, data[pdb_entry] , imgt_out_path):
429
+ got_data=True
430
+ else:
431
+ print(f"removed {imgt_out_path}")
432
+ # os.rmdir(imgt_out_path)
433
+
434
+ if not got_data:
435
+ print(f"deleted {pdb_entry}")
436
+ # os.rmdir(pdb_entry_dir)
437
+
438
+ # Failed or failed or deleted or removed