#!/usr/bin/env python3 """ Extract structural and sequence features from AlphaFold PDB files. Part of APED - African Protein Engineering Dataset """ import argparse import os import warnings from pathlib import Path import numpy as np import pandas as pd warnings.filterwarnings('ignore') # Amino acid properties HYDROPHOBICITY = { 'A': 1.8, 'R': -4.5, 'N': -3.5, 'D': -3.5, 'C': 2.5, 'Q': -3.5, 'E': -3.5, 'G': -0.4, 'H': -3.2, 'I': 4.5, 'L': 3.8, 'K': -3.9, 'M': 1.9, 'F': 2.8, 'P': -1.6, 'S': -0.8, 'T': -0.7, 'W': -0.9, 'Y': -1.3, 'V': 4.2 } CHARGE = { 'A': 0, 'R': 1, 'N': 0, 'D': -1, 'C': 0, 'Q': 0, 'E': -1, 'G': 0, 'H': 0.5, 'I': 0, 'L': 0, 'K': 1, 'M': 0, 'F': 0, 'P': 0, 'S': 0, 'T': 0, 'W': 0, 'Y': 0, 'V': 0 } MW = { 'A': 89.1, 'R': 174.2, 'N': 132.1, 'D': 133.1, 'C': 121.2, 'Q': 146.2, 'E': 147.1, 'G': 75.1, 'H': 155.2, 'I': 131.2, 'L': 131.2, 'K': 146.2, 'M': 149.2, 'F': 165.2, 'P': 115.1, 'S': 105.1, 'T': 119.1, 'W': 204.2, 'Y': 181.2, 'V': 117.1 } def parse_pdb(pdb_file: Path) -> dict: """Parse PDB file and extract sequence, pLDDT, and secondary structure.""" sequence = [] plddt_scores = [] residue_ids = set() three_to_one = { 'ALA': 'A', 'ARG': 'R', 'ASN': 'N', 'ASP': 'D', 'CYS': 'C', 'GLN': 'Q', 'GLU': 'E', 'GLY': 'G', 'HIS': 'H', 'ILE': 'I', 'LEU': 'L', 'LYS': 'K', 'MET': 'M', 'PHE': 'F', 'PRO': 'P', 'SER': 'S', 'THR': 'T', 'TRP': 'W', 'TYR': 'Y', 'VAL': 'V' } with open(pdb_file, 'r') as f: for line in f: if line.startswith('ATOM') and line[12:16].strip() == 'CA': res_id = int(line[22:26].strip()) if res_id not in residue_ids: residue_ids.add(res_id) res_name = line[17:20].strip() if res_name in three_to_one: sequence.append(three_to_one[res_name]) plddt = float(line[60:66].strip()) plddt_scores.append(plddt) return { 'sequence': ''.join(sequence), 'plddt_scores': plddt_scores } def calculate_sequence_features(sequence: str) -> dict: """Calculate sequence-based features.""" length = len(sequence) if length == 0: return {} # Hydrophobicity hydro = np.mean([HYDROPHOBICITY.get(aa, 0) for aa in sequence]) # Net charge charge = sum([CHARGE.get(aa, 0) for aa in sequence]) # Molecular weight mw = sum([MW.get(aa, 0) for aa in sequence]) - 18.015 * (length - 1) # Isoelectric point (simplified) pos_count = sum(1 for aa in sequence if aa in 'RKH') neg_count = sum(1 for aa in sequence if aa in 'DE') pi = 7.0 + (pos_count - neg_count) * 0.5 / max(length, 1) pi = max(3.0, min(12.0, pi)) # Instability index (simplified) dipeptide_instability = 0 for i in range(len(sequence) - 1): if sequence[i:i+2] in ['DG', 'GD', 'NG', 'GN']: dipeptide_instability += 1 instability = 40 + dipeptide_instability * 10 / max(length, 1) # Aromaticity aromatic = sum(1 for aa in sequence if aa in 'FWY') / length # Amino acid composition aa_counts = {aa: sequence.count(aa) / length for aa in 'ACDEFGHIKLMNPQRSTVWY'} return { 'sequence_length': length, 'hydrophobicity': round(hydro, 4), 'charge': charge, 'molecular_weight': round(mw, 2), 'isoelectric_point': round(pi, 2), 'instability_index': round(instability, 2), 'aromaticity': round(aromatic, 4), 'proline_fraction': round(aa_counts.get('P', 0), 4), 'glycine_fraction': round(aa_counts.get('G', 0), 4), 'charged_fraction': round(sum(aa_counts.get(aa, 0) for aa in 'RKDE'), 4) } def estimate_secondary_structure(sequence: str) -> dict: """Estimate secondary structure propensities.""" helix_formers = set('AELM') sheet_formers = set('VIY') helix_count = sum(1 for aa in sequence if aa in helix_formers) sheet_count = sum(1 for aa in sequence if aa in sheet_formers) length = max(len(sequence), 1) helix_frac = helix_count / length sheet_frac = sheet_count / length coil_frac = 1.0 - helix_frac - sheet_frac return { 'helix_fraction': round(max(0, helix_frac), 4), 'sheet_fraction': round(max(0, sheet_frac), 4), 'coil_fraction': round(max(0, coil_frac), 4) } def extract_features_from_pdb(pdb_file: Path) -> dict: """Extract all features from a single PDB file.""" # Get UniProt ID from filename filename = pdb_file.stem if filename.startswith('AF-'): uniprot_id = filename.split('-')[1] else: uniprot_id = filename # Parse PDB pdb_data = parse_pdb(pdb_file) sequence = pdb_data['sequence'] plddt_scores = pdb_data['plddt_scores'] if not sequence: return None # Calculate features features = { 'uniprot_id': uniprot_id, 'sequence': sequence, 'mean_plddt': round(np.mean(plddt_scores), 2) if plddt_scores else 0, 'min_plddt': round(np.min(plddt_scores), 2) if plddt_scores else 0, 'max_plddt': round(np.max(plddt_scores), 2) if plddt_scores else 0, } # Add sequence features features.update(calculate_sequence_features(sequence)) # Add secondary structure estimates features.update(estimate_secondary_structure(sequence)) return features def main(): parser = argparse.ArgumentParser( description="Extract features from AlphaFold PDB structures" ) parser.add_argument( "--input-dir", type=str, required=True, help="Directory containing PDB files" ) parser.add_argument( "--output", type=str, default="data/ml_ready/aped_ml_dataset.parquet", help="Output file path (parquet or csv)" ) parser.add_argument( "--min-plddt", type=float, default=50.0, help="Minimum mean pLDDT to include" ) args = parser.parse_args() input_dir = Path(args.input_dir) output_path = Path(args.output) output_path.parent.mkdir(parents=True, exist_ok=True) pdb_files = list(input_dir.glob("*.pdb")) print(f"Found {len(pdb_files)} PDB files") features_list = [] for i, pdb_file in enumerate(pdb_files): features = extract_features_from_pdb(pdb_file) if features and features['mean_plddt'] >= args.min_plddt: features_list.append(features) if (i + 1) % 100 == 0: print(f" Processed {i + 1}/{len(pdb_files)}") df = pd.DataFrame(features_list) # Save if str(output_path).endswith('.parquet'): df.to_parquet(output_path, index=False) else: df.to_csv(output_path, index=False) print(f"\nComplete!") print(f" Proteins: {len(df)}") print(f" Features: {len(df.columns)}") print(f" Output: {output_path}") # Print summary statistics print(f"\nFeature summary:") print(f" Mean pLDDT: {df['mean_plddt'].mean():.1f} ± {df['mean_plddt'].std():.1f}") print(f" Mean length: {df['sequence_length'].mean():.0f} ± {df['sequence_length'].std():.0f}") if __name__ == "__main__": main()