Download run_mpnn_af2.py from YangyangMiao1998/DiffTopo: direct link, hf CLI and curl.
- Browser
- Download file 9.6 kB
-
https://huggingface.co/YangyangMiao1998/DiffTopo/resolve/main/run_mpnn_af2.py
- Command line
-
hf download hf://YangyangMiao1998/DiffTopo/run_mpnn_af2.py
-
curl -L -o run_mpnn_af2.py https://huggingface.co/YangyangMiao1998/DiffTopo/resolve/main/run_mpnn_af2.py
9.6 kB
| import sys | |
| import os | |
| import re | |
| import warnings | |
| import argparse | |
| import time | |
| import jax | |
| import jax.numpy as jnp | |
| import numpy as np | |
| import matplotlib.pyplot as plt | |
| import pandas as pd | |
| import tqdm | |
| # Suppress future warnings | |
| warnings.simplefilter(action='ignore', category=FutureWarning) | |
| # Progress bar format | |
| TQDM_BAR_FORMAT = '{l_bar}{bar}| {n_fmt}/{total_fmt} [elapsed: {elapsed} remaining: {remaining}]' | |
| def setup_colabdesign(colabdesign_path): | |
| """Add ColabDesign to system path and import required modules""" | |
| sys.path.append(colabdesign_path) | |
| import colabdesign | |
| from colabdesign.mpnn import mk_mpnn_model, clear_mem | |
| from colabdesign.shared.protein import pdb_to_string | |
| from colabdesign.mpnn.model import aa_order | |
| from colabdesign.af import mk_af_model | |
| return mk_mpnn_model, mk_af_model, aa_order | |
| def parse_arguments(): | |
| """Parse command line arguments""" | |
| parser = argparse.ArgumentParser( | |
| formatter_class=argparse.ArgumentDefaultsHelpFormatter, | |
| description="ProteinMPNN design pipeline with AlphaFold2 validation" | |
| ) | |
| # Required paths | |
| parser.add_argument("--colabdesign_path", type=str, required=True, | |
| help="Path to ColabDesign installation") | |
| parser.add_argument("--designpdb", type=str, required=True, | |
| help="PDB file path for MPNN design") | |
| parser.add_argument("--template", type=str, default="", | |
| help="Template PDB file for AF2 prediction (leave empty to run without template)") | |
| parser.add_argument("--no_template", action='store_true', | |
| help="Run AF2 without structural template") | |
| parser.add_argument("--outdir", type=str, default="./output", | |
| help="Output directory") | |
| # Design constraints | |
| parser.add_argument("--fixpos", type=str, default="", | |
| help="Residue indices to fix (e.g., '23 24 27 28 30 31')") | |
| parser.add_argument("--template_chains", type=str, default="A", | |
| help="Template chains for AF2 prediction (e.g., 'A,B,C')") | |
| # MPNN options | |
| parser.add_argument("--seqnum", type=int, default=32, | |
| help="Number of sequences to design") | |
| parser.add_argument("--temp", type=float, default=0.1, | |
| help="Sampling temperature (0.0=argmax, >1.0=random)") | |
| parser.add_argument("--modelname", type=str, default='v_48_020', | |
| choices=['v_48_002', 'v_48_010', 'v_48_020', 'v_48_030'], | |
| help="ProteinMPNN model version") | |
| parser.add_argument("--bias", action='store_true', | |
| help="Add bias for polar/charged amino acids") | |
| parser.add_argument("--penala", action='store_true', | |
| help="Penalize alanine in design") | |
| # AF2 options | |
| parser.add_argument("--num_recycles", type=int, default=3, | |
| help="Number of recycles for AF2 prediction") | |
| parser.add_argument("--af2_params", type=str, | |
| default="/content/af2_params", | |
| help="Path to AF2 parameters") | |
| return parser.parse_args() | |
| def prepare_output_directory(outdir): | |
| """Create output directory structure""" | |
| os.makedirs(outdir, exist_ok=True) | |
| pdb_dir = os.path.join(outdir, "all_pdb") | |
| if os.path.isdir(pdb_dir): | |
| os.system(f"rm -f {pdb_dir}/*") | |
| else: | |
| os.makedirs(pdb_dir) | |
| return pdb_dir | |
| def run_mpnn_design(mpnn_model, aa_order, args, pdb_path): | |
| """Run ProteinMPNN sequence design""" | |
| # Parse design constraints | |
| chains = "A" | |
| homooligomer = True | |
| inverse = True | |
| rm_aa = "C" | |
| # Clean up fix_pos format | |
| fix_pos = None | |
| if args.fixpos: | |
| fix_pos = ','.join(args.fixpos.split()) | |
| # Clean up amino acids to remove | |
| rm_aa = ",".join(list(re.sub("[^A-Z]+", "", rm_aa.upper()))) | |
| if not rm_aa: | |
| rm_aa = None | |
| # Prepare MPNN inputs | |
| mpnn_model.prep_inputs( | |
| pdb_filename=pdb_path, | |
| chain=chains, | |
| homooligomer=homooligomer, | |
| fix_pos=fix_pos, | |
| inverse=inverse, | |
| rm_aa=rm_aa, | |
| verbose=True | |
| ) | |
| # Apply amino acid biases if requested | |
| if args.bias: | |
| # Add bias for polar and charged amino acids | |
| for aa in "DEHKNQRSTWY": | |
| mpnn_model._inputs["bias"][:, aa_order[aa]] += 1.39 | |
| if args.penala: | |
| # Penalize alanine | |
| mpnn_model._inputs["bias"][:, aa_order['A']] -= 0.5 | |
| # Sample sequences | |
| batch = min(32, args.seqnum) | |
| num = max(1, args.seqnum // batch) | |
| out = mpnn_model.sample( | |
| num=num, | |
| batch=batch, | |
| temperature=args.temp, | |
| rescore=homooligomer | |
| ) | |
| return out | |
| def save_mpnn_results(out, outdir, num_seqs): | |
| """Save MPNN design results to FASTA and CSV""" | |
| # Save FASTA file | |
| fasta_path = os.path.join(outdir, "design.fasta") | |
| with open(fasta_path, "w") as fasta: | |
| for n in range(num_seqs): | |
| line = f'>score:{out["score"][n]:.3f}_seqid:{out["seqid"][n]:.3f}\n{out["seq"][n]}' | |
| fasta.write(line + "\n") | |
| # Save CSV file | |
| labels = ["score", "seqid", "seq"] | |
| data = [[out[k][n] for k in labels] for n in range(num_seqs)] | |
| df = pd.DataFrame(data, columns=labels) | |
| csv_path = os.path.join(outdir, 'mpnn_results.csv') | |
| df.to_csv(csv_path, index=False) | |
| print(f"MPNN results saved to {fasta_path} and {csv_path}") | |
| def run_alphafold_validation(af_model, out, args, pdb_dir): | |
| """Run AlphaFold2 validation on designed sequences""" | |
| data = [] | |
| labels = ["dgram_cce", "plddt", "ptm", "i_ptm", "rmsd", "composite", | |
| "mpnn_score", "seqid", "seq"] | |
| t0 = time.time() | |
| with tqdm.tqdm(total=out["S"].shape[0], bar_format=TQDM_BAR_FORMAT) as pbar: | |
| for n, S in enumerate(out["S"]): | |
| # Extract sequence | |
| seq = S[:af_model._len].argmax(-1) | |
| # Run AF2 prediction | |
| af_model.predict( | |
| seq=seq, | |
| num_recycles=args.num_recycles, | |
| models=[0, 1], | |
| num_models=2, | |
| verbose=False | |
| ) | |
| # Calculate composite score | |
| af_model.aux["log"]["composite"] = ( | |
| af_model.aux["log"]["ptm"] * af_model.aux["log"]["plddt"] | |
| ) | |
| # Save results | |
| af_model._save_results(save_best=True, verbose=False) | |
| af_model.save_current_pdb(os.path.join(pdb_dir, f"n{n}.pdb")) | |
| af_model._k += 1 | |
| # Collect metrics | |
| af = af_model._tmp["log"][n] | |
| data.append([ | |
| af["dgram_cce"], | |
| af["plddt"], | |
| af["ptm"], | |
| af["i_ptm"], | |
| af["rmsd"], | |
| af["composite"], | |
| out["score"][n], | |
| out["seqid"][n], | |
| out["seq"][n] | |
| ]) | |
| # Save intermediate results | |
| df = pd.DataFrame(data, columns=labels) | |
| csv_path = os.path.join(args.outdir, 'alphafold_results.csv') | |
| df.to_csv(csv_path, index=False) | |
| # Update progress | |
| elapsed = time.time() - t0 | |
| print(f'Round {n} completed in {elapsed:.2f}s') | |
| t0 = time.time() | |
| pbar.update(1) | |
| # Save best structure | |
| best_pdb = os.path.join(args.outdir, "best.pdb") | |
| af_model.save_pdb(best_pdb) | |
| print(f"Best structure saved to {best_pdb}") | |
| return data | |
| def main(): | |
| """Main pipeline execution""" | |
| # Parse arguments | |
| args = parse_arguments() | |
| # Setup ColabDesign | |
| print("Setting up ColabDesign...") | |
| mk_mpnn_model, mk_af_model, aa_order = setup_colabdesign(args.colabdesign_path) | |
| # Prepare output directory | |
| print(f"Preparing output directory: {args.outdir}") | |
| pdb_dir = prepare_output_directory(args.outdir) | |
| # Initialize MPNN model | |
| print(f"Initializing ProteinMPNN model: {args.modelname}") | |
| mpnn_model = mk_mpnn_model(args.modelname) | |
| # Run MPNN design | |
| print(f"Running ProteinMPNN design on {args.designpdb}...") | |
| mpnn_out = run_mpnn_design(mpnn_model, aa_order, args, args.designpdb) | |
| # Save MPNN results | |
| save_mpnn_results(mpnn_out, args.outdir, args.seqnum) | |
| # Initialize AlphaFold model | |
| use_template = not args.no_template and bool(args.template) | |
| print(f"Initializing AlphaFold2 model (use_templates={use_template})...") | |
| af_model = mk_af_model( | |
| protocol='fixbb', | |
| use_multimer=False, | |
| use_templates=use_template, | |
| use_bfloat16=True, | |
| data_dir=args.af2_params | |
| ) | |
| # Prepare AF2 inputs | |
| if use_template: | |
| print(f"Preparing AF2 with template: {args.template}") | |
| af_model.prep_inputs( | |
| args.template, | |
| args.template_chains, | |
| homooligomer=True | |
| ) | |
| af_model.set_opt("template", rm_ic=False) | |
| else: | |
| print(f"Preparing AF2 without template, using sequence length from: {args.designpdb}") | |
| af_model.prep_inputs( | |
| args.designpdb, | |
| "A", | |
| homooligomer=True | |
| ) | |
| # Run AlphaFold validation | |
| print("Running AlphaFold2 validation...") | |
| af_results = run_alphafold_validation(af_model, mpnn_out, args, pdb_dir) | |
| print("\nPipeline completed successfully!") | |
| print(f"Results saved to: {args.outdir}") | |
| if __name__ == "__main__": | |
| main() |