dna_noc / src /data /02_parse_samples_match_reference_v2.py
manhngvu's picture
🎉 Update: Optimized models with F1=0.7135 + Complete research report + Analysis (2026-05-08)
4636192 verified
Raw
History Blame Contribute Delete
10.5 kB
"""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")
# 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_v2(csv_path, num_contributors):
"""Extract observed genotypes from a sample CSV file - IMPROVED."""
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()
# Filter out empty, NaN, OL (outlier), and invalid entries
if allele and allele != 'nan' and allele != '' and allele.upper() != 'OL':
try:
# Try to convert to float to validate it's a number
float(allele)
alleles.append(allele)
except:
# If not a number, still include it (could be AMEL format like X, Y)
if allele.upper() in ['X', 'Y', 'AM']:
alleles.append(allele.upper())
if alleles:
# Remove duplicates and sort for comparison
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()
# Handle AMEL specially
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
# Find common markers
common_markers = set(sample_markers.keys()) & set(known_person_markers.keys())
if not common_markers:
return 0, 0, 0
# Count matching markers
matches = 0
perfect_matches = 0
for marker in common_markers:
# Normalize and parse alleles
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(',')])
# Check if alleles match (at least one allele in common for heterozygotes)
# Or exact match for homozygotes
if sample_alleles & ref_alleles: # Any common allele
matches += 1
if sample_alleles == ref_alleles: # Exact match
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 = []
# 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, perfect_score = match_person_to_reference_v2(
sample_genotype, person_markers
)
# Use a threshold: need at least 70% matching alleles
if match_score >= 0.7:
known_matches.append((person_id, matches, match_score, perfect_score))
# Sort by perfect score (exact matches), then by match score
known_matches.sort(key=lambda x: (x[3], x[2]), reverse=True)
# For multi-person samples, deduplicate based on uniqueness
# If we have more matches than contributors, assume they're the same person identified multiple times
# by different markers
# Conservative approach: assume each high-quality match is one known person
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)
# 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)}...", end='\r')
# 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_v2(csv_path, num_contributors)
if not sample_genotype:
continue
# Match to reference
num_known, num_unknown, known_matches = identify_known_unknown_contributors_v2(
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_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()