File size: 8,728 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
244
245
246
247
248
249
250
251
"""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()