akshayansamy commited on
Commit
aa4a230
·
verified ·
1 Parent(s): fc905aa

Upload src/03_filter_chain.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. src/03_filter_chain.py +364 -0
src/03_filter_chain.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Generate publication-style figures from CullPDB chain CSV(s).
4
+
5
+ Reads from a single combined CSV or from curated_csv/subset_chains/ (all CSVs merged).
6
+ Saves figures to curated_csv/figures/.
7
+
8
+ Summary (after curation):
9
+ - curation_summary.png: one-page dashboard with key stats + overview plots.
10
+
11
+ Individual plots:
12
+ - Chains per pc, per method, no_breaks; resolution/length histograms;
13
+ - Chains by (pc, no_breaks); resolution vs length scatter.
14
+ """
15
+ import csv
16
+ import sys
17
+ from collections import defaultdict
18
+ from pathlib import Path
19
+ from typing import Any, Dict, Iterator, List
20
+
21
+ SCRIPT_DIR = Path(__file__).resolve().parent
22
+ BASE = SCRIPT_DIR.parent
23
+ CURATED_DIR = BASE / "curated_csv"
24
+ FIG_DIR = CURATED_DIR / "figures"
25
+
26
+ try:
27
+ import matplotlib
28
+ matplotlib.use("Agg")
29
+ import matplotlib.pyplot as plt
30
+ except ImportError:
31
+ print("matplotlib required: pip install matplotlib", file=sys.stderr)
32
+ sys.exit(1)
33
+
34
+ try:
35
+ import numpy as np
36
+ except ImportError:
37
+ np = None # will skip scatter / numeric bins where needed
38
+
39
+
40
+ def iter_rows(input_path: Path) -> Iterator[Dict[str, Any]]:
41
+ """Yield rows from a single CSV or all CSVs in a directory."""
42
+ if input_path.is_file():
43
+ with open(input_path, newline="") as f:
44
+ for row in csv.DictReader(f):
45
+ yield row
46
+ return
47
+ for p in sorted(input_path.glob("*.csv")):
48
+ with open(p, newline="") as f:
49
+ for row in csv.DictReader(f):
50
+ yield row
51
+
52
+
53
+ def safe_float(x: Any) -> float:
54
+ try:
55
+ return float(x)
56
+ except (ValueError, TypeError):
57
+ return float("nan")
58
+
59
+
60
+ def safe_int(x: Any) -> int:
61
+ try:
62
+ return int(float(x))
63
+ except (ValueError, TypeError):
64
+ return 0
65
+
66
+
67
+ def main():
68
+ import argparse
69
+ ap = argparse.ArgumentParser(description="Visualize CullPDB chain data.")
70
+ ap.add_argument(
71
+ "--input", "-i",
72
+ type=Path,
73
+ default=CURATED_DIR / "cullpdb_combined_chains.csv",
74
+ help="Master chain CSV (default: curated_csv/cullpdb_combined_chains.csv)",
75
+ )
76
+ ap.add_argument(
77
+ "--output-dir", "-o",
78
+ type=Path,
79
+ default=FIG_DIR,
80
+ help="Directory for output figures",
81
+ )
82
+ ap.add_argument(
83
+ "--format",
84
+ default="png",
85
+ choices=("png", "pdf", "svg"),
86
+ help="Figure format",
87
+ )
88
+ ap.add_argument(
89
+ "--dpi",
90
+ type=int,
91
+ default=150,
92
+ help="DPI for raster formats",
93
+ )
94
+ ap.add_argument(
95
+ "--max-points-scatter",
96
+ type=int,
97
+ default=10000,
98
+ help="Max points in resolution vs length scatter (downsample if larger)",
99
+ )
100
+ args = ap.parse_args()
101
+
102
+ if not args.input.exists():
103
+ print(f"Input not found: {args.input}", file=sys.stderr)
104
+ sys.exit(1)
105
+
106
+ # Load data
107
+ rows = list(iter_rows(args.input))
108
+ if not rows:
109
+ print("No rows loaded.", file=sys.stderr)
110
+ sys.exit(1)
111
+
112
+ print(f"Loaded {len(rows)} chains from {args.input}", file=sys.stderr)
113
+ args.output_dir.mkdir(parents=True, exist_ok=True)
114
+ ext = args.format
115
+ dpi = args.dpi
116
+
117
+ # Try seaborn for style
118
+ try:
119
+ import seaborn as sns
120
+ sns.set_theme(style="whitegrid", font_scale=1.1)
121
+ palette = "colorblind"
122
+ except ImportError:
123
+ palette = None
124
+ for style in ("seaborn-v0_8-whitegrid", "seaborn-whitegrid", "ggplot"):
125
+ if style in plt.style.available:
126
+ plt.style.use(style)
127
+ break
128
+
129
+ # --- Single pass: collect all stats for summary + individual plots ---
130
+ pc_counts = defaultdict(int)
131
+ method_counts = defaultdict(int)
132
+ nb_counts = defaultdict(int)
133
+ pc_nb = defaultdict(lambda: defaultdict(int))
134
+ resols = []
135
+ lens = []
136
+ unique_sources = set()
137
+ unique_pdbs = set()
138
+ for r in rows:
139
+ pc = safe_float(r.get("pc"))
140
+ if np is not None and np.isnan(pc):
141
+ pass
142
+ else:
143
+ pc_counts[pc] += 1
144
+ m = (r.get("method") or "").strip().upper() or "unknown"
145
+ method_counts[m] += 1
146
+ nb = (r.get("no_breaks") or "").strip().lower()
147
+ nb_key = "yes" if nb in ("yes", "y", "1", "true") else "no"
148
+ nb_counts[nb_key] += 1
149
+ if np is not None and not np.isnan(pc):
150
+ pc_nb[pc][nb_key] += 1
151
+ res = safe_float(r.get("resolution"))
152
+ if res and (np is None or not np.isnan(res)) and 0 < res < 20:
153
+ resols.append(res)
154
+ le = safe_int(r.get("len"))
155
+ if 0 < le < 100000:
156
+ lens.append(le)
157
+ src = (r.get("source_list") or "").strip()
158
+ if src:
159
+ unique_sources.add(src)
160
+ pdb = (r.get("pdb") or "").strip()
161
+ if pdb:
162
+ unique_pdbs.add(pdb)
163
+
164
+ n_chains = len(rows)
165
+ n_subsets = len(unique_sources)
166
+ n_pdbs = len(unique_pdbs)
167
+ res_median = float(np.median(resols)) if np and resols else (sorted(resols)[len(resols)//2] if resols else None)
168
+ res_min = min(resols) if resols else None
169
+ res_max = max(resols) if resols else None
170
+ len_median = int(np.median(lens)) if np and lens else (sorted(lens)[len(lens)//2] if lens else None)
171
+ len_min = min(lens) if lens else None
172
+ len_max = max(lens) if lens else None
173
+
174
+ # --- Summary figure (one-page dashboard after curation) ---
175
+ fig = plt.figure(figsize=(12, 10))
176
+ fig.suptitle("CullPDB curated dataset — summary", fontsize=14, fontweight="bold", y=0.98)
177
+
178
+ # Stats text panel
179
+ ax_text = fig.add_subplot(3, 2, 1)
180
+ ax_text.axis("off")
181
+ stats_lines = [
182
+ "Dataset overview",
183
+ "",
184
+ f" Total chains: {n_chains:,}",
185
+ f" Unique PDBs: {n_pdbs:,}",
186
+ f" Subsets (lists): {n_subsets}",
187
+ "",
188
+ "Resolution (Å)",
189
+ f" Min / Median / Max: {res_min:.2f} / {res_median:.2f} / {res_max:.2f}" if resols else " —",
190
+ "",
191
+ "Sequence length",
192
+ f" Min / Median / Max: {len_min} / {len_median} / {len_max}" if lens else " —",
193
+ ]
194
+ ax_text.text(0.05, 0.95, "\n".join(stats_lines), transform=ax_text.transAxes,
195
+ fontsize=11, verticalalignment="top", fontfamily="monospace",
196
+ bbox=dict(boxstyle="round", facecolor="wheat", alpha=0.3))
197
+
198
+ # Chains per pc (compact)
199
+ ax1 = fig.add_subplot(3, 2, 2)
200
+ if pc_counts:
201
+ pcs = sorted(pc_counts.keys())
202
+ counts = [pc_counts[p] for p in pcs]
203
+ ax1.bar(range(len(pcs)), counts, color="steelblue", edgecolor="navy", linewidth=0.5)
204
+ ax1.set_xticks(range(len(pcs)))
205
+ ax1.set_xticklabels([str(p) for p in pcs], rotation=45, ha="right", fontsize=8)
206
+ ax1.set_ylabel("Chains")
207
+ ax1.set_title("Chains per pc (%)")
208
+
209
+ # Method (compact)
210
+ ax2 = fig.add_subplot(3, 2, 3)
211
+ if method_counts:
212
+ methods = sorted(method_counts.keys(), key=lambda x: -method_counts[x])
213
+ counts = [method_counts[m] for m in methods]
214
+ ax2.barh(methods, counts, color="teal", alpha=0.85, edgecolor="darkgreen", linewidth=0.3)
215
+ ax2.set_xlabel("Chains")
216
+ ax2.set_title("By method")
217
+
218
+ # no_breaks (compact)
219
+ ax3 = fig.add_subplot(3, 2, 4)
220
+ if nb_counts:
221
+ labels = ["no", "yes"]
222
+ counts = [nb_counts.get(l, 0) for l in labels]
223
+ ax3.bar(labels, counts, color=["coral", "seagreen"], edgecolor="black", linewidth=0.5)
224
+ ax3.set_ylabel("Chains")
225
+ ax3.set_title("No breaks")
226
+
227
+ # Resolution histogram (compact)
228
+ ax4 = fig.add_subplot(3, 2, 5)
229
+ if resols:
230
+ ax4.hist(resols, bins=40, color="steelblue", alpha=0.8, edgecolor="white", linewidth=0.2)
231
+ ax4.set_xlabel("Resolution (Å)")
232
+ ax4.set_ylabel("Chains")
233
+ ax4.set_title("Resolution distribution")
234
+
235
+ # Length histogram (compact)
236
+ ax5 = fig.add_subplot(3, 2, 6)
237
+ if lens:
238
+ ax5.hist(lens, bins=50, color="mediumpurple", alpha=0.8, edgecolor="white", linewidth=0.2)
239
+ ax5.set_xlabel("Sequence length")
240
+ ax5.set_ylabel("Chains")
241
+ ax5.set_title("Length distribution")
242
+
243
+ plt.tight_layout(rect=[0, 0, 1, 0.96])
244
+ plt.savefig(args.output_dir / f"curation_summary.{ext}", dpi=dpi, bbox_inches="tight")
245
+ plt.close()
246
+ print(f" Saved curation_summary.{ext}", file=sys.stderr)
247
+
248
+ # --- 1. Chains per pc (bar) ---
249
+ if pc_counts:
250
+ pcs = sorted(pc_counts.keys())
251
+ counts = [pc_counts[p] for p in pcs]
252
+ fig, ax = plt.subplots(figsize=(8, 4))
253
+ bars = ax.bar(range(len(pcs)), counts, color="steelblue", edgecolor="navy", linewidth=0.5)
254
+ ax.set_xticks(range(len(pcs)))
255
+ ax.set_xticklabels([str(p) for p in pcs], rotation=45, ha="right")
256
+ ax.set_xlabel("Sequence identity cutoff (%)")
257
+ ax.set_ylabel("Number of chains")
258
+ ax.set_title("Chains per sequence identity cutoff (pc)")
259
+ plt.tight_layout()
260
+ plt.savefig(args.output_dir / f"chains_per_pc.{ext}", dpi=dpi, bbox_inches="tight")
261
+ plt.close()
262
+ print(f" Saved chains_per_pc.{ext}", file=sys.stderr)
263
+
264
+ # --- 2. Chains per method ---
265
+ if method_counts:
266
+ methods = sorted(method_counts.keys(), key=lambda x: -method_counts[x])
267
+ counts = [method_counts[m] for m in methods]
268
+ fig, ax = plt.subplots(figsize=(6, 4))
269
+ ax.barh(methods, counts, color="teal", alpha=0.85, edgecolor="darkgreen", linewidth=0.5)
270
+ ax.set_xlabel("Number of chains")
271
+ ax.set_ylabel("Method")
272
+ ax.set_title("Chains per method")
273
+ plt.tight_layout()
274
+ plt.savefig(args.output_dir / f"chains_per_method.{ext}", dpi=dpi, bbox_inches="tight")
275
+ plt.close()
276
+ print(f" Saved chains_per_method.{ext}", file=sys.stderr)
277
+
278
+ # --- 3. no_breaks yes vs no ---
279
+ if nb_counts:
280
+ labels = ["no", "yes"]
281
+ counts = [nb_counts.get(l, 0) for l in labels]
282
+ fig, ax = plt.subplots(figsize=(4, 4))
283
+ colors = ["coral", "seagreen"] if palette is None else plt.cm.tab10.colors[:2]
284
+ ax.bar(labels, counts, color=colors, edgecolor="black", linewidth=0.5)
285
+ ax.set_ylabel("Number of chains")
286
+ ax.set_xlabel("No breaks")
287
+ ax.set_title("Chains by no_breaks filter")
288
+ plt.tight_layout()
289
+ plt.savefig(args.output_dir / f"chains_no_breaks.{ext}", dpi=dpi, bbox_inches="tight")
290
+ plt.close()
291
+ print(f" Saved chains_no_breaks.{ext}", file=sys.stderr)
292
+
293
+ # --- 4. Resolution histogram ---
294
+ if resols:
295
+ fig, ax = plt.subplots(figsize=(6, 4))
296
+ ax.hist(resols, bins=50, color="steelblue", alpha=0.8, edgecolor="white", linewidth=0.3)
297
+ ax.set_xlabel("Resolution (Å)")
298
+ ax.set_ylabel("Number of chains")
299
+ ax.set_title("Resolution distribution")
300
+ plt.tight_layout()
301
+ plt.savefig(args.output_dir / f"resolution_hist.{ext}", dpi=dpi, bbox_inches="tight")
302
+ plt.close()
303
+ print(f" Saved resolution_hist.{ext}", file=sys.stderr)
304
+
305
+ # --- 5. Sequence length histogram ---
306
+ if lens:
307
+ fig, ax = plt.subplots(figsize=(6, 4))
308
+ ax.hist(lens, bins=60, color="mediumpurple", alpha=0.8, edgecolor="white", linewidth=0.3)
309
+ ax.set_xlabel("Sequence length")
310
+ ax.set_ylabel("Number of chains")
311
+ ax.set_title("Sequence length distribution")
312
+ plt.tight_layout()
313
+ plt.savefig(args.output_dir / f"length_hist.{ext}", dpi=dpi, bbox_inches="tight")
314
+ plt.close()
315
+ print(f" Saved length_hist.{ext}", file=sys.stderr)
316
+
317
+ # --- 6. Chain count by (pc, no_breaks) grouped bar ---
318
+ if pc_nb:
319
+ pcs = sorted(pc_nb.keys())
320
+ yes_counts = [pc_nb[p]["yes"] for p in pcs]
321
+ no_counts = [pc_nb[p]["no"] for p in pcs]
322
+ n = len(pcs)
323
+ x = np.arange(n) if np is not None else list(range(n))
324
+ w = 0.35
325
+ fig, ax = plt.subplots(figsize=(10, 4))
326
+ ax.bar(x - w/2, no_counts, w, label="no_breaks=no", color="coral", edgecolor="black", linewidth=0.3)
327
+ ax.bar(x + w/2, yes_counts, w, label="no_breaks=yes", color="seagreen", edgecolor="black", linewidth=0.3)
328
+ ax.set_xticks(x)
329
+ ax.set_xticklabels([str(p) for p in pcs], rotation=45, ha="right")
330
+ ax.set_xlabel("Sequence identity cutoff (%)")
331
+ ax.set_ylabel("Number of chains")
332
+ ax.legend()
333
+ ax.set_title("Chains by pc and no_breaks")
334
+ plt.tight_layout()
335
+ plt.savefig(args.output_dir / f"chains_pc_no_breaks.{ext}", dpi=dpi, bbox_inches="tight")
336
+ plt.close()
337
+ print(f" Saved chains_pc_no_breaks.{ext}", file=sys.stderr)
338
+
339
+ # --- 7. Resolution vs length scatter (sampled) ---
340
+ if np and rows:
341
+ resols_all = [safe_float(r.get("resolution")) for r in rows]
342
+ lens_all = [safe_int(r.get("len")) for r in rows]
343
+ valid = [(r, l) for r, l in zip(resols_all, lens_all) if 0 < r < 20 and 0 < l < 100000]
344
+ if len(valid) > args.max_points_scatter:
345
+ rng = np.random.default_rng(42)
346
+ idx = rng.choice(len(valid), size=args.max_points_scatter, replace=False)
347
+ valid = [valid[i] for i in idx]
348
+ if valid:
349
+ res, le = zip(*valid)
350
+ fig, ax = plt.subplots(figsize=(6, 5))
351
+ ax.scatter(res, le, alpha=0.15, s=8, c="steelblue", edgecolors="none")
352
+ ax.set_xlabel("Resolution (Å)")
353
+ ax.set_ylabel("Sequence length")
354
+ ax.set_title("Resolution vs sequence length (sampled)")
355
+ plt.tight_layout()
356
+ plt.savefig(args.output_dir / f"resolution_vs_length.{ext}", dpi=dpi, bbox_inches="tight")
357
+ plt.close()
358
+ print(f" Saved resolution_vs_length.{ext}", file=sys.stderr)
359
+
360
+ print(f"Figures written to {args.output_dir}", file=sys.stderr)
361
+
362
+
363
+ if __name__ == "__main__":
364
+ main()