"""Phase 2: Parse raw sample CSVs and match against reference genotypes to determine known/unknown contributors.""" 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") # Convert to nested dict: {study_id: {kit: {person_id: {marker: alleles}}}} 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(csv_path, num_contributors): """Extract observed genotypes from a sample CSV file.""" try: df = pd.read_csv(csv_path) # Extract unique markers and their alleles sample_genotype = {} for _, row in df.iterrows(): marker = row['Marker'] # Get non-empty alleles (columns Allele 1-100) 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 != '': alleles.append(allele) if alleles: # Store as comma-separated string (like reference format) sample_genotype[marker] = ','.join(sorted(set(alleles))) return sample_genotype except Exception as e: print(f" āš ļø Error reading {csv_path.name}: {e}") return {} def match_person_to_reference(sample_markers, known_person_markers, marker_threshold=24): """Calculate match score between sample and known person.""" if not known_person_markers or not sample_markers: return 0, 0 # Find common markers common_markers = set(sample_markers.keys()) & set(known_person_markers.keys()) if not common_markers: return 0, 0 # Count matching markers matches = 0 for marker in common_markers: sample_alleles = set(sample_markers[marker].split(',')) ref_alleles = set(known_person_markers[marker].split(',')) # Check if alleles match (allowing for heterozygosity) if sample_alleles == ref_alleles: matches += 1 match_score = matches / len(common_markers) return matches, match_score def identify_known_unknown_contributors(sample_genotype, ref_db, study_id, kit, num_contributors): """Identify which contributors in sample are known vs unknown.""" known_matches = [] # Try to match against all known people in this study/kit 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 = match_person_to_reference(sample_genotype, person_markers, marker_threshold=24) if matches >= 24: # Threshold: at least 24/28 markers match known_matches.append((person_id, matches, match_score)) # Sort by match score known_matches.sort(key=lambda x: x[2], reverse=True) # Deduplicate: if we have more known matches than contributors, keep top ones num_known = min(len(known_matches), num_contributors) num_unknown = max(0, num_contributors - num_known) # Safety: if we somehow have matches, use them if known_matches and num_known == 0: num_known = 1 num_unknown = max(0, num_contributors - 1) return num_known, num_unknown, known_matches def process_all_samples(): """Process all raw sample CSV files and generate labels.""" print("\n" + "=" * 80) print("šŸ” PHASE 2: Parse Samples & Match to Reference Database") print("=" * 80) # Load reference ref_db = load_reference_genotypes() # Find all sample CSV files (exclude Known Genotypes files) 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") # Track results results = [] stats = defaultdict(int) # Process each file for idx, csv_path in enumerate(sorted(sample_files)): if idx % 100 == 0: print(f" Processing {idx}/{len(sample_files)}...") # Extract folder info to determine number of contributors path_parts = csv_path.parts num_contributors = 1 study_id = "Unknown" kit = "Unknown" # Determine number of contributors from folder name 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 # Extract study and kit from folder name 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" # Extract sample genotype sample_genotype = extract_sample_genotype(csv_path, num_contributors) if not sample_genotype: continue # Match to reference num_known, num_unknown, known_matches = identify_known_unknown_contributors( sample_genotype, ref_db, study_id, kit, num_contributors ) # Validate 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 # Create results DataFrame 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]}") # Check class balance 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}%)") # Save results 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() print("\n" + "=" * 80) print("āœ… PHASE 2 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()