| """Phase 2 v2: Parse raw sample CSVs and match against reference genotypes - IMPROVED MATCHING.""" |
|
|
| import pandas as pd |
| import numpy as np |
| from pathlib import Path |
| import glob |
| import json |
| from collections import defaultdict |
| import warnings |
|
|
| warnings.filterwarnings('ignore') |
|
|
| ROOT = Path("/Users/manhnguyen/Project/NOC_DNA_V2") |
| RAW_DATA_DIR = ROOT / "data/PROVEDIt_1-5-Person CSVs UnFiltered" |
| OUTPUT_DIR = ROOT / "data/reconstructed" |
| OUTPUT_DIR.mkdir(parents=True, exist_ok=True) |
|
|
| def load_reference_genotypes(): |
| """Load reference genotypes from extracted data.""" |
| print("📖 Loading reference genotypes...") |
| ref_df = pd.read_csv(OUTPUT_DIR / "reference_genotypes_raw.csv") |
|
|
| |
| ref_db = defaultdict(lambda: defaultdict(lambda: defaultdict(dict))) |
|
|
| for _, row in ref_df.iterrows(): |
| study = row['study_id'] |
| kit = row['kit'] |
| person = int(row['person_id']) |
| marker = row['marker'] |
| alleles = str(row['alleles']).strip() |
|
|
| ref_db[study][kit][person][marker] = alleles |
|
|
| print(f"✅ Loaded reference genotypes for {len(ref_db)} studies") |
| for study in ref_db: |
| total_people = sum(len(ref_db[study][k]) for k in ref_db[study]) |
| print(f" {study}: {total_people} people across {len(ref_db[study])} kits") |
|
|
| return ref_db |
|
|
| def extract_sample_genotype_v2(csv_path, num_contributors): |
| """Extract observed genotypes from a sample CSV file - IMPROVED.""" |
| try: |
| df = pd.read_csv(csv_path) |
|
|
| |
| sample_genotype = {} |
|
|
| for _, row in df.iterrows(): |
| marker = row['Marker'] |
|
|
| |
| alleles = [] |
| for i in range(1, 101): |
| col_name = f'Allele {i}' |
| if col_name in df.columns: |
| allele = str(row[col_name]).strip() |
| |
| if allele and allele != 'nan' and allele != '' and allele.upper() != 'OL': |
| try: |
| |
| float(allele) |
| alleles.append(allele) |
| except: |
| |
| if allele.upper() in ['X', 'Y', 'AM']: |
| alleles.append(allele.upper()) |
|
|
| if alleles: |
| |
| unique_alleles = sorted(set(alleles)) |
| sample_genotype[marker] = ','.join(unique_alleles) |
|
|
| return sample_genotype |
|
|
| except Exception as e: |
| print(f" ⚠️ Error reading {csv_path.name}: {e}") |
| return {} |
|
|
| def normalize_allele(allele_str): |
| """Normalize allele string for comparison.""" |
| allele_str = str(allele_str).strip().upper() |
| |
| if allele_str in ['X', 'Y', 'AM']: |
| return allele_str |
| try: |
| return str(float(allele_str)) |
| except: |
| return allele_str |
|
|
| def match_person_to_reference_v2(sample_markers, known_person_markers, verbose=False): |
| """Calculate match score between sample and known person - IMPROVED.""" |
| if not known_person_markers or not sample_markers: |
| return 0, 0, 0 |
|
|
| |
| common_markers = set(sample_markers.keys()) & set(known_person_markers.keys()) |
|
|
| if not common_markers: |
| return 0, 0, 0 |
|
|
| |
| matches = 0 |
| perfect_matches = 0 |
|
|
| for marker in common_markers: |
| |
| sample_alleles = set([normalize_allele(a) for a in sample_markers[marker].split(',')]) |
| ref_alleles = set([normalize_allele(a) for a in known_person_markers[marker].split(',')]) |
|
|
| |
| |
| if sample_alleles & ref_alleles: |
| matches += 1 |
|
|
| if sample_alleles == ref_alleles: |
| perfect_matches += 1 |
|
|
| match_score = matches / len(common_markers) |
| perfect_score = perfect_matches / len(common_markers) |
|
|
| return matches, match_score, perfect_score |
|
|
| def identify_known_unknown_contributors_v2(sample_genotype, ref_db, study_id, kit, num_contributors): |
| """Identify which contributors in sample are known vs unknown - IMPROVED.""" |
|
|
| known_matches = [] |
|
|
| |
| if study_id in ref_db and kit in ref_db[study_id]: |
| for person_id, person_markers in ref_db[study_id][kit].items(): |
| matches, match_score, perfect_score = match_person_to_reference_v2( |
| sample_genotype, person_markers |
| ) |
|
|
| |
| if match_score >= 0.7: |
| known_matches.append((person_id, matches, match_score, perfect_score)) |
|
|
| |
| known_matches.sort(key=lambda x: (x[3], x[2]), reverse=True) |
|
|
| |
| |
| |
|
|
| |
| unique_matches = [] |
| used_people = set() |
|
|
| for person_id, matches, match_score, perfect_score in known_matches: |
| if person_id not in used_people and len(unique_matches) < num_contributors: |
| unique_matches.append((person_id, matches, match_score)) |
| used_people.add(person_id) |
|
|
| num_known = len(unique_matches) |
| num_unknown = max(0, num_contributors - num_known) |
|
|
| return num_known, num_unknown, unique_matches |
|
|
| def process_all_samples_v2(): |
| """Process all raw sample CSV files and generate labels - IMPROVED.""" |
|
|
| print("\n" + "=" * 80) |
| print("🔍 PHASE 2 v2: Parse Samples & Match to Reference (IMPROVED)") |
| print("=" * 80) |
|
|
| |
| ref_db = load_reference_genotypes() |
|
|
| |
| sample_files = [] |
| for f in RAW_DATA_DIR.rglob("*.csv"): |
| if "Known Genotypes" not in f.name: |
| sample_files.append(f) |
|
|
| print(f"\n📂 Found {len(sample_files)} sample CSV files") |
|
|
| |
| results = [] |
| stats = defaultdict(int) |
|
|
| |
| for idx, csv_path in enumerate(sorted(sample_files)): |
| if idx % 100 == 0: |
| print(f" Processing {idx}/{len(sample_files)}...", end='\r') |
|
|
| |
| path_parts = csv_path.parts |
| num_contributors = 1 |
| study_id = "Unknown" |
| kit = "Unknown" |
|
|
| |
| for part in path_parts: |
| if "1-Person" in part: |
| num_contributors = 1 |
| elif "2-Person" in part: |
| num_contributors = 2 |
| elif "3-Person" in part: |
| num_contributors = 3 |
| elif "4-Person" in part: |
| num_contributors = 4 |
| elif "5-Person" in part: |
| num_contributors = 5 |
|
|
| |
| if "RD14" in part or "RD14-0003" in part: |
| study_id = "RD14-0003" |
| elif "RD12" in part or "RD12-0002" in part: |
| study_id = "RD12-0002" |
|
|
| if "IDPlus29" in part: |
| kit = "IDPlus29" |
| elif "IDPlus28" in part: |
| kit = "IDPlus28" |
| elif "GF29" in part: |
| kit = "GF29" |
| elif "F6C29" in part: |
| kit = "F6C29" |
| elif "PP16HS32" in part: |
| kit = "PP16HS32" |
|
|
| |
| sample_genotype = extract_sample_genotype_v2(csv_path, num_contributors) |
|
|
| if not sample_genotype: |
| continue |
|
|
| |
| num_known, num_unknown, known_matches = identify_known_unknown_contributors_v2( |
| sample_genotype, ref_db, study_id, kit, num_contributors |
| ) |
|
|
| |
| if num_known + num_unknown != num_contributors: |
| num_unknown = num_contributors - num_known |
|
|
| unknown_present = 1 if num_unknown > 0 else 0 |
|
|
| results.append({ |
| 'sample_file': csv_path.name, |
| 'study_id': study_id, |
| 'kit': kit, |
| 'num_contributors': num_contributors, |
| 'num_known': num_known, |
| 'num_unknown': num_unknown, |
| 'unknown_present': unknown_present, |
| 'num_markers': len(sample_genotype), |
| 'top_match_score': known_matches[0][2] if known_matches else 0, |
| 'matched_people': ';'.join([str(m[0]) for m in known_matches[:3]]) |
| }) |
|
|
| stats[f"{study_id}_{kit}_{num_contributors}P"] += 1 |
|
|
| |
| results_df = pd.DataFrame(results) |
|
|
| print(f"\n✅ Processed {len(results_df)} samples successfully") |
| print(f"\nDistribution by study/kit/contributors:") |
| for key in sorted(stats.keys()): |
| print(f" {key}: {stats[key]}") |
|
|
| |
| print(f"\nClass balance (unknown_present):") |
| print(f" No unknown (0): {(results_df['unknown_present'] == 0).sum()} ({100*(results_df['unknown_present'] == 0).sum()/len(results_df):.1f}%)") |
| print(f" Has unknown (1): {(results_df['unknown_present'] == 1).sum()} ({100*(results_df['unknown_present'] == 1).sum()/len(results_df):.1f}%)") |
|
|
| |
| output_file = OUTPUT_DIR / "sample_labels.csv" |
| results_df.to_csv(output_file, index=False) |
| print(f"\n💾 Saved: {output_file.name}") |
|
|
| return results_df |
|
|
| def main(): |
| results_df = process_all_samples_v2() |
|
|
| print("\n" + "=" * 80) |
| print("✅ PHASE 2 v2 COMPLETE!") |
| print("=" * 80) |
| print(f"\nOutput summary:") |
| print(f" Total samples labeled: {len(results_df)}") |
| print(f" File: {OUTPUT_DIR / 'sample_labels.csv'}") |
| print(f"\nNext step: Phase 3 - Build final dataset with proper splits") |
|
|
| if __name__ == "__main__": |
| main() |
|
|