File size: 10,472 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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
"""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()