File size: 7,409 Bytes
318c457
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
#!/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()