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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Build chain CSVs from index. Curated by subset: only list/FASTA pairs in
|
| 4 |
+
curated_csv/cullpdb_list_fasta_index.csv are processed.
|
| 5 |
+
|
| 6 |
+
Outputs:
|
| 7 |
+
- curated_csv/cullpdb_combined_chains.csv — single master CSV for all analysis
|
| 8 |
+
- curated_csv/subset_chains/<list_basename>.csv — one CSV per subset
|
| 9 |
+
"""
|
| 10 |
+
import csv
|
| 11 |
+
import re
|
| 12 |
+
import sys
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from typing import List, Optional, Tuple
|
| 15 |
+
|
| 16 |
+
SCRIPT_DIR = Path(__file__).resolve().parent
|
| 17 |
+
BASE = SCRIPT_DIR.parent
|
| 18 |
+
CULLPDB_DIR = BASE / "pieces" / "2026_01_26"
|
| 19 |
+
CURATED_DIR = BASE / "curated_csv"
|
| 20 |
+
SUBSET_CSV_DIR = CURATED_DIR / "subset_chains" # one CSV per subset, named by list_basename
|
| 21 |
+
COMBINED_CSV = CURATED_DIR / "cullpdb_combined_chains.csv" # single CSV for all analysis
|
| 22 |
+
|
| 23 |
+
PAT = re.compile(
|
| 24 |
+
r"^cullpdb_pc([\d.]+)_res([\d.]+)-([\d.]+)_"
|
| 25 |
+
r"(?:(noBrks)_)?"
|
| 26 |
+
r"len40-10000_R([\d.]+)_"
|
| 27 |
+
r"(.+?)_d\d{4}_\d{2}_\d{2}_chains(\d+)$"
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def split_pdb_chain(pdb_chain: str) -> tuple:
|
| 32 |
+
"""Split PDB chain ID into (pdb_id, chain_id). PDB ID is first 4 chars, rest is chain."""
|
| 33 |
+
if len(pdb_chain) <= 4:
|
| 34 |
+
return (pdb_chain, "")
|
| 35 |
+
return (pdb_chain[:4], pdb_chain[4:])
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def parse_params_from_basename(base: str) -> Optional[dict]:
|
| 39 |
+
m = PAT.match(base)
|
| 40 |
+
if not m:
|
| 41 |
+
return None
|
| 42 |
+
pc, res_min, res_max, no_brks, r_cutoff, methods, n_chains = m.groups()
|
| 43 |
+
n = int(n_chains)
|
| 44 |
+
no_brk = no_brks is not None
|
| 45 |
+
return {
|
| 46 |
+
"pc": float(pc),
|
| 47 |
+
"resolution_range": f"{res_min}-{res_max}",
|
| 48 |
+
"no_breaks": "yes" if no_brk else "no",
|
| 49 |
+
"R": float(r_cutoff),
|
| 50 |
+
"source_list": base,
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def read_list_file(path: Path) -> List[dict]:
|
| 55 |
+
"""Return list of dicts: PDBchain, len, method, resol, rfac, freerfac."""
|
| 56 |
+
rows = []
|
| 57 |
+
with open(path) as f:
|
| 58 |
+
lines = f.readlines()
|
| 59 |
+
if not lines:
|
| 60 |
+
return rows
|
| 61 |
+
# header: PDBchain len method resol rfac freerfac
|
| 62 |
+
for line in lines[1:]:
|
| 63 |
+
line = line.strip()
|
| 64 |
+
if not line:
|
| 65 |
+
continue
|
| 66 |
+
parts = line.split()
|
| 67 |
+
if len(parts) < 5:
|
| 68 |
+
continue
|
| 69 |
+
pdb_chain = parts[0]
|
| 70 |
+
try:
|
| 71 |
+
length = int(parts[1])
|
| 72 |
+
except ValueError:
|
| 73 |
+
continue
|
| 74 |
+
method = parts[2]
|
| 75 |
+
resol = parts[3]
|
| 76 |
+
rfac = parts[4]
|
| 77 |
+
freerfac = parts[5] if len(parts) > 5 else ""
|
| 78 |
+
rows.append({
|
| 79 |
+
"pdb_chain": pdb_chain,
|
| 80 |
+
"len": length,
|
| 81 |
+
"method": method,
|
| 82 |
+
"resol": resol,
|
| 83 |
+
"rfac": rfac,
|
| 84 |
+
"freerfac": freerfac,
|
| 85 |
+
})
|
| 86 |
+
return rows
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def read_fasta_entries(path: Path) -> List[Tuple[str, str]]:
|
| 90 |
+
"""Return list of (pdb_chain_from_header, sequence) in order (one per FASTA entry)."""
|
| 91 |
+
entries = []
|
| 92 |
+
current_seq = []
|
| 93 |
+
current_id = None
|
| 94 |
+
with open(path) as f:
|
| 95 |
+
for line in f:
|
| 96 |
+
line = line.rstrip("\n")
|
| 97 |
+
if line.startswith(">"):
|
| 98 |
+
if current_seq is not None:
|
| 99 |
+
if current_id is not None:
|
| 100 |
+
entries.append((current_id, "".join(current_seq)))
|
| 101 |
+
# New entry: first token after ">" is PDBchain
|
| 102 |
+
rest = line[1:].strip()
|
| 103 |
+
current_id = rest.split(None, 1)[0] if rest else ""
|
| 104 |
+
current_seq = []
|
| 105 |
+
else:
|
| 106 |
+
current_seq.append(line)
|
| 107 |
+
if current_id is not None:
|
| 108 |
+
entries.append((current_id, "".join(current_seq)))
|
| 109 |
+
return entries
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def load_pairs_from_index(index_csv: Path) -> List[tuple]:
|
| 113 |
+
"""Load (base, list_path, fasta_path, params) from curated index CSV. Only these subsets are used."""
|
| 114 |
+
pairs = []
|
| 115 |
+
with open(index_csv, newline="") as f:
|
| 116 |
+
r = csv.DictReader(f)
|
| 117 |
+
for row in r:
|
| 118 |
+
base = row.get("list_basename", "").strip()
|
| 119 |
+
list_path_s = row.get("list_path", "").strip()
|
| 120 |
+
fasta_path_s = row.get("fasta_path", "").strip()
|
| 121 |
+
if not base or not list_path_s or not fasta_path_s:
|
| 122 |
+
continue
|
| 123 |
+
list_path = Path(list_path_s)
|
| 124 |
+
fasta_path = Path(fasta_path_s)
|
| 125 |
+
if not list_path.exists() or not fasta_path.exists():
|
| 126 |
+
print(f"Skip (missing): {base}", file=sys.stderr)
|
| 127 |
+
continue
|
| 128 |
+
params = parse_params_from_basename(base)
|
| 129 |
+
if not params:
|
| 130 |
+
print(f"Skip (parse): {base}", file=sys.stderr)
|
| 131 |
+
continue
|
| 132 |
+
pairs.append((base, list_path, fasta_path, params))
|
| 133 |
+
return pairs
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def main():
|
| 137 |
+
index_csv = CURATED_DIR / "cullpdb_list_fasta_index.csv"
|
| 138 |
+
if not index_csv.exists():
|
| 139 |
+
print(f"Index not found: {index_csv}. Run build_list_fasta_index.py first.", file=sys.stderr)
|
| 140 |
+
sys.exit(1)
|
| 141 |
+
|
| 142 |
+
pairs = load_pairs_from_index(index_csv)
|
| 143 |
+
if not pairs:
|
| 144 |
+
print("No subsets in index (or paths missing). Nothing to do.", file=sys.stderr)
|
| 145 |
+
sys.exit(1)
|
| 146 |
+
print(f"Curating from index: {len(pairs)} subsets.")
|
| 147 |
+
fieldnames = [
|
| 148 |
+
"pdb_chain", "pdb", "chain", "sequence", "len", "method", "resolution", "rfac", "freerfac",
|
| 149 |
+
"pc", "no_breaks", "R", "source_list",
|
| 150 |
+
]
|
| 151 |
+
SUBSET_CSV_DIR.mkdir(parents=True, exist_ok=True)
|
| 152 |
+
|
| 153 |
+
# Sanity-check counters
|
| 154 |
+
id_mismatches = 0
|
| 155 |
+
len_mismatches = 0
|
| 156 |
+
count_mismatches = 0
|
| 157 |
+
files_skipped = 0
|
| 158 |
+
rows_written_total = 0
|
| 159 |
+
files_written = 0
|
| 160 |
+
all_rows = [] # for combined CSV (all analysis uses this file)
|
| 161 |
+
|
| 162 |
+
for base, list_path, fasta_path, params in pairs:
|
| 163 |
+
list_rows = read_list_file(list_path)
|
| 164 |
+
fasta_entries = read_fasta_entries(fasta_path)
|
| 165 |
+
n_list, n_fasta = len(list_rows), len(fasta_entries)
|
| 166 |
+
if n_list != n_fasta:
|
| 167 |
+
print(f"SKIP {base}: list has {n_list} rows, fasta has {n_fasta} entries", file=sys.stderr)
|
| 168 |
+
files_skipped += 1
|
| 169 |
+
continue
|
| 170 |
+
|
| 171 |
+
subset_rows = []
|
| 172 |
+
file_id_mismatches = 0
|
| 173 |
+
file_len_mismatches = 0
|
| 174 |
+
for i, (row, (fasta_id, seq)) in enumerate(zip(list_rows, fasta_entries)):
|
| 175 |
+
list_id = row["pdb_chain"]
|
| 176 |
+
list_len = row["len"]
|
| 177 |
+
seq_len = len(seq)
|
| 178 |
+
|
| 179 |
+
# Sanity 1: PDBchain in list must match first token in FASTA header
|
| 180 |
+
if list_id != fasta_id:
|
| 181 |
+
id_mismatches += 1
|
| 182 |
+
file_id_mismatches += 1
|
| 183 |
+
if file_id_mismatches <= 3:
|
| 184 |
+
print(f"ID mismatch in {base} row {i+2}: list={list_id!r} fasta_header={fasta_id!r}", file=sys.stderr)
|
| 185 |
+
continue
|
| 186 |
+
|
| 187 |
+
# Sanity 2: list length must match actual sequence length
|
| 188 |
+
if list_len != seq_len:
|
| 189 |
+
len_mismatches += 1
|
| 190 |
+
file_len_mismatches += 1
|
| 191 |
+
if file_len_mismatches <= 3:
|
| 192 |
+
print(f"LEN mismatch in {base} {list_id}: list len={list_len} seq len={seq_len}", file=sys.stderr)
|
| 193 |
+
continue
|
| 194 |
+
|
| 195 |
+
pdb_id, chain_id = split_pdb_chain(list_id)
|
| 196 |
+
out_row = {
|
| 197 |
+
"pdb_chain": list_id,
|
| 198 |
+
"pdb": pdb_id,
|
| 199 |
+
"chain": chain_id,
|
| 200 |
+
"sequence": seq,
|
| 201 |
+
"len": list_len,
|
| 202 |
+
"method": row["method"],
|
| 203 |
+
"resolution": row["resol"],
|
| 204 |
+
"rfac": row["rfac"],
|
| 205 |
+
"freerfac": row["freerfac"],
|
| 206 |
+
"pc": params["pc"],
|
| 207 |
+
"no_breaks": params["no_breaks"],
|
| 208 |
+
"R": params["R"],
|
| 209 |
+
"source_list": params["source_list"],
|
| 210 |
+
}
|
| 211 |
+
subset_rows.append(out_row)
|
| 212 |
+
|
| 213 |
+
if file_id_mismatches > 0 or file_len_mismatches > 0:
|
| 214 |
+
count_mismatches += 1
|
| 215 |
+
|
| 216 |
+
# Write one CSV per subset
|
| 217 |
+
out_path = SUBSET_CSV_DIR / f"{base}.csv"
|
| 218 |
+
with open(out_path, "w", newline="") as f:
|
| 219 |
+
w = csv.DictWriter(f, fieldnames=fieldnames)
|
| 220 |
+
w.writeheader()
|
| 221 |
+
w.writerows(subset_rows)
|
| 222 |
+
all_rows.extend(subset_rows)
|
| 223 |
+
rows_written_total += len(subset_rows)
|
| 224 |
+
files_written += 1
|
| 225 |
+
|
| 226 |
+
# Write single combined CSV for all downstream analysis
|
| 227 |
+
with open(COMBINED_CSV, "w", newline="") as f:
|
| 228 |
+
w = csv.DictWriter(f, fieldnames=fieldnames)
|
| 229 |
+
w.writeheader()
|
| 230 |
+
w.writerows(all_rows)
|
| 231 |
+
print(f"Wrote {COMBINED_CSV} with {len(all_rows)} chain rows (master for analysis).")
|
| 232 |
+
|
| 233 |
+
# Summary
|
| 234 |
+
print(f"Wrote {files_written} subset CSVs to {SUBSET_CSV_DIR} ({rows_written_total} chain rows total).")
|
| 235 |
+
print(f"Sanity check: ID mismatches (list PDBchain vs FASTA header) = {id_mismatches}")
|
| 236 |
+
print(f"Sanity check: length mismatches (list len vs len(sequence)) = {len_mismatches}")
|
| 237 |
+
print(f"Files with ID or len mismatch = {count_mismatches}; files skipped (list vs FASTA count) = {files_skipped}")
|
| 238 |
+
if id_mismatches > 0 or len_mismatches > 0 or files_skipped > 0:
|
| 239 |
+
sys.exit(1)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
if __name__ == "__main__":
|
| 243 |
+
main()
|