Datasets:
Upload 4 files
Browse filesFiles changed (4)
- src/add_nr_column.pyAdded+28
- src/add_paths_to_tsv.pyAdded+91
- src/multivariate_stratification.pyAdded+66
- src/sabdab_downloader_fixed.pyAdded+438
12345678910111213141516171819202122232425262728#!/usr/bin/env python3import csv
summary_file = "sabdab_summary_all_with_paths.tsv"nr_file = "all_nr.tsv"output_file = "sabdab_summary_with_nr_flag.tsv"
# Read all pdb IDs from the non-redundant setnr_pdbs = set()with open(nr_file, newline="") as f: reader = csv.DictReader(f, delimiter="\t") for row in reader: nr_pdbs.add(row["pdb"].strip().lower())
# Process the summary file and add the new columnwith open(summary_file, newline="") as infile, open(output_file, "w", newline="") as outfile: reader = csv.DictReader(infile, delimiter="\t") fieldnames = reader.fieldnames + ["in_nr_set"]
writer = csv.DictWriter(outfile, fieldnames=fieldnames, delimiter="\t") writer.writeheader()
for row in reader: pdb = row["pdb"].strip().lower() row["in_nr_set"] = str(pdb in nr_pdbs) writer.writerow(row)
print(f"Output written to {output_file}")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091import pandas as pdfrom pathlib import Pathimport re
# Inputtsv_path = "sabdab_summary_all_sorted.tsv"base_dir = Path("sabdab_dataset")
df = pd.read_csv(tsv_path, sep="\t")
def find_file(directory, pattern): if not directory.exists(): return None
regex = re.compile(pattern, re.IGNORECASE)
for f in directory.iterdir(): if f.is_file() and regex.fullmatch(f.name): # return actual existing path relative to sabdab_dataset return str(f.relative_to(base_dir.parent))
return None
def get_paths(row): pdb = str(row["pdb"]) H = str(row["Hchain"]) L = str(row["Lchain"])
pdb_dir = base_dir / pdb.lower()
return pd.Series({ "abangle": find_file( pdb_dir / "abangle", rf"{pdb}\.abangle" ),
"annotation_H": find_file( pdb_dir / "annotation", rf"{pdb}_{H}_VH\.ann" ),
"annotation_L": find_file( pdb_dir / "annotation", rf"{pdb}_{L}_VL\.ann" ),
"imgt_H": find_file( pdb_dir / "imgt", rf"{pdb}_{H}_H\.ann" ),
"imgt_L": find_file( pdb_dir / "imgt", rf"{pdb}_{L}_L\.ann" ),
"sequence_raw": find_file( pdb_dir / "sequence", rf"{pdb}_raw\.pdb" ),
"sequence_H": find_file( pdb_dir / "sequence", rf"{pdb}_{H}_VH\.fa" ),
"sequence_L": find_file( pdb_dir / "sequence", rf"{pdb}_{L}_VL\.fa" ),
"structure": find_file( pdb_dir / "structure", rf"{pdb}\.pdb" ),
"structure_chothia": find_file( pdb_dir / "structure" / "chothia", rf"{pdb}\.pdb" ), })
# Apply row-wisenew_cols = df.apply(get_paths, axis=1)
df = pd.concat([df, new_cols], axis=1)
df.to_csv("sabdab_summary_all_with_paths.tsv", sep="\t", index=False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566import pandas as pdimport numpy as np
# Load the datadf = pd.read_csv("~/Desktop/sabdab_summary_with_flags.tsv", sep="\t")
# Create the strata columnstrata_cols = ["antigen_type", "heavy_species", "method", "scfv", "engineered", "light_ctype", "in_nr_set", "curated_quality_dataset"]df["strata"] = df[strata_cols].astype(str).agg("_".join, axis=1)
# Initialize split columndf["split"] = ""
# Define fractionstrain_frac = 0.8val_frac = 0.1test_frac = 0.1
# Set random seed for reproducibilitynp.random.seed(42)
# Get all unique strataall_strata = df["strata"].unique()
for s in all_strata: idx = df[df["strata"] == s].index.to_list() np.random.shuffle(idx) n = len(idx) n_train = max(1, int(n * train_frac)) n_val = max(1, int(n * val_frac)) n_test = n - n_train - n_val # whatever remains
# Adjust in case rounding caused n_test < 1 if n_test < 1: n_test = 1 if n_val > 1: n_val -= 1 else: n_train -= 1
# Assign df.loc[idx[:n_train], "split"] = "train" df.loc[idx[n_train:n_train+n_val], "split"] = "validation" df.loc[idx[n_train+n_val:], "split"] = "test"
# Drop temporary strata columndf.drop(columns=["strata"], inplace=True)
# Check countsprint(df["split"].value_counts(normalize=True) * 100)
cols = ["antigen_type", "heavy_species", "method", "scfv", "engineered", "light_ctype", "in_nr_set", "curated_quality_dataset"]
for col in cols: print(f"\n=== {col} ===") # Cross-tab of counts by split ct = pd.crosstab(df[col], df["split"]) # Convert counts to percentages **row-wise** so each category sums to 100% ct_percent = ct.div(ct.sum(axis=1), axis=0) * 100 print(ct_percent.round(1))
# Save to TSVdf.to_csv("~/Desktop/sabdab_summary_with_splits.tsv", sep="\t", index=False)print("Saved updated DataFrame with split column to ~/Desktop/sabdab_summary_with_splits.tsv")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438description='''
SAbDab Download Script \\\ //The OPIG Antibody Database \\\ //Authors: James Dunbar and Konrad Krawczyk 2013. ||Contributors: Jinwoo Leem ||Supervisor: Charlotte Deane
Contact: opig@stats.ox.ac.uk
In collaboration with:UCB: Jiye Shi, Terry Baker.Roche: Angelika Fuchs, Guy Georges.
o This is a script that allows a user to download data from SAbDab.o It requires a csv summary file downloaded from the website (opig.stats.ox.ac.uk/webapps/sabdab)
o This file should contain AT LEAST:
1. A header line with tab-separated fields as "pdb Hchain Lchain model" 2. The pdb identifier, heavy chain, light chain and model id on new lines e.g.
pdb Hchain Lchain model 12e8 H L 0 12e8 P M 0 1ahw B A 0 1ahw E D 0 . . . . . . . . . . . .
o Other fields will be ignored but may be included in the file.
o The user must provide a directory in which the data should be downloaded to.o The type of data that should be downloaded should be specified using the command-line options.
o Example useage: To run on a linux command line type:
python sabdab_downloader.py -s summary_file.csv -o path/to/output/ --original_pdb
This will create a directory in "path/to/output/" name sabdab_dataset. It will contain a directory for each unique pdb code in the summary_file.csv . The structure for each of these pdbs will be downloaded there.'''
epilogue="""Copyright (C) 2013 James Dunbar"""
import argparse, sys, os, urllib.request
def getpdb(pdb_entry, out_path): """ Get the PDB file from sabdab. Check that it has successfully downloaded. """ out_file = os.path.join( out_path, "%s.pdb"%pdb_entry) try: urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/structure/%s.pdb"%(pdb_entry,pdb_entry), out_file) except Exception as e: print("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/structure/%s.pdb failed"%(pdb_entry,pdb_entry)) return False if os.path.isfile(out_file): Retrieved = open(out_file).read() if not Retrieved.count("ATOM"): print("Failed to retrieve PDB file from SAbDab") os.remove(out_file) return False else: return True else: return False
def getchothpdb(pdb_entry, out_path): """ Get the chothia PDB file from sabdab. Check that it has successfully downloaded. """ out_file = os.path.join( out_path, "%s.pdb"%pdb_entry) try: urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/structure/chothia/%s.pdb"%(pdb_entry,pdb_entry), out_file) except Exception as e: print("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/structure/chothia/%s.pdb failed"%(pdb_entry,pdb_entry)) return False if os.path.isfile(out_file): Retrieved = open(out_file).read() if not Retrieved.count("ATOM"): print("Failed to retrieve PDB file from SAbDab") os.remove(out_file) return False else: return True else: return False
def getsequence(entry, fab_list, out_path): """ Get the sequence files Check that they successfully download Put them into the directory """
out_file = os.path.join( out_path, "%s_raw.pdb"%entry) try: urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/sequences/%s_raw.fa"%(entry,entry), out_file) except Exception as e: print("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/sequences/%s_raw.fa failed"%(entry,entry)) return False if os.path.isfile(out_file): Retrieved = open(out_file).read() if not Retrieved.count(">%s"%entry): print("Failed to retrieve sequence file from SAbDab.") os.remove(out_file) return False else: return False
for fab in fab_list: Hchain = fab[1].upper() if Hchain!="NA": out_file = os.path.join( out_path, "%s_%s_VH.fa"%(entry,Hchain) ) try: urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/sequences/%s_%s_VH.fa"%(entry,entry,Hchain), out_file) except Exception as e: Hchain = Hchain.lower() out_file = os.path.join( out_path, "%s_%s_VH.fa"%(entry,Hchain) ) try: urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/sequences/%s_%s_VH.fa"%(entry,entry,Hchain), out_file) except Exception as e: print("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/sequences/%s_%s_VH.fa failed"%(entry,entry,Hchain)) return False if os.path.isfile(out_file): Retrieved = open(out_file).read() if not Retrieved.count(">%s"%entry): print("Failed to retrieve sequence file from SAbDab.") os.remove(out_file) return False else: return False
Lchain = fab[2].upper() if Lchain!="NA": out_file = os.path.join( out_path, "%s_%s_VL.fa"%(entry,Lchain) ) try: urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/sequences/%s_%s_VL.fa"%(entry,entry,Lchain), out_file) except Exception as e: Lchain = Lchain.lower() out_file = os.path.join( out_path, "%s_%s_VL.fa"%(entry,Lchain) ) try: urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/sequences/%s_%s_VL.fa"%(entry,entry,Lchain), out_file) except Exception as e: print("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/sequences/%s_%s_VL.fa failed"%(entry,entry,Lchain)) return False if os.path.isfile(out_file): Retrieved = open(out_file).read() if not Retrieved.count(">%s"%entry): print("Failed to retrieve sequence file from SAbDab.") os.remove(out_file) return False else: return False
return True
def getannotation(entry, fab_list, out_path): """ Get the annotation files for the antibody sequences. These are for the variable region of the sequences only. """ for fab in fab_list: Hchain = fab[1].upper() if Hchain!="NA": out_file = os.path.join( out_path, "%s_%s_VH.ann"%(entry,Hchain) ) try: urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/annotation/%s_%s_VH.ann"%(entry,entry,Hchain), out_file) except Exception as e: Hchain = Hchain.lower() out_file = os.path.join( out_path, "%s_%s_VH.ann"%(entry,Hchain) ) try: urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/annotation/%s_%s_VH.ann"%(entry,entry,Hchain), out_file) except Exception as e: print("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/annotation/%s_%s_VH.ann failed"%(entry,entry,Hchain)) return False if os.path.isfile(out_file): Retrieved = open(out_file).read() if not Retrieved.count("H3"): print("Failed to retrieve annotation file from SAbDab.") os.remove(out_file) return False else: return False
Lchain = fab[2].upper() if Lchain!="NA": out_file = os.path.join( out_path, "%s_%s_VL.ann"%(entry,Lchain) ) try: urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/annotation/%s_%s_VL.ann"%(entry,entry,Lchain), out_file) except Exception as e: Lchain = Lchain.lower() out_file = os.path.join( out_path, "%s_%s_VL.ann"%(entry,Lchain) ) try: urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/annotation/%s_%s_VL.ann"%(entry,entry,Lchain), out_file) except Exception as e: print("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/annotation/%s_%s_VL.ann failed"%(entry,entry,Lchain)) return False if os.path.isfile(out_file): Retrieved = open(out_file).read() if not Retrieved.count("L3"): print("Failed to retrieve annotation file from SAbDab.") os.remove(out_file) return False else: return False return True
def getabangle(entry, fab_list, out_path): """ Get the orientation angles for any of the fabs in the pdb. A non-paired antibody chain e.g VHH will have NA as the other chain identifier. """ for fab in fab_list: if "NA" in fab: continue else: out_file = os.path.join( out_path, "%s.abangle"%(entry) ) try: urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/abangle/%s.abangle"%(entry,entry), out_file) except Exception as e: print("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/abangle/%s.abangle failed"%(entry,entry)) return False if os.path.isfile(out_file): Retrieved = open(out_file).read() if not Retrieved.count(entry): print("Failed to retrieve abangle file from SAbDab.") os.remove(out_file) return False else: return False return True return True
def getimgt(entry, fab_list, out_path): """ Get the imgt files for the antibody sequences. """ for fab in fab_list: Hchain = fab[1].upper() if Hchain!="NA": out_file = os.path.join( out_path, "%s_%s_H.ann"%(entry,Hchain) ) try: urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/imgt/%s_%s_H.imgt"%(entry,entry,Hchain), out_file) except Exception as e: Hchain = Hchain.lower() out_file = os.path.join( out_path, "%s_%s_H.ann"%(entry,Hchain) ) try: urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/imgt/%s_%s_H.imgt"%(entry,entry,Hchain), out_file) except Exception as e: print("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/imgt/%s_%s_H.imgt failed"%(entry,entry,Hchain)) return False if os.path.isfile(out_file): Retrieved = open(out_file).read() if not Retrieved.count("gene_type"): print("Failed to retrieve imgt file from SAbDab.") os.remove(out_file) return False else: return False
Lchain = fab[2].upper() if Lchain!="NA": out_file = os.path.join( out_path, "%s_%s_L.ann"%(entry,Lchain) ) try: urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/imgt/%s_%s_L.imgt"%(entry,entry,Lchain), out_file) except Exception as e: Lchain = Lchain.lower() out_file = os.path.join( out_path, "%s_%s_L.ann"%(entry,Lchain) ) try: urllib.request.urlretrieve("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/imgt/%s_%s_L.imgt"%(entry,entry,Lchain), out_file) except Exception as e: print("https://opig.stats.ox.ac.uk/webapps/abdb/entries/%s/imgt/%s_%s_L.imgt failed"%(entry,entry,Lchain)) return False if os.path.isfile(out_file): Retrieved = open(out_file).read() if not Retrieved.count("gene_type"): print("Failed to retrieve imgt file from SAbDab.") os.remove(out_file) return False else: return False
return True
if __name__ == "__main__":
parser = argparse.ArgumentParser(prog="sabdab_downloader", description=description, epilog=epilogue,formatter_class=argparse.RawDescriptionHelpFormatter) 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") parser.add_argument( '--output_path','-o',type=str, help="The path to the output directory.", dest="output_path") parser.add_argument( '--original_pdb',action="store_true", help="Download the pdb structure(s).", dest="original_pdb") parser.add_argument( '--chothia_pdb', action="store_true", help="Download the chothia re-numbered pdb structure(s).", dest="chothia_pdb") parser.add_argument( '--sequences',action="store_true", help="Download the sequence information.", dest="sequence") parser.add_argument( '--annotation',action="store_true", help="Download the chothia numbered sequence information.", dest="annotation") parser.add_argument( '--abangle',action="store_true", help="Download the abangle angles.", dest="abangle") parser.add_argument( '--imgt',action="store_true", help="Download the imgt information for the structure.", dest="imgt")
args= parser.parse_args()
if len(sys.argv)<2: parser.print_help() sys.exit(0)
##################### # Check the inputs # #####################
if not args.summary_file: print("No summary file found.") sys.exit(1) if not args.output_path: print("No output path given.") sys.exit(1)
if not (args.original_pdb or args.chothia_pdb or args.sequence or args.annotation or args.abangle or args.imgt): print("No requested data type given. Please choose at least one.")
if not os.path.exists(args.output_path): print("Output path does not exist.") sys.exit(1)
if not os.path.isdir(args.output_path): print("Output path is not a directory.") sys.exit(1)
if not os.access(args.output_path, os.W_OK): print("Output path is not writable.") sys.exit(1)
# Set up output directory output_path = os.path.join(args.output_path,"sabdab_dataset") try: os.mkdir(output_path) except OSError: print("A 'sabdab_dataset' already exists in the output directory. Please rename it or provide a new output directory.") sys.exit(1)
# Get the summary data try: with open(args.summary_file,'r') as input_file: lines = input_file.readlines() header = lines[0].strip().split("\t")[:4] if header != ["pdb", "Hchain", "Lchain", "model"]: raise IndexError data={} for line in lines[1:]: if not line.strip(): continue entry = line.strip().split("\t")[:4] if len(entry) < 4 and not entry[0].isalnum(): raise IndexError try: data[entry[0].lower()].append(entry) except KeyError: data[entry[0].lower()] = [entry] except IOError: print("Could not open summary file.") sys.exit(1) except IndexError: print("Summary file in incorrect format.") sys.exit(1)
for pdb_entry in data: print("Getting data for %s"%pdb_entry) got_data=False pdb_entry_dir = os.path.join(output_path, pdb_entry) os.mkdir(pdb_entry_dir) if args.original_pdb or args.chothia_pdb: struc_out_path = os.path.join(pdb_entry_dir,"structure") os.mkdir(struc_out_path) if args.original_pdb: if getpdb(pdb_entry, struc_out_path): got_data=True else: print(f"removed {struc_out_path}") # os.rmdir(struc_out_path)
if args.chothia_pdb: choth_struc_out_path = os.path.join(struc_out_path,"chothia") os.mkdir(choth_struc_out_path) if getchothpdb(pdb_entry, choth_struc_out_path): got_data=True else: print(f"removed {choth_struc_out_path}") # os.rmdir(choth_struc_out_path)
if args.sequence: seq_out_path = os.path.join(pdb_entry_dir,"sequence") os.mkdir(seq_out_path) if getsequence(pdb_entry, data[pdb_entry] , seq_out_path): got_data=True else: print(f"removed {seq_out_path}") # os.rmdir(seq_out_path)
if args.annotation: annotation_out_path = os.path.join(pdb_entry_dir,"annotation") os.mkdir(annotation_out_path) if getannotation(pdb_entry, data[pdb_entry] , annotation_out_path): got_data=True else: print(f"removed {annotation_out_path}") # os.rmdir(annotation_out_path)
if args.abangle: abangle_out_path = os.path.join(pdb_entry_dir,"abangle") os.mkdir(abangle_out_path) if getabangle(pdb_entry, data[pdb_entry] , abangle_out_path): got_data=True else: print(f"removed {abangle_out_path}") # os.rmdir(abangle_out_path)
if args.imgt: imgt_out_path = os.path.join(pdb_entry_dir,"imgt") os.mkdir(imgt_out_path) if getimgt(pdb_entry, data[pdb_entry] , imgt_out_path): got_data=True else: print(f"removed {imgt_out_path}") # os.rmdir(imgt_out_path)
if not got_data: print(f"deleted {pdb_entry}") # os.rmdir(pdb_entry_dir)
# Failed or failed or deleted or removedsrc/add_nr_column.pyAdded+28
src/add_paths_to_tsv.pyAdded+91
src/multivariate_stratification.pyAdded+66
src/sabdab_downloader_fixed.pyAdded+438