Upload src/03_filter_chain.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364#!/usr/bin/env python3"""Generate publication-style figures from CullPDB chain CSV(s).
Reads from a single combined CSV or from curated_csv/subset_chains/ (all CSVs merged).Saves figures to curated_csv/figures/.
Summary (after curation): - curation_summary.png: one-page dashboard with key stats + overview plots.
Individual plots: - Chains per pc, per method, no_breaks; resolution/length histograms; - Chains by (pc, no_breaks); resolution vs length scatter."""import csvimport sysfrom collections import defaultdictfrom pathlib import Pathfrom typing import Any, Dict, Iterator, List
SCRIPT_DIR = Path(__file__).resolve().parentBASE = SCRIPT_DIR.parentCURATED_DIR = BASE / "curated_csv"FIG_DIR = CURATED_DIR / "figures"
try: import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as pltexcept ImportError: print("matplotlib required: pip install matplotlib", file=sys.stderr) sys.exit(1)
try: import numpy as npexcept ImportError: np = None # will skip scatter / numeric bins where needed
def iter_rows(input_path: Path) -> Iterator[Dict[str, Any]]: """Yield rows from a single CSV or all CSVs in a directory.""" if input_path.is_file(): with open(input_path, newline="") as f: for row in csv.DictReader(f): yield row return for p in sorted(input_path.glob("*.csv")): with open(p, newline="") as f: for row in csv.DictReader(f): yield row
def safe_float(x: Any) -> float: try: return float(x) except (ValueError, TypeError): return float("nan")
def safe_int(x: Any) -> int: try: return int(float(x)) except (ValueError, TypeError): return 0
def main(): import argparse ap = argparse.ArgumentParser(description="Visualize CullPDB chain data.") ap.add_argument( "--input", "-i", type=Path, default=CURATED_DIR / "cullpdb_combined_chains.csv", help="Master chain CSV (default: curated_csv/cullpdb_combined_chains.csv)", ) ap.add_argument( "--output-dir", "-o", type=Path, default=FIG_DIR, help="Directory for output figures", ) ap.add_argument( "--format", default="png", choices=("png", "pdf", "svg"), help="Figure format", ) ap.add_argument( "--dpi", type=int, default=150, help="DPI for raster formats", ) ap.add_argument( "--max-points-scatter", type=int, default=10000, help="Max points in resolution vs length scatter (downsample if larger)", ) args = ap.parse_args()
if not args.input.exists(): print(f"Input not found: {args.input}", file=sys.stderr) sys.exit(1)
# Load data rows = list(iter_rows(args.input)) if not rows: print("No rows loaded.", file=sys.stderr) sys.exit(1)
print(f"Loaded {len(rows)} chains from {args.input}", file=sys.stderr) args.output_dir.mkdir(parents=True, exist_ok=True) ext = args.format dpi = args.dpi
# Try seaborn for style try: import seaborn as sns sns.set_theme(style="whitegrid", font_scale=1.1) palette = "colorblind" except ImportError: palette = None for style in ("seaborn-v0_8-whitegrid", "seaborn-whitegrid", "ggplot"): if style in plt.style.available: plt.style.use(style) break
# --- Single pass: collect all stats for summary + individual plots --- pc_counts = defaultdict(int) method_counts = defaultdict(int) nb_counts = defaultdict(int) pc_nb = defaultdict(lambda: defaultdict(int)) resols = [] lens = [] unique_sources = set() unique_pdbs = set() for r in rows: pc = safe_float(r.get("pc")) if np is not None and np.isnan(pc): pass else: pc_counts[pc] += 1 m = (r.get("method") or "").strip().upper() or "unknown" method_counts[m] += 1 nb = (r.get("no_breaks") or "").strip().lower() nb_key = "yes" if nb in ("yes", "y", "1", "true") else "no" nb_counts[nb_key] += 1 if np is not None and not np.isnan(pc): pc_nb[pc][nb_key] += 1 res = safe_float(r.get("resolution")) if res and (np is None or not np.isnan(res)) and 0 < res < 20: resols.append(res) le = safe_int(r.get("len")) if 0 < le < 100000: lens.append(le) src = (r.get("source_list") or "").strip() if src: unique_sources.add(src) pdb = (r.get("pdb") or "").strip() if pdb: unique_pdbs.add(pdb)
n_chains = len(rows) n_subsets = len(unique_sources) n_pdbs = len(unique_pdbs) res_median = float(np.median(resols)) if np and resols else (sorted(resols)[len(resols)//2] if resols else None) res_min = min(resols) if resols else None res_max = max(resols) if resols else None len_median = int(np.median(lens)) if np and lens else (sorted(lens)[len(lens)//2] if lens else None) len_min = min(lens) if lens else None len_max = max(lens) if lens else None
# --- Summary figure (one-page dashboard after curation) --- fig = plt.figure(figsize=(12, 10)) fig.suptitle("CullPDB curated dataset — summary", fontsize=14, fontweight="bold", y=0.98)
# Stats text panel ax_text = fig.add_subplot(3, 2, 1) ax_text.axis("off") stats_lines = [ "Dataset overview", "", f" Total chains: {n_chains:,}", f" Unique PDBs: {n_pdbs:,}", f" Subsets (lists): {n_subsets}", "", "Resolution (Å)", f" Min / Median / Max: {res_min:.2f} / {res_median:.2f} / {res_max:.2f}" if resols else " —", "", "Sequence length", f" Min / Median / Max: {len_min} / {len_median} / {len_max}" if lens else " —", ] ax_text.text(0.05, 0.95, "\n".join(stats_lines), transform=ax_text.transAxes, fontsize=11, verticalalignment="top", fontfamily="monospace", bbox=dict(boxstyle="round", facecolor="wheat", alpha=0.3))
# Chains per pc (compact) ax1 = fig.add_subplot(3, 2, 2) if pc_counts: pcs = sorted(pc_counts.keys()) counts = [pc_counts[p] for p in pcs] ax1.bar(range(len(pcs)), counts, color="steelblue", edgecolor="navy", linewidth=0.5) ax1.set_xticks(range(len(pcs))) ax1.set_xticklabels([str(p) for p in pcs], rotation=45, ha="right", fontsize=8) ax1.set_ylabel("Chains") ax1.set_title("Chains per pc (%)")
# Method (compact) ax2 = fig.add_subplot(3, 2, 3) if method_counts: methods = sorted(method_counts.keys(), key=lambda x: -method_counts[x]) counts = [method_counts[m] for m in methods] ax2.barh(methods, counts, color="teal", alpha=0.85, edgecolor="darkgreen", linewidth=0.3) ax2.set_xlabel("Chains") ax2.set_title("By method")
# no_breaks (compact) ax3 = fig.add_subplot(3, 2, 4) if nb_counts: labels = ["no", "yes"] counts = [nb_counts.get(l, 0) for l in labels] ax3.bar(labels, counts, color=["coral", "seagreen"], edgecolor="black", linewidth=0.5) ax3.set_ylabel("Chains") ax3.set_title("No breaks")
# Resolution histogram (compact) ax4 = fig.add_subplot(3, 2, 5) if resols: ax4.hist(resols, bins=40, color="steelblue", alpha=0.8, edgecolor="white", linewidth=0.2) ax4.set_xlabel("Resolution (Å)") ax4.set_ylabel("Chains") ax4.set_title("Resolution distribution")
# Length histogram (compact) ax5 = fig.add_subplot(3, 2, 6) if lens: ax5.hist(lens, bins=50, color="mediumpurple", alpha=0.8, edgecolor="white", linewidth=0.2) ax5.set_xlabel("Sequence length") ax5.set_ylabel("Chains") ax5.set_title("Length distribution")
plt.tight_layout(rect=[0, 0, 1, 0.96]) plt.savefig(args.output_dir / f"curation_summary.{ext}", dpi=dpi, bbox_inches="tight") plt.close() print(f" Saved curation_summary.{ext}", file=sys.stderr)
# --- 1. Chains per pc (bar) --- if pc_counts: pcs = sorted(pc_counts.keys()) counts = [pc_counts[p] for p in pcs] fig, ax = plt.subplots(figsize=(8, 4)) bars = ax.bar(range(len(pcs)), counts, color="steelblue", edgecolor="navy", linewidth=0.5) ax.set_xticks(range(len(pcs))) ax.set_xticklabels([str(p) for p in pcs], rotation=45, ha="right") ax.set_xlabel("Sequence identity cutoff (%)") ax.set_ylabel("Number of chains") ax.set_title("Chains per sequence identity cutoff (pc)") plt.tight_layout() plt.savefig(args.output_dir / f"chains_per_pc.{ext}", dpi=dpi, bbox_inches="tight") plt.close() print(f" Saved chains_per_pc.{ext}", file=sys.stderr)
# --- 2. Chains per method --- if method_counts: methods = sorted(method_counts.keys(), key=lambda x: -method_counts[x]) counts = [method_counts[m] for m in methods] fig, ax = plt.subplots(figsize=(6, 4)) ax.barh(methods, counts, color="teal", alpha=0.85, edgecolor="darkgreen", linewidth=0.5) ax.set_xlabel("Number of chains") ax.set_ylabel("Method") ax.set_title("Chains per method") plt.tight_layout() plt.savefig(args.output_dir / f"chains_per_method.{ext}", dpi=dpi, bbox_inches="tight") plt.close() print(f" Saved chains_per_method.{ext}", file=sys.stderr)
# --- 3. no_breaks yes vs no --- if nb_counts: labels = ["no", "yes"] counts = [nb_counts.get(l, 0) for l in labels] fig, ax = plt.subplots(figsize=(4, 4)) colors = ["coral", "seagreen"] if palette is None else plt.cm.tab10.colors[:2] ax.bar(labels, counts, color=colors, edgecolor="black", linewidth=0.5) ax.set_ylabel("Number of chains") ax.set_xlabel("No breaks") ax.set_title("Chains by no_breaks filter") plt.tight_layout() plt.savefig(args.output_dir / f"chains_no_breaks.{ext}", dpi=dpi, bbox_inches="tight") plt.close() print(f" Saved chains_no_breaks.{ext}", file=sys.stderr)
# --- 4. Resolution histogram --- if resols: fig, ax = plt.subplots(figsize=(6, 4)) ax.hist(resols, bins=50, color="steelblue", alpha=0.8, edgecolor="white", linewidth=0.3) ax.set_xlabel("Resolution (Å)") ax.set_ylabel("Number of chains") ax.set_title("Resolution distribution") plt.tight_layout() plt.savefig(args.output_dir / f"resolution_hist.{ext}", dpi=dpi, bbox_inches="tight") plt.close() print(f" Saved resolution_hist.{ext}", file=sys.stderr)
# --- 5. Sequence length histogram --- if lens: fig, ax = plt.subplots(figsize=(6, 4)) ax.hist(lens, bins=60, color="mediumpurple", alpha=0.8, edgecolor="white", linewidth=0.3) ax.set_xlabel("Sequence length") ax.set_ylabel("Number of chains") ax.set_title("Sequence length distribution") plt.tight_layout() plt.savefig(args.output_dir / f"length_hist.{ext}", dpi=dpi, bbox_inches="tight") plt.close() print(f" Saved length_hist.{ext}", file=sys.stderr)
# --- 6. Chain count by (pc, no_breaks) grouped bar --- if pc_nb: pcs = sorted(pc_nb.keys()) yes_counts = [pc_nb[p]["yes"] for p in pcs] no_counts = [pc_nb[p]["no"] for p in pcs] n = len(pcs) x = np.arange(n) if np is not None else list(range(n)) w = 0.35 fig, ax = plt.subplots(figsize=(10, 4)) ax.bar(x - w/2, no_counts, w, label="no_breaks=no", color="coral", edgecolor="black", linewidth=0.3) ax.bar(x + w/2, yes_counts, w, label="no_breaks=yes", color="seagreen", edgecolor="black", linewidth=0.3) ax.set_xticks(x) ax.set_xticklabels([str(p) for p in pcs], rotation=45, ha="right") ax.set_xlabel("Sequence identity cutoff (%)") ax.set_ylabel("Number of chains") ax.legend() ax.set_title("Chains by pc and no_breaks") plt.tight_layout() plt.savefig(args.output_dir / f"chains_pc_no_breaks.{ext}", dpi=dpi, bbox_inches="tight") plt.close() print(f" Saved chains_pc_no_breaks.{ext}", file=sys.stderr)
# --- 7. Resolution vs length scatter (sampled) --- if np and rows: resols_all = [safe_float(r.get("resolution")) for r in rows] lens_all = [safe_int(r.get("len")) for r in rows] valid = [(r, l) for r, l in zip(resols_all, lens_all) if 0 < r < 20 and 0 < l < 100000] if len(valid) > args.max_points_scatter: rng = np.random.default_rng(42) idx = rng.choice(len(valid), size=args.max_points_scatter, replace=False) valid = [valid[i] for i in idx] if valid: res, le = zip(*valid) fig, ax = plt.subplots(figsize=(6, 5)) ax.scatter(res, le, alpha=0.15, s=8, c="steelblue", edgecolors="none") ax.set_xlabel("Resolution (Å)") ax.set_ylabel("Sequence length") ax.set_title("Resolution vs sequence length (sampled)") plt.tight_layout() plt.savefig(args.output_dir / f"resolution_vs_length.{ext}", dpi=dpi, bbox_inches="tight") plt.close() print(f" Saved resolution_vs_length.{ext}", file=sys.stderr)
print(f"Figures written to {args.output_dir}", file=sys.stderr)
if __name__ == "__main__": main()src/03_filter_chain.pyAdded+364