File size: 8,883 Bytes
4636192 | 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 239 240 241 242 243 | """Enhanced Feature Engineering: Add domain-specific DNA features."""
import pandas as pd
import numpy as np
from pathlib import Path
import json
import warnings
warnings.filterwarnings('ignore')
ROOT = Path(__file__).parent.parent.parent
RECONSTRUCTED_DIR = ROOT / "data/reconstructed"
RAW_DATA_DIR = ROOT / "data/PROVEDIt_1-5-Person CSVs UnFiltered"
OUTPUT_DIR = ROOT / "data/reconstructed/production"
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
def load_all_sample_data():
"""Load all sample labels from both phases."""
print("π Loading all sample labels...")
labels_df = pd.read_csv(RECONSTRUCTED_DIR / "sample_labels.csv")
print(f"β
Loaded {len(labels_df)} total samples")
# Split by study
rd14_samples = labels_df[labels_df['study_id'] == 'RD14-0003'].copy()
rd12_samples = labels_df[labels_df['study_id'] == 'RD12-0002'].copy()
print(f" RD14: {len(rd14_samples)} samples")
print(f" RD12: {len(rd12_samples)} samples")
return labels_df, rd14_samples, rd12_samples
def extract_peak_features_enhanced(sample_file, raw_data_dir):
"""Extract enhanced peak features from raw CSV."""
features = {}
try:
# Find the CSV file
found_files = list(raw_data_dir.rglob(f"{sample_file}"))
if not found_files:
return features
csv_path = found_files[0]
df = pd.read_csv(csv_path)
# Extract statistics per marker
for _, row in df.iterrows():
marker = row['Marker']
# Extract all heights and sizes
heights = []
sizes = []
alleles = []
for i in range(1, 101):
height_col = f'Height {i}'
size_col = f'Size {i}'
allele_col = f'Allele {i}'
if height_col in df.columns:
height = row[height_col]
if pd.notna(height) and height != '' and str(height).upper() != 'NAN':
try:
h = float(height)
if h > 0:
heights.append(h)
except:
pass
if size_col in df.columns and len(heights) > 0:
size = row[size_col]
if pd.notna(size) and size != '':
try:
sizes.append(float(size))
except:
pass
if allele_col in df.columns:
allele = str(row[allele_col]).strip()
if allele and allele.upper() != 'OL' and allele != 'nan':
alleles.append(allele)
if heights:
# Basic features
features[f"{marker}_peak_count"] = len(heights)
features[f"{marker}_max_height"] = max(heights)
features[f"{marker}_sum_height"] = sum(heights)
features[f"{marker}_mean_height"] = np.mean(heights)
features[f"{marker}_std_height"] = np.std(heights) if len(heights) > 1 else 0
# Domain-specific: Peak height ratio (peak 1 / peak 2)
if len(heights) >= 2:
sorted_heights = sorted(heights, reverse=True)
features[f"{marker}_peak_ratio"] = sorted_heights[0] / sorted_heights[1] if sorted_heights[1] > 0 else 0
# Allele balance: ratio of two highest peaks
features[f"{marker}_allele_balance"] = min(sorted_heights[0], sorted_heights[1]) / max(sorted_heights[0], sorted_heights[1]) if sorted_heights[0] > 0 else 0
# Domain-specific: Homozygosity indicator
if len(alleles) == 2:
features[f"{marker}_is_homozygous"] = 1 if alleles[0] == alleles[1] else 0
else:
features[f"{marker}_is_homozygous"] = 0
# Domain-specific: Peak distribution (coefficient of variation)
if len(heights) > 1:
features[f"{marker}_cv_heights"] = np.std(heights) / np.mean(heights) if np.mean(heights) > 0 else 0
except Exception as e:
pass
return features
def build_enhanced_feature_matrix(labels_df):
"""Build feature matrix with domain-specific features."""
print("\nπ οΈ Building enhanced feature matrix with domain features...")
features_list = []
for idx, row in labels_df.iterrows():
if idx % 100 == 0:
print(f" Processing {idx}/{len(labels_df)}...", end='\r')
sample_file = row['sample_file']
# Basic info
feature_dict = {
'sample_file': sample_file,
'study_id': row['study_id'],
'kit': row['kit'],
'num_contributors': row['num_contributors'],
'num_known': row['num_known'],
'num_unknown': row['num_unknown'],
'unknown_present': row['unknown_present'],
}
# Extract enhanced peak features
peak_features = extract_peak_features_enhanced(sample_file, RAW_DATA_DIR)
feature_dict.update(peak_features)
features_list.append(feature_dict)
feature_df = pd.DataFrame(features_list)
# Fill NaN with 0
feature_df = feature_df.fillna(0)
# Filter: Keep only samples with minimum markers
marker_threshold = 15
marker_cols = [c for c in feature_df.columns if '_peak_count' in c]
feature_df['num_markers_detected'] = (feature_df[marker_cols] > 0).sum(axis=1)
print(f"\n Total features before filtering: {len(feature_df)}")
print(f" Min marker threshold: {marker_threshold}")
filtered_df = feature_df[feature_df['num_markers_detected'] >= marker_threshold].copy()
print(f" Total features after filtering: {len(filtered_df)}")
print(f" Feature columns: {len(filtered_df.columns)}")
return filtered_df
def split_by_study(feature_df):
"""Split dataset by study."""
print("\nπ Splitting by study...")
rd14_df = feature_df[feature_df['study_id'] == 'RD14-0003'].copy()
rd12_df = feature_df[feature_df['study_id'] == 'RD12-0002'].copy()
print(f" RD14: {len(rd14_df)} samples")
print(f" RD12: {len(rd12_df)} samples")
print(f" Combined: {len(feature_df)} samples")
return rd14_df, rd12_df, feature_df
def save_enhanced_features(rd14_df, rd12_df, combined_df):
"""Save enhanced feature matrices."""
print("\nπΎ Saving enhanced feature matrices...")
# Save by study
rd14_df.to_csv(OUTPUT_DIR / "rd14_enhanced_features.csv", index=False)
rd12_df.to_csv(OUTPUT_DIR / "rd12_enhanced_features.csv", index=False)
# Save combined
combined_df.to_csv(OUTPUT_DIR / "combined_enhanced_features.csv", index=False)
# Save summary (convert numpy types to python native types)
summary = {
"rd14": {
"total_samples": int(len(rd14_df)),
"num_features": int(len(rd14_df.columns)),
"unknown_present_0": int((rd14_df['unknown_present'] == 0).sum()),
"unknown_present_1": int((rd14_df['unknown_present'] == 1).sum()),
},
"rd12": {
"total_samples": int(len(rd12_df)),
"num_features": int(len(rd12_df.columns)),
"unknown_present_0": int((rd12_df['unknown_present'] == 0).sum()),
"unknown_present_1": int((rd12_df['unknown_present'] == 1).sum()),
},
"combined": {
"total_samples": int(len(combined_df)),
"num_features": int(len(combined_df.columns)),
"unknown_present_0": int((combined_df['unknown_present'] == 0).sum()),
"unknown_present_1": int((combined_df['unknown_present'] == 1).sum()),
}
}
with open(OUTPUT_DIR / "enhanced_features_summary.json", "w") as f:
json.dump(summary, f, indent=2)
print(f" β
RD14: {OUTPUT_DIR}/rd14_enhanced_features.csv")
print(f" β
RD12: {OUTPUT_DIR}/rd12_enhanced_features.csv")
print(f" β
Combined: {OUTPUT_DIR}/combined_enhanced_features.csv")
return summary
def main():
print("=" * 80)
print("π§ STEP 5: Enhanced Feature Engineering")
print("=" * 80)
# Load data
labels_df, rd14_samples, rd12_samples = load_all_sample_data()
# Build enhanced features
feature_df = build_enhanced_feature_matrix(labels_df)
# Split by study
rd14_df, rd12_df, combined_df = split_by_study(feature_df)
# Save
summary = save_enhanced_features(rd14_df, rd12_df, combined_df)
print("\n" + "=" * 80)
print("β
STEP 5 COMPLETE!")
print("=" * 80)
print("\nπ Feature Engineering Summary:")
print(json.dumps(summary, indent=2))
print(f"\nNext step: Light hyperparameter tuning with 5-fold CV")
if __name__ == "__main__":
main()
|