| """Phase 3: Build final clean dataset with proper splits, labels, and features.""" |
|
|
| import pandas as pd |
| import numpy as np |
| from pathlib import Path |
| import json |
| from sklearn.model_selection import train_test_split |
| import warnings |
|
|
| warnings.filterwarnings('ignore') |
|
|
| ROOT = Path("/Users/manhnguyen/Project/NOC_DNA_V2") |
| RECONSTRUCTED_DIR = ROOT / "data/reconstructed" |
| RAW_DATA_DIR = ROOT / "data/PROVEDIt_1-5-Person CSVs UnFiltered" |
| OUTPUT_DIR_RD14 = ROOT / "data/reconstructed/rd14_clean" |
| OUTPUT_DIR_RD12 = ROOT / "data/reconstructed/rd12_clean" |
|
|
| OUTPUT_DIR_RD14.mkdir(parents=True, exist_ok=True) |
| OUTPUT_DIR_RD12.mkdir(parents=True, exist_ok=True) |
|
|
| def load_sample_labels(): |
| """Load sample labels from Phase 2.""" |
| print("๐ Loading sample labels from Phase 2...") |
| labels_df = pd.read_csv(RECONSTRUCTED_DIR / "sample_labels.csv") |
| print(f"โ
Loaded {len(labels_df)} samples") |
| return labels_df |
|
|
| def filter_high_quality_samples(labels_df): |
| """Filter for high-quality samples based on criteria.""" |
| print("\n๐ Filtering for high-quality samples...") |
|
|
| print(f" Starting with: {len(labels_df)} samples") |
|
|
| |
| filtered = labels_df[labels_df['num_markers'] >= 20].copy() |
| print(f" After marker count filter: {len(filtered)} samples") |
|
|
| |
| filtered = filtered[filtered['num_contributors'].isin([1, 2, 3, 4, 5])].copy() |
| print(f" After contributor count filter: {len(filtered)} samples") |
|
|
| |
| filtered = filtered[filtered['study_id'].isin(['RD14-0003', 'RD12-0002'])].copy() |
| print(f" After study filter: {len(filtered)} samples") |
|
|
| |
| known_kits = ['IDPlus28', 'F6C29', 'GF29', 'IDPlus29', 'PP16HS32'] |
| filtered = filtered[filtered['kit'].isin(known_kits)].copy() |
| print(f" After kit filter: {len(filtered)} samples") |
|
|
| print(f"\n โ
Final filtered count: {len(filtered)} samples") |
| return filtered |
|
|
| def balance_classes(labels_df): |
| """Balance unknown_present classes (0 vs 1).""" |
| print("\nโ๏ธ Balancing class distribution...") |
|
|
| |
| no_unknown = labels_df[labels_df['unknown_present'] == 0] |
| has_unknown = labels_df[labels_df['unknown_present'] == 1] |
|
|
| print(f" No unknown (0): {len(no_unknown)}") |
| print(f" Has unknown (1): {len(has_unknown)}") |
|
|
| |
| min_class_size = min(len(no_unknown), len(has_unknown)) |
|
|
| no_unknown_balanced = no_unknown.sample(n=min_class_size, random_state=42) |
| has_unknown_balanced = has_unknown.sample(n=min_class_size, random_state=42) |
|
|
| balanced = pd.concat([no_unknown_balanced, has_unknown_balanced], ignore_index=True) |
| balanced = balanced.sample(frac=1, random_state=42).reset_index(drop=True) |
|
|
| print(f" โ
Balanced dataset: {len(balanced)} samples ({len(no_unknown_balanced)} per class)") |
| return balanced |
|
|
| def create_splits(labels_df): |
| """Create train/dev/test splits stratified by unknown_present.""" |
| print("\n๐ Creating train/dev/test splits...") |
|
|
| |
| train, temp = train_test_split( |
| labels_df, test_size=0.4, random_state=42, stratify=labels_df['unknown_present'] |
| ) |
|
|
| dev, test = train_test_split( |
| temp, test_size=0.5, random_state=42, stratify=temp['unknown_present'] |
| ) |
|
|
| |
| train['partition'] = 'train' |
| dev['partition'] = 'dev' |
| test['partition'] = 'test' |
|
|
| |
| combined = pd.concat([train, dev, test], ignore_index=True) |
| combined['split_id'] = 'split_01' |
| combined['benchmark_id'] = combined['study_id'].apply( |
| lambda x: 'rd14-fullref-50_multisplit_v2' if x == 'RD14-0003' else 'rd12-fullref-61_multisplit_v2' |
| ) |
|
|
| print(f" Train: {len(train)} samples") |
| print(f" Dev: {len(dev)} samples") |
| print(f" Test: {len(test)} samples") |
|
|
| return combined |
|
|
| def extract_peak_features(sample_file, raw_data_dir): |
| """Extract peak features from raw CSV for a sample.""" |
| features = {} |
|
|
| try: |
| |
| 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) |
|
|
| |
| for _, row in df.iterrows(): |
| marker = row['Marker'] |
|
|
| |
| peaks = 0 |
| max_height = 0 |
| sum_height = 0 |
|
|
| for i in range(1, 101): |
| height_col = f'Height {i}' |
| if height_col in df.columns: |
| height = row[height_col] |
| if pd.notna(height) and height != '' and height != 'nan': |
| try: |
| h = float(height) |
| if h > 0: |
| peaks += 1 |
| max_height = max(max_height, h) |
| sum_height += h |
| except: |
| pass |
|
|
| if peaks > 0: |
| features[f"{marker}_peak_count"] = peaks |
| features[f"{marker}_max_height"] = max_height |
| features[f"{marker}_sum_height"] = sum_height |
|
|
| except Exception as e: |
| pass |
|
|
| return features |
|
|
| def extract_marker_features(sample_genotype): |
| """Extract marker-based features.""" |
| features = {} |
|
|
| if not sample_genotype: |
| return features |
|
|
| |
| features['num_markers'] = len(sample_genotype) |
|
|
| |
| num_homozygous = sum(1 for alleles in sample_genotype.values() if len(set(alleles.split(','))) == 1) |
| features['num_homozygous'] = num_homozygous |
| features['num_heterozygous'] = len(sample_genotype) - num_homozygous |
|
|
| return features |
|
|
| def build_feature_matrix(labels_df): |
| """Build complete feature matrix with peak and marker features.""" |
| print("\n๐ ๏ธ Building feature matrix...") |
|
|
| 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'] |
| 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'], |
| 'num_markers_detected': row['num_markers'], |
| 'partition': row['partition'], |
| 'split_id': row['split_id'], |
| 'benchmark_id': row['benchmark_id'] |
| } |
|
|
| |
| peak_features = extract_peak_features(sample_file, RAW_DATA_DIR) |
| feature_dict.update(peak_features) |
|
|
| features_list.append(feature_dict) |
|
|
| feature_df = pd.DataFrame(features_list) |
| print(f"โ
Created feature matrix: {len(feature_df)} samples ร {len(feature_df.columns)} features") |
| return feature_df |
|
|
| def save_dataset(feature_df): |
| """Save dataset split by study.""" |
| print("\n๐พ Saving datasets...") |
|
|
| |
| rd14_df = feature_df[feature_df['study_id'] == 'RD14-0003'].copy() |
| rd12_df = feature_df[feature_df['study_id'] == 'RD12-0002'].copy() |
|
|
| |
| rd14_labels = rd14_df[['sample_file', 'benchmark_id', 'split_id', 'partition', 'study_id', 'kit', |
| 'num_known', 'num_unknown', 'unknown_present', 'num_contributors']].copy() |
| rd14_labels.to_csv(OUTPUT_DIR_RD14 / "sample_labels_all_splits.csv", index=False) |
|
|
| |
| rd12_labels = rd12_df[['sample_file', 'benchmark_id', 'split_id', 'partition', 'study_id', 'kit', |
| 'num_known', 'num_unknown', 'unknown_present', 'num_contributors']].copy() |
| rd12_labels.to_csv(OUTPUT_DIR_RD12 / "sample_labels_all_splits.csv", index=False) |
|
|
| print(f" โ
RD14 dataset: {len(rd14_df)} samples") |
| print(f" File: {OUTPUT_DIR_RD14}/sample_labels_all_splits.csv") |
| print(f" โ
RD12 dataset: {len(rd12_df)} samples") |
| print(f" File: {OUTPUT_DIR_RD12}/sample_labels_all_splits.csv") |
|
|
| |
| rd14_df.to_csv(OUTPUT_DIR_RD14 / "features_matrix.csv", index=False) |
| rd12_df.to_csv(OUTPUT_DIR_RD12 / "features_matrix.csv", index=False) |
|
|
| |
| summary = { |
| "rd14": { |
| "total_samples": len(rd14_df), |
| "train": len(rd14_df[rd14_df['partition'] == 'train']), |
| "dev": len(rd14_df[rd14_df['partition'] == 'dev']), |
| "test": len(rd14_df[rd14_df['partition'] == 'test']), |
| "unknown_0": len(rd14_df[rd14_df['unknown_present'] == 0]), |
| "unknown_1": len(rd14_df[rd14_df['unknown_present'] == 1]), |
| "num_features": len(rd14_df.columns) |
| }, |
| "rd12": { |
| "total_samples": len(rd12_df), |
| "train": len(rd12_df[rd12_df['partition'] == 'train']), |
| "dev": len(rd12_df[rd12_df['partition'] == 'dev']), |
| "test": len(rd12_df[rd12_df['partition'] == 'test']), |
| "unknown_0": len(rd12_df[rd12_df['unknown_present'] == 0]), |
| "unknown_1": len(rd12_df[rd12_df['unknown_present'] == 1]), |
| "num_features": len(rd12_df.columns) |
| } |
| } |
|
|
| with open(OUTPUT_DIR_RD14 / "dataset_summary.json", "w") as f: |
| json.dump(summary, f, indent=2) |
|
|
| with open(OUTPUT_DIR_RD12 / "dataset_summary.json", "w") as f: |
| json.dump(summary, f, indent=2) |
|
|
| print(f"\n๐ Dataset Summary:") |
| print(json.dumps(summary, indent=2)) |
|
|
| return rd14_df, rd12_df |
|
|
| def main(): |
| print("=" * 80) |
| print("๐ง PHASE 3: Build Final Clean Dataset with Proper Splits") |
| print("=" * 80) |
|
|
| |
| labels_df = load_sample_labels() |
|
|
| |
| filtered_df = filter_high_quality_samples(labels_df) |
|
|
| |
| balanced_df = balance_classes(filtered_df) |
|
|
| |
| split_df = create_splits(balanced_df) |
|
|
| |
| feature_df = build_feature_matrix(split_df) |
|
|
| |
| rd14_df, rd12_df = save_dataset(feature_df) |
|
|
| print("\n" + "=" * 80) |
| print("โ
PHASE 3 COMPLETE!") |
| print("=" * 80) |
| print(f"\nDatasets ready for training:") |
| print(f" RD14: {OUTPUT_DIR_RD14}/sample_labels_all_splits.csv") |
| print(f" RD12: {OUTPUT_DIR_RD12}/sample_labels_all_splits.csv") |
| print(f"\nNext step: Phase 4 - Retrain models with new data") |
|
|
| if __name__ == "__main__": |
| main() |
|
|