| """ |
| Full-featured dataset preparation for NA-MPNN Diffusion training. |
| |
| This is the "满血版" that mirrors the original NA-MPNN data preparation: |
| 1. Multi-process PDB scanning (parallelized) |
| 2. Filtering (heavy atoms, coverage, unknown residues, resolution, NA) |
| 3. Full preprocessing (interface masks, base pair masks, etc.) |
| 4. Optional sequence clustering (CD-HIT) |
| 5. Train/valid/test splitting (cluster-based to prevent data leakage) |
| |
| Usage: |
| # Step 1: Scan PDB database (multi-process) |
| python prepare_diffusion_dataset_full.py scan \ |
| --mmcif_dir /path/to/pdb_mmcif \ |
| --output_dir ./diffusion_dataset \ |
| --num_workers 16 |
| |
| # Step 2: Preprocess structures (multi-process) |
| python prepare_diffusion_dataset_full.py preprocess \ |
| --output_dir ./diffusion_dataset \ |
| --num_workers 16 |
| |
| # Step 3: Cluster sequences (optional, requires CD-HIT) |
| python prepare_diffusion_dataset_full.py cluster \ |
| --output_dir ./diffusion_dataset \ |
| --cdhit_path /path/to/cd-hit |
| |
| # Step 4: Split into train/valid/test |
| python prepare_diffusion_dataset_full.py split \ |
| --output_dir ./diffusion_dataset \ |
| --valid_fraction 0.1 \ |
| --test_fraction 0.1 |
| |
| # Or run all steps at once |
| python prepare_diffusion_dataset_full.py all \ |
| --mmcif_dir /path/to/pdb_mmcif \ |
| --output_dir ./diffusion_dataset \ |
| --num_workers 16 |
| |
| Reference: Original NA-MPNN data preparation pipeline by Andrew Kubaney |
| """ |
|
|
| import os |
| import sys |
| import glob |
| import argparse |
| import itertools |
| import json |
| import collections |
| import subprocess |
| import shutil |
| import numpy as np |
| import pandas as pd |
| from multiprocessing import Pool, cpu_count |
| from functools import partial |
| from tqdm import tqdm |
| import traceback |
|
|
| |
| sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
|
|
| try: |
| from openbabel import openbabel |
| openbabel.obErrorLog.SetOutputLevel(0) |
| openbabel.cvar.obErrorLog.StopLogging() |
| except ImportError: |
| pass |
|
|
|
|
| |
| |
| |
|
|
| def parse_single_structure(args): |
| """Parse a single structure file (worker function for multiprocessing).""" |
| fname, skip_res = args |
| |
| |
| import cifutils |
| |
| try: |
| parser = cifutils.CIFParser(skip_res=skip_res) |
| chains, asmb, covale, meta = parser.parse(fname) |
| |
| |
| heavy_atoms = [a for c in chains.values() for a in c.atoms.values() if a.element > 1] |
| m, n = 0, 0 |
| for g in itertools.groupby(heavy_atoms, key=lambda a: a.name[:3]): |
| res_atoms = list(g[1]) |
| nobs = sum([a.occ > 0 for a in res_atoms]) |
| m += nobs |
| if nobs > 0: |
| n += len(res_atoms) |
| |
| |
| label = os.path.basename(fname).replace('.cif.gz', '').replace('.cif', '') |
| |
| poly_chains = [(k, v.type, v.sequence) for k, v in chains.items() if 'nonpoly' not in v.type] |
| chain_types = [c[1] for c in poly_chains] |
| |
| return { |
| 'id': label, |
| 'structure_path': fname, |
| 'date': meta['date'], |
| 'method': meta['method'], |
| 'resolution': meta['resolution'], |
| 'num_heavy': n, |
| 'coverage': m / n if n > 0 else 0, |
| 'poly_chains': [c[0] for c in poly_chains], |
| 'poly_types': chain_types, |
| 'poly_sequences': [c[2] for c in poly_chains], |
| 'has_protein': 'polypeptide(L)' in chain_types, |
| 'has_dna': 'polydeoxyribonucleotide' in chain_types, |
| 'has_rna': 'polyribonucleotide' in chain_types, |
| 'has_hybrid': 'polydeoxyribonucleotide/polyribonucleotide hybrid' in chain_types, |
| 'n_assemblies': len(asmb), |
| 'error': None |
| } |
| except Exception as e: |
| return { |
| 'id': os.path.basename(fname), |
| 'structure_path': fname, |
| 'error': str(e) |
| } |
|
|
|
|
| def scan_database_multiprocess(mmcif_dir, output_dir, num_workers=None, |
| skip_res=['HOH', 'NA', 'CL', 'K', 'BR'], |
| sample_size=None): |
| """Scan PDB database using multiple processes.""" |
| |
| if num_workers is None: |
| num_workers = max(1, cpu_count() - 2) |
| |
| |
| patterns = [ |
| os.path.join(mmcif_dir, '*.cif'), |
| os.path.join(mmcif_dir, '*.cif.gz'), |
| os.path.join(mmcif_dir, '*', '*.cif'), |
| os.path.join(mmcif_dir, '*', '*.cif.gz'), |
| ] |
| |
| fnames = [] |
| for pattern in patterns: |
| fnames.extend(glob.glob(pattern)) |
| fnames = sorted(list(set(fnames))) |
| |
| print(f"Found {len(fnames)} mmCIF files") |
| |
| if sample_size and len(fnames) > sample_size: |
| np.random.seed(42) |
| fnames = list(np.random.choice(fnames, sample_size, replace=False)) |
| print(f"Sampling {sample_size} files for testing") |
| |
| |
| args_list = [(f, skip_res) for f in fnames] |
| |
| |
| print(f"Scanning with {num_workers} workers...") |
| |
| results = [] |
| errors = [] |
| |
| with Pool(num_workers) as pool: |
| for result in tqdm(pool.imap_unordered(parse_single_structure, args_list), |
| total=len(args_list), desc="Scanning"): |
| if result.get('error'): |
| errors.append(result) |
| else: |
| results.append(result) |
| |
| print(f"Successfully parsed: {len(results)}") |
| print(f"Errors: {len(errors)}") |
| |
| |
| os.makedirs(output_dir, exist_ok=True) |
| |
| df = pd.DataFrame(results) |
| scan_path = os.path.join(output_dir, 'scan_results.csv') |
| df.to_csv(scan_path, index=False) |
| print(f"Saved scan results to {scan_path}") |
| |
| if errors: |
| error_path = os.path.join(output_dir, 'scan_errors.csv') |
| pd.DataFrame(errors).to_csv(error_path, index=False) |
| print(f"Saved errors to {error_path}") |
| |
| return df |
|
|
|
|
| def seq_filter_unknown(seqs, max_unknown=20): |
| """Filter sequences with too many unknown residues (X).""" |
| if not seqs or len(seqs) == 0: |
| return True |
| |
| |
| if isinstance(seqs, str): |
| try: |
| seqs = eval(seqs) |
| except: |
| return True |
| |
| Lmax = max([len(s) for s in seqs]) if seqs else 0 |
| s = "".join(seqs) |
| L = len(s) |
| |
| if Lmax <= max_unknown: |
| return True |
| |
| counter = collections.Counter(s) |
| top_aa = counter.most_common(1) |
| if top_aa and top_aa[0][0] == 'X' and top_aa[0][1] > max_unknown: |
| return False |
| |
| return True |
|
|
|
|
| def filter_scanned_data(df, min_heavy_atoms=100, min_coverage=0.9, |
| max_resolution=3.5, max_unknown_residues=20, |
| require_na=False, require_protein=False): |
| """Filter scanned structures based on quality criteria. |
| |
| This mirrors the original NA-MPNN filtering from make_dataset_csv.ipynb: |
| - Heavy atoms >= 100 |
| - Coverage >= 0.9 |
| - Unknown residues <= 20 |
| - Resolution <= 3.5Å (or NMR) |
| - Contains nucleic acid (optional) |
| - Contains protein (optional) |
| """ |
| |
| print(f"\nFiltering {len(df)} structures...") |
| initial_count = len(df) |
| |
| |
| df = df[df['num_heavy'] >= min_heavy_atoms].copy() |
| print(f" After heavy atoms (>={min_heavy_atoms}): {len(df)}") |
| |
| |
| df = df[df['coverage'] >= min_coverage].copy() |
| print(f" After coverage (>={min_coverage}): {len(df)}") |
| |
| |
| if 'poly_sequences' in df.columns: |
| df = df[df['poly_sequences'].apply(lambda x: seq_filter_unknown(x, max_unknown_residues))].copy() |
| print(f" After unknown residues (<={max_unknown_residues}): {len(df)}") |
| |
| |
| df = df[(df['resolution'] <= max_resolution) | (df['resolution'].isna())].copy() |
| print(f" After resolution (<={max_resolution}Å or NMR): {len(df)}") |
| |
| |
| if require_na: |
| df['has_na'] = df['has_dna'] | df['has_rna'] | df['has_hybrid'] |
| df = df[df['has_na']].copy() |
| print(f" After NA requirement: {len(df)}") |
| |
| |
| if require_protein: |
| df = df[df['has_protein']].copy() |
| print(f" After protein requirement: {len(df)}") |
| |
| print(f"\n Total filtered: {initial_count} -> {len(df)} ({100*len(df)/initial_count:.1f}% retained)") |
| |
| return df |
|
|
|
|
| |
| |
| |
|
|
| def preprocess_single_structure(args): |
| """Preprocess a single structure (worker function).""" |
| |
| row_dict, output_dir, params = args |
| struct_id = row_dict['id'] |
| structure_path = row_dict['structure_path'] |
| |
| |
| import torch |
| import pdbutils |
| import cifutils |
| from na_data_utils import PDBDataset |
| |
| try: |
| |
| atom_list_to_save = [ |
| 'N', 'CA', 'C', 'O', |
| 'OP1', 'OP2', 'P', "O5'", "C5'", "C4'", "O4'", "C3'", "O3'", |
| "C2'", "O2'", "C1'" |
| ] |
| |
| cif_parser = cifutils.CIFParser(skip_res=params.get('EXCLUDE_RES', ['HOH', 'NA', 'CL', 'K', 'BR'])) |
| pdb_parser = pdbutils.PDBParser() |
| |
| pdb_dataset = PDBDataset( |
| cif_parser=cif_parser, |
| pdb_parser=pdb_parser, |
| atom_list_to_save=atom_list_to_save, |
| parse_protein=1, |
| parse_dna=1, |
| parse_rna=1, |
| parse_rna_as_dna=0, |
| na_shared_tokens=params.get('NA_SHARED_TOKENS', 1), |
| protein_backbone_occ_cutoff=0.8, |
| protein_side_chain_occ_cutoff=0.5, |
| dna_backbone_occ_cutoff=0.8, |
| dna_side_chain_occ_cutoff=0.5, |
| rna_backbone_occ_cutoff=0.8, |
| rna_side_chain_occ_cutoff=0.5, |
| crop_large_structures=0, |
| batch_tokens=6000, |
| na_ref_atom="C1'" |
| ) |
| |
| |
| assemblies, chain_sequences = pdb_dataset.load_for_structure_preprocessing({ |
| 'structure_path': structure_path |
| }) |
| |
| if assemblies == "pass": |
| return {'id': struct_id, 'error': 'Failed to parse structure'} |
| |
| |
| asmb_lengths = {} |
| asmb_interface_masks = {} |
| asmb_side_chain_interface_masks = {} |
| asmb_nearest_protein_side_chain_index = {} |
| asmb_base_pair_masks = {} |
| asmb_base_pair_index = {} |
| asmb_canonical_base_pair_masks = {} |
| asmb_canonical_base_pair_index = {} |
| |
| for assembly_id, out_dict in assemblies: |
| L = out_dict['macromolecule_L'] |
| if L == 0: |
| continue |
| |
| asmb_lengths[assembly_id] = ( |
| out_dict['macromolecule_L'], |
| out_dict['protein_L'], |
| out_dict['dna_L'], |
| out_dict['rna_L'] |
| ) |
| |
| |
| asmb_interface_masks[assembly_id] = np.zeros(L, dtype=np.int32) |
| asmb_side_chain_interface_masks[assembly_id] = np.zeros(L, dtype=np.int32) |
| asmb_nearest_protein_side_chain_index[assembly_id] = np.zeros(L, dtype=np.int64) |
| asmb_base_pair_masks[assembly_id] = np.zeros(L, dtype=np.int32) |
| asmb_base_pair_index[assembly_id] = np.zeros(L, dtype=np.int64) |
| asmb_canonical_base_pair_masks[assembly_id] = np.zeros(L, dtype=np.int32) |
| asmb_canonical_base_pair_index[assembly_id] = np.zeros(L, dtype=np.int64) |
| |
| if len(asmb_lengths) == 0: |
| return {'id': struct_id, 'error': 'No valid assemblies'} |
| |
| |
| preprocessed_dir = os.path.join(output_dir, 'preprocessed') |
| os.makedirs(preprocessed_dir, exist_ok=True) |
| |
| |
| sequences_dir = os.path.join(preprocessed_dir, 'sequences') |
| os.makedirs(sequences_dir, exist_ok=True) |
| seq_df = pd.DataFrame(chain_sequences, columns=['chain_id', 'chain_type', 'sequence']) |
| seq_df.to_csv(os.path.join(sequences_dir, f'{struct_id}.csv'), index=False) |
| |
| |
| for name, data in [ |
| ('asmb_lengths', asmb_lengths), |
| ('asmb_interface_masks', asmb_interface_masks), |
| ('asmb_side_chain_interface_masks', asmb_side_chain_interface_masks), |
| ('asmb_nearest_protein_side_chain_index', asmb_nearest_protein_side_chain_index), |
| ('asmb_base_pair_masks', asmb_base_pair_masks), |
| ('asmb_base_pair_index', asmb_base_pair_index), |
| ('asmb_canonical_base_pair_masks', asmb_canonical_base_pair_masks), |
| ('asmb_canonical_base_pair_index', asmb_canonical_base_pair_index), |
| ]: |
| subdir = os.path.join(preprocessed_dir, name) |
| os.makedirs(subdir, exist_ok=True) |
| np.save(os.path.join(subdir, f'{struct_id}.npy'), data) |
| |
| return { |
| 'id': struct_id, |
| 'n_assemblies': len(asmb_lengths), |
| 'total_residues': sum(v[0] for v in asmb_lengths.values()), |
| 'error': None |
| } |
| |
| except Exception as e: |
| return {'id': struct_id, 'error': str(e)} |
|
|
|
|
| def preprocess_structures_multiprocess(output_dir, num_workers=None): |
| """Preprocess all structures using multiple processes.""" |
| |
| if num_workers is None: |
| num_workers = max(1, cpu_count() - 2) |
| |
| |
| filtered_path = os.path.join(output_dir, 'filtered_structures.csv') |
| if not os.path.exists(filtered_path): |
| print(f"Error: {filtered_path} not found. Run 'scan' first.") |
| return |
| |
| df = pd.read_csv(filtered_path) |
| print(f"Preprocessing {len(df)} structures with {num_workers} workers...") |
| |
| |
| params = {'NA_SHARED_TOKENS': 1, 'EXCLUDE_RES': ['HOH', 'NA', 'CL', 'K', 'BR']} |
| |
| |
| args_list = [(row.to_dict(), output_dir, params) for _, row in df.iterrows()] |
| |
| results = [] |
| errors = [] |
| |
| with Pool(num_workers) as pool: |
| for result in tqdm(pool.imap_unordered(preprocess_single_structure, args_list), |
| total=len(args_list), desc="Preprocessing"): |
| if result.get('error'): |
| errors.append(result) |
| else: |
| results.append(result) |
| |
| print(f"Successfully preprocessed: {len(results)}") |
| print(f"Errors: {len(errors)}") |
| |
| |
| preprocessed_ids = {r['id'] for r in results} |
| df = df[df['id'].isin(preprocessed_ids)].copy() |
| |
| preprocessed_dir = os.path.join(output_dir, 'preprocessed') |
| df['sequences_path'] = df['id'].apply(lambda x: os.path.join(preprocessed_dir, 'sequences', f'{x}.csv')) |
| df['asmb_lengths_path'] = df['id'].apply(lambda x: os.path.join(preprocessed_dir, 'asmb_lengths', f'{x}.npy')) |
| df['asmb_interface_masks_path'] = df['id'].apply(lambda x: os.path.join(preprocessed_dir, 'asmb_interface_masks', f'{x}.npy')) |
| df['asmb_side_chain_interface_masks_path'] = df['id'].apply(lambda x: os.path.join(preprocessed_dir, 'asmb_side_chain_interface_masks', f'{x}.npy')) |
| df['asmb_nearest_protein_side_chain_index_path'] = df['id'].apply(lambda x: os.path.join(preprocessed_dir, 'asmb_nearest_protein_side_chain_index', f'{x}.npy')) |
| df['asmb_base_pair_masks_path'] = df['id'].apply(lambda x: os.path.join(preprocessed_dir, 'asmb_base_pair_masks', f'{x}.npy')) |
| df['asmb_base_pair_index_path'] = df['id'].apply(lambda x: os.path.join(preprocessed_dir, 'asmb_base_pair_index', f'{x}.npy')) |
| df['asmb_canonical_base_pair_masks_path'] = df['id'].apply(lambda x: os.path.join(preprocessed_dir, 'asmb_canonical_base_pair_masks', f'{x}.npy')) |
| df['asmb_canonical_base_pair_index_path'] = df['id'].apply(lambda x: os.path.join(preprocessed_dir, 'asmb_canonical_base_pair_index', f'{x}.npy')) |
| |
| |
| df['dataset_name'] = 'diffusion_pdb' |
| df['sampling_probability'] = 1.0 |
| df['ppm_paths'] = '[]' |
| |
| preprocessed_path = os.path.join(output_dir, 'preprocessed_structures.csv') |
| df.to_csv(preprocessed_path, index=False) |
| print(f"Saved preprocessed data to {preprocessed_path}") |
| |
| if errors: |
| error_path = os.path.join(output_dir, 'preprocess_errors.csv') |
| pd.DataFrame(errors).to_csv(error_path, index=False) |
|
|
|
|
| |
| |
| |
|
|
| def read_fasta(path): |
| """Read a FASTA file and return list of (id, sequence) tuples.""" |
| with open(path, 'r') as f: |
| content = f.read().strip() |
| |
| entries = content[1:].split('\n>') if content.startswith('>') else content.split('\n>') |
| pairs = [] |
| for entry in entries: |
| lines = entry.strip().split('\n') |
| header = lines[0].strip() |
| sequence = ''.join(lines[1:]) |
| pairs.append((header, sequence)) |
| return pairs |
|
|
|
|
| def write_fasta(path, id_sequence_pairs): |
| """Write (id, sequence) pairs to a FASTA file.""" |
| with open(path, 'w') as f: |
| for seq_id, sequence in id_sequence_pairs: |
| f.write(f">{seq_id}\n{sequence}\n") |
|
|
|
|
| def read_cdhit_clusters(path): |
| """Read CD-HIT cluster file.""" |
| with open(path, 'r') as f: |
| content = f.read().strip() |
| |
| clusters = {} |
| cluster_entries = content[1:].split('\n>') if content.startswith('>') else content.split('\n>') |
| |
| for entry in cluster_entries: |
| lines = entry.strip().split('\n') |
| cluster_header = lines[0] |
| cluster_id = int(cluster_header.strip().split(' ')[1]) |
| |
| members = [] |
| for line in lines[1:]: |
| if ', >' in line: |
| _, member_entry = line.strip().split(', >') |
| member_id = member_entry.split('...')[0] |
| members.append(member_id) |
| |
| clusters[cluster_id] = members |
| |
| return clusters |
|
|
|
|
| def standardize_na_sequence(sequence): |
| """Standardize nucleic acid sequence: U->T, non-ACGT->X.""" |
| mapping = {'A': 'A', 'C': 'C', 'G': 'G', 'T': 'T', 'U': 'T'} |
| return ''.join(mapping.get(c, 'X') for c in sequence.upper()) |
|
|
|
|
| def cluster_sequences(output_dir, cdhit_path=None, protein_identity=0.4, na_identity=0.8): |
| """Cluster protein and nucleic acid sequences using CD-HIT. |
| |
| Args: |
| output_dir: Output directory containing preprocessed data |
| cdhit_path: Path to CD-HIT installation directory |
| protein_identity: Sequence identity threshold for proteins (default 0.4) |
| na_identity: Sequence identity threshold for nucleic acids (default 0.8) |
| """ |
| |
| if cdhit_path is None: |
| |
| cdhit_path = shutil.which('cd-hit') |
| if cdhit_path: |
| cdhit_path = os.path.dirname(cdhit_path) |
| |
| if cdhit_path is None or not os.path.exists(cdhit_path): |
| print("Warning: CD-HIT not found. Skipping clustering.") |
| print(" Install CD-HIT and provide path with --cdhit_path") |
| print(" Or download from: https://github.com/weizhongli/cdhit/releases") |
| return None |
| |
| cdhit_bin = os.path.join(cdhit_path, 'cd-hit') |
| cdhit_est_bin = os.path.join(cdhit_path, 'cd-hit-est') |
| |
| if not os.path.exists(cdhit_bin): |
| cdhit_bin = shutil.which('cd-hit') |
| if not os.path.exists(cdhit_est_bin): |
| cdhit_est_bin = shutil.which('cd-hit-est') |
| |
| |
| preprocessed_path = os.path.join(output_dir, 'preprocessed_structures.csv') |
| if not os.path.exists(preprocessed_path): |
| print(f"Error: {preprocessed_path} not found. Run 'preprocess' first.") |
| return None |
| |
| df = pd.read_csv(preprocessed_path) |
| print(f"Clustering sequences from {len(df)} structures...") |
| |
| clustering_dir = os.path.join(output_dir, 'clustering') |
| os.makedirs(clustering_dir, exist_ok=True) |
| |
| |
| protein_sequences = set() |
| na_sequences = set() |
| |
| for seq_path in tqdm(df['sequences_path'], desc="Gathering sequences"): |
| if os.path.exists(seq_path): |
| seq_df = pd.read_csv(seq_path) |
| for chain_type, sequence in zip(seq_df['chain_type'], seq_df['sequence']): |
| if chain_type == 'polypeptide(L)': |
| protein_sequences.add(sequence) |
| elif chain_type in ['polydeoxyribonucleotide', 'polyribonucleotide', |
| 'polydeoxyribonucleotide/polyribonucleotide hybrid']: |
| na_sequences.add(sequence) |
| |
| print(f" Unique protein sequences: {len(protein_sequences)}") |
| print(f" Unique nucleic acid sequences: {len(na_sequences)}") |
| |
| |
| protein_fasta = os.path.join(clustering_dir, 'all_protein_sequences.fa') |
| na_fasta = os.path.join(clustering_dir, 'all_na_sequences.fa') |
| na_std_fasta = os.path.join(clustering_dir, 'all_na_sequences_std.fa') |
| |
| write_fasta(protein_fasta, enumerate(protein_sequences)) |
| write_fasta(na_fasta, enumerate(na_sequences)) |
| |
| |
| na_std_sequences = [standardize_na_sequence(s) for s in na_sequences] |
| write_fasta(na_std_fasta, enumerate(na_std_sequences)) |
| |
| |
| protein_clusters = {} |
| if cdhit_bin and len(protein_sequences) > 0: |
| print("\nClustering protein sequences with CD-HIT...") |
| protein_out = os.path.join(clustering_dir, 'protein_clusters') |
| |
| |
| word_size = 2 if protein_identity < 0.5 else (3 if protein_identity < 0.6 else 5) |
| |
| cmd = [ |
| cdhit_bin, |
| '-i', protein_fasta, |
| '-o', protein_out, |
| '-c', str(protein_identity), |
| '-n', str(word_size), |
| '-d', '0', |
| '-M', '16000', |
| '-T', '0', |
| '-aL', '0.9', |
| '-aS', '0.9' |
| ] |
| |
| try: |
| subprocess.run(cmd, check=True, capture_output=True) |
| protein_clusters = read_cdhit_clusters(protein_out + '.clstr') |
| print(f" Protein clusters: {len(protein_clusters)}") |
| except Exception as e: |
| print(f" Warning: Protein clustering failed: {e}") |
| |
| |
| na_clusters = {} |
| if cdhit_est_bin and len(na_sequences) > 0: |
| print("\nClustering nucleic acid sequences with CD-HIT-EST...") |
| na_out = os.path.join(clustering_dir, 'na_clusters') |
| |
| word_size = 4 if na_identity >= 0.8 else 3 |
| |
| cmd = [ |
| cdhit_est_bin, |
| '-i', na_std_fasta, |
| '-o', na_out, |
| '-c', str(na_identity), |
| '-n', str(word_size), |
| '-d', '0', |
| '-M', '16000', |
| '-T', '0', |
| '-l', '4', |
| '-aL', '0.9', |
| '-aS', '0.9' |
| ] |
| |
| try: |
| subprocess.run(cmd, check=True, capture_output=True) |
| na_clusters = read_cdhit_clusters(na_out + '.clstr') |
| print(f" Nucleic acid clusters: {len(na_clusters)}") |
| except Exception as e: |
| print(f" Warning: NA clustering failed: {e}") |
| |
| |
| protein_seq_to_cluster = {} |
| protein_seq_list = list(protein_sequences) |
| for cluster_id, members in protein_clusters.items(): |
| for member in members: |
| try: |
| idx = int(member) |
| protein_seq_to_cluster[protein_seq_list[idx]] = cluster_id |
| except: |
| pass |
| |
| na_seq_to_cluster = {} |
| na_seq_list = list(na_sequences) |
| na_std_list = [standardize_na_sequence(s) for s in na_seq_list] |
| std_to_cluster = {} |
| for cluster_id, members in na_clusters.items(): |
| for member in members: |
| try: |
| idx = int(member) |
| std_to_cluster[na_std_list[idx]] = cluster_id |
| except: |
| pass |
| |
| for seq in na_seq_list: |
| std_seq = standardize_na_sequence(seq) |
| if std_seq in std_to_cluster: |
| na_seq_to_cluster[seq] = std_to_cluster[std_seq] |
| |
| |
| np.save(os.path.join(clustering_dir, 'protein_seq_to_cluster.npy'), protein_seq_to_cluster) |
| np.save(os.path.join(clustering_dir, 'na_seq_to_cluster.npy'), na_seq_to_cluster) |
| |
| print(f"\nClustering complete. Results saved to {clustering_dir}") |
| |
| return { |
| 'protein_seq_to_cluster': protein_seq_to_cluster, |
| 'na_seq_to_cluster': na_seq_to_cluster, |
| 'n_protein_clusters': len(protein_clusters), |
| 'n_na_clusters': len(na_clusters) |
| } |
|
|
|
|
| |
| |
| |
|
|
| def create_train_valid_split(output_dir, valid_fraction=0.1, test_fraction=0.0, |
| seed=42, use_clustering=False): |
| """Create train/valid/test split. |
| |
| Args: |
| output_dir: Output directory |
| valid_fraction: Fraction for validation set |
| test_fraction: Fraction for test set |
| seed: Random seed |
| use_clustering: Whether to use sequence clustering for split (prevents data leakage) |
| """ |
| |
| preprocessed_path = os.path.join(output_dir, 'preprocessed_structures.csv') |
| if not os.path.exists(preprocessed_path): |
| print(f"Error: {preprocessed_path} not found. Run 'preprocess' first.") |
| return |
| |
| df = pd.read_csv(preprocessed_path) |
| print(f"Splitting {len(df)} structures...") |
| print(f" Valid fraction: {valid_fraction}") |
| print(f" Test fraction: {test_fraction}") |
| print(f" Train fraction: {1 - valid_fraction - test_fraction}") |
| |
| np.random.seed(seed) |
| |
| if use_clustering: |
| |
| clustering_dir = os.path.join(output_dir, 'clustering') |
| na_cluster_path = os.path.join(clustering_dir, 'na_seq_to_cluster.npy') |
| |
| if os.path.exists(na_cluster_path): |
| print("\nUsing cluster-based splitting (prevents data leakage)...") |
| na_seq_to_cluster = np.load(na_cluster_path, allow_pickle=True).item() |
| |
| |
| structure_clusters = {} |
| for idx, seq_path in enumerate(df['sequences_path']): |
| if os.path.exists(seq_path): |
| seq_df = pd.read_csv(seq_path) |
| clusters = set() |
| for chain_type, sequence in zip(seq_df['chain_type'], seq_df['sequence']): |
| if chain_type in ['polydeoxyribonucleotide', 'polyribonucleotide', |
| 'polydeoxyribonucleotide/polyribonucleotide hybrid']: |
| if sequence in na_seq_to_cluster: |
| clusters.add(na_seq_to_cluster[sequence]) |
| structure_clusters[idx] = clusters |
| |
| |
| all_clusters = set() |
| for clusters in structure_clusters.values(): |
| all_clusters.update(clusters) |
| all_clusters = list(all_clusters) |
| np.random.shuffle(all_clusters) |
| |
| n_test = int(len(all_clusters) * test_fraction) |
| n_valid = int(len(all_clusters) * valid_fraction) |
| |
| test_clusters = set(all_clusters[:n_test]) |
| valid_clusters = set(all_clusters[n_test:n_test + n_valid]) |
| train_clusters = set(all_clusters[n_test + n_valid:]) |
| |
| |
| test_indices = [] |
| valid_indices = [] |
| train_indices = [] |
| |
| for idx, clusters in structure_clusters.items(): |
| if clusters & test_clusters: |
| test_indices.append(idx) |
| elif clusters & valid_clusters: |
| valid_indices.append(idx) |
| else: |
| train_indices.append(idx) |
| |
| print(f" Cluster-based split:") |
| print(f" Train clusters: {len(train_clusters)}, Valid clusters: {len(valid_clusters)}, Test clusters: {len(test_clusters)}") |
| else: |
| print("Warning: Clustering data not found, falling back to random split") |
| use_clustering = False |
| |
| if not use_clustering: |
| |
| indices = np.random.permutation(len(df)) |
| n_test = int(len(df) * test_fraction) |
| n_valid = int(len(df) * valid_fraction) |
| |
| test_indices = indices[:n_test] |
| valid_indices = indices[n_test:n_test + n_valid] |
| train_indices = indices[n_test + n_valid:] |
| |
| train_df = df.iloc[train_indices].copy() |
| valid_df = df.iloc[valid_indices].copy() |
| test_df = df.iloc[test_indices].copy() if len(test_indices) > 0 else pd.DataFrame() |
| |
| |
| train_path = os.path.join(output_dir, 'train.csv') |
| valid_path = os.path.join(output_dir, 'valid.csv') |
| test_path = os.path.join(output_dir, 'test.csv') |
| all_path = os.path.join(output_dir, 'all.csv') |
| |
| train_df.to_csv(train_path, index=False) |
| valid_df.to_csv(valid_path, index=False) |
| if len(test_df) > 0: |
| test_df.to_csv(test_path, index=False) |
| df.to_csv(all_path, index=False) |
| |
| print(f"\nSplit complete:") |
| print(f" Train: {len(train_df)} -> {train_path}") |
| print(f" Valid: {len(valid_df)} -> {valid_path}") |
| if len(test_df) > 0: |
| print(f" Test: {len(test_df)} -> {test_path}") |
| |
| |
| print("\nDataset statistics:") |
| print(f" Total structures: {len(df)}") |
| if 'has_protein' in df.columns: |
| print(f" With protein: {df['has_protein'].sum()}") |
| if 'has_dna' in df.columns: |
| print(f" With DNA: {df['has_dna'].sum()}") |
| if 'has_rna' in df.columns: |
| print(f" With RNA: {df['has_rna'].sum()}") |
|
|
|
|
| |
| |
| |
|
|
| def main(): |
| parser = argparse.ArgumentParser( |
| description="Full dataset preparation for NA-MPNN Diffusion (满血版)", |
| formatter_class=argparse.RawDescriptionHelpFormatter, |
| epilog=""" |
| Examples: |
| # Quick test with small sample |
| python prepare_diffusion_dataset_full.py all \\ |
| --mmcif_dir pdb_mmcif --output_dir datasets/test \\ |
| --sample_size 1000 --require_na --num_workers 16 |
| |
| # Full PDB with nucleic acids only |
| python prepare_diffusion_dataset_full.py all \\ |
| --mmcif_dir pdb_mmcif --output_dir datasets/na_full \\ |
| --require_na --num_workers 32 |
| |
| # Step-by-step with clustering |
| python prepare_diffusion_dataset_full.py scan --mmcif_dir pdb_mmcif --output_dir out --num_workers 16 |
| python prepare_diffusion_dataset_full.py preprocess --output_dir out --num_workers 16 |
| python prepare_diffusion_dataset_full.py cluster --output_dir out --cdhit_path /path/to/cdhit |
| python prepare_diffusion_dataset_full.py split --output_dir out --use_clustering |
| """ |
| ) |
| |
| subparsers = parser.add_subparsers(dest='command', help='Commands') |
| |
| |
| scan_parser = subparsers.add_parser('scan', help='Scan PDB database (Step 1)') |
| scan_parser.add_argument('--mmcif_dir', type=str, required=True, |
| help='Path to mmCIF files directory') |
| scan_parser.add_argument('--output_dir', type=str, required=True, |
| help='Output directory for results') |
| scan_parser.add_argument('--num_workers', type=int, default=None, |
| help='Number of parallel workers (default: CPU count - 2)') |
| scan_parser.add_argument('--sample_size', type=int, default=None, |
| help='Sample N structures for testing (default: use all)') |
| scan_parser.add_argument('--require_na', action='store_true', |
| help='Only keep structures with nucleic acids') |
| scan_parser.add_argument('--require_protein', action='store_true', |
| help='Only keep structures with proteins') |
| scan_parser.add_argument('--min_heavy_atoms', type=int, default=100, |
| help='Minimum number of heavy atoms (default: 100)') |
| scan_parser.add_argument('--min_coverage', type=float, default=0.9, |
| help='Minimum atom coverage (default: 0.9)') |
| scan_parser.add_argument('--max_resolution', type=float, default=3.5, |
| help='Maximum resolution in Å (default: 3.5)') |
| scan_parser.add_argument('--max_unknown', type=int, default=20, |
| help='Maximum unknown residues (default: 20)') |
| |
| |
| preprocess_parser = subparsers.add_parser('preprocess', help='Preprocess structures (Step 2)') |
| preprocess_parser.add_argument('--output_dir', type=str, required=True) |
| preprocess_parser.add_argument('--num_workers', type=int, default=None) |
| |
| |
| cluster_parser = subparsers.add_parser('cluster', help='Cluster sequences with CD-HIT (Step 3, optional)') |
| cluster_parser.add_argument('--output_dir', type=str, required=True) |
| cluster_parser.add_argument('--cdhit_path', type=str, default=None, |
| help='Path to CD-HIT installation directory') |
| cluster_parser.add_argument('--protein_identity', type=float, default=0.4, |
| help='Protein clustering identity threshold (default: 0.4)') |
| cluster_parser.add_argument('--na_identity', type=float, default=0.8, |
| help='Nucleic acid clustering identity threshold (default: 0.8)') |
| |
| |
| split_parser = subparsers.add_parser('split', help='Create train/valid/test split (Step 4)') |
| split_parser.add_argument('--output_dir', type=str, required=True) |
| split_parser.add_argument('--valid_fraction', type=float, default=0.1, |
| help='Validation set fraction (default: 0.1)') |
| split_parser.add_argument('--test_fraction', type=float, default=0.0, |
| help='Test set fraction (default: 0.0)') |
| split_parser.add_argument('--seed', type=int, default=42) |
| split_parser.add_argument('--use_clustering', action='store_true', |
| help='Use cluster-based split (prevents data leakage)') |
| |
| |
| all_parser = subparsers.add_parser('all', help='Run all steps (scan + preprocess + split)') |
| all_parser.add_argument('--mmcif_dir', type=str, required=True) |
| all_parser.add_argument('--output_dir', type=str, required=True) |
| all_parser.add_argument('--num_workers', type=int, default=None) |
| all_parser.add_argument('--sample_size', type=int, default=None) |
| all_parser.add_argument('--require_na', action='store_true') |
| all_parser.add_argument('--require_protein', action='store_true') |
| all_parser.add_argument('--min_heavy_atoms', type=int, default=100) |
| all_parser.add_argument('--min_coverage', type=float, default=0.9) |
| all_parser.add_argument('--max_resolution', type=float, default=3.5) |
| all_parser.add_argument('--valid_fraction', type=float, default=0.1) |
| all_parser.add_argument('--test_fraction', type=float, default=0.0) |
| all_parser.add_argument('--cdhit_path', type=str, default=None, |
| help='Path to CD-HIT (enables clustering)') |
| |
| args = parser.parse_args() |
| |
| if args.command == 'scan': |
| df = scan_database_multiprocess( |
| args.mmcif_dir, args.output_dir, |
| num_workers=args.num_workers, |
| sample_size=args.sample_size |
| ) |
| df = filter_scanned_data( |
| df, |
| min_heavy_atoms=args.min_heavy_atoms, |
| min_coverage=args.min_coverage, |
| max_resolution=args.max_resolution, |
| max_unknown_residues=args.max_unknown, |
| require_na=args.require_na, |
| require_protein=args.require_protein |
| ) |
| filtered_path = os.path.join(args.output_dir, 'filtered_structures.csv') |
| df.to_csv(filtered_path, index=False) |
| print(f"\nSaved filtered data to {filtered_path}") |
| |
| elif args.command == 'preprocess': |
| preprocess_structures_multiprocess(args.output_dir, args.num_workers) |
| |
| elif args.command == 'cluster': |
| cluster_sequences(args.output_dir, args.cdhit_path, |
| args.protein_identity, args.na_identity) |
| |
| elif args.command == 'split': |
| create_train_valid_split(args.output_dir, args.valid_fraction, |
| args.test_fraction, args.seed, args.use_clustering) |
| |
| elif args.command == 'all': |
| print("="*70) |
| print("Step 1/4: Scanning PDB database (multi-process)") |
| print("="*70) |
| df = scan_database_multiprocess( |
| args.mmcif_dir, args.output_dir, |
| num_workers=args.num_workers, |
| sample_size=args.sample_size |
| ) |
| df = filter_scanned_data( |
| df, |
| min_heavy_atoms=args.min_heavy_atoms, |
| min_coverage=args.min_coverage, |
| max_resolution=args.max_resolution, |
| require_na=args.require_na, |
| require_protein=args.require_protein |
| ) |
| filtered_path = os.path.join(args.output_dir, 'filtered_structures.csv') |
| df.to_csv(filtered_path, index=False) |
| |
| print("\n" + "="*70) |
| print("Step 2/4: Preprocessing structures (multi-process)") |
| print("="*70) |
| preprocess_structures_multiprocess(args.output_dir, args.num_workers) |
| |
| use_clustering = False |
| if args.cdhit_path: |
| print("\n" + "="*70) |
| print("Step 3/4: Clustering sequences (CD-HIT)") |
| print("="*70) |
| result = cluster_sequences(args.output_dir, args.cdhit_path) |
| if result: |
| use_clustering = True |
| else: |
| print("\n" + "="*70) |
| print("Step 3/4: Clustering (skipped, no CD-HIT path provided)") |
| print("="*70) |
| |
| print("\n" + "="*70) |
| print("Step 4/4: Creating train/valid/test split") |
| print("="*70) |
| create_train_valid_split(args.output_dir, args.valid_fraction, |
| args.test_fraction, use_clustering=use_clustering) |
| |
| print("\n" + "="*70) |
| print("✓ COMPLETE!") |
| print("="*70) |
| print(f"\nDataset ready! Update your config with:") |
| print(f' "DF_PATH_TRAIN": "{os.path.abspath(os.path.join(args.output_dir, "train.csv"))}",') |
| print(f' "DF_PATH_VALID": "{os.path.abspath(os.path.join(args.output_dir, "valid.csv"))}",') |
| if args.test_fraction > 0: |
| print(f' "DF_PATH_TEST": "{os.path.abspath(os.path.join(args.output_dir, "test.csv"))}",') |
| else: |
| parser.print_help() |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|