File size: 6,319 Bytes
8ed1de7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Temporal Split Verification Script
Ensures:
- No patient appears in both training and test sets
- Training and test weeks are disjoint per disease
- Test set for each disease contains at least 10 samples
"""

import pandas as pd
import json
from pathlib import Path
from collections import defaultdict

# ============================================
# CONFIGURATION
# ============================================

METADATA_PATH = Path("../metadata.csv")
MANIFEST_PATH = Path("../data/manifest.json")

# Temporal splits: mapping of disease -> set of test weeks
# Based on Table 2 from the paper
TEMPORAL_SPLITS = {
    'Z00': {9, 10, 11},
    'E11': {1, 2, 3},
    'K29': {1, 2, 3},
    'K76': {2, 3, 4},
    'B18': {2, 3, 10},
    'C34': {8, 9, 10},
    'N18': {2, 3, 4},
    'J44': {5, 6, 7, 11},
    'A15': {13}
}


# ============================================
# VALIDATION FUNCTIONS
# ============================================

def load_metadata():
    """Load metadata CSV."""
    return pd.read_csv(METADATA_PATH)


def validate_patient_no_leakage(metadata):
    """Check that no patient appears in both train and test sets."""
    errors = []
    
    for disease in metadata['Diagnosis'].unique():
        disease_patients = metadata[metadata['Diagnosis'] == disease]
        test_weeks = TEMPORAL_SPLITS.get(disease, set())
        
        # Patients in test weeks
        test_patients = disease_patients[disease_patients['Week'].isin(test_weeks)]['Patient_id'].tolist()
        
        # Patients in training weeks
        train_patients = disease_patients[~disease_patients['Week'].isin(test_weeks)]['Patient_id'].tolist()
        
        # Check overlap
        overlap = set(test_patients) & set(train_patients)
        if overlap:
            errors.append(f"Patient leakage in {disease}: patients {overlap} appear in both train and test")
    
    if errors:
        print(f"❌ Patient leakage validation FAILED: {len(errors)} errors")
        for err in errors[:5]:
            print(f"   {err}")
        return False
    
    print("✅ Patient leakage validation PASSED: no patient appears in both train and test")
    return True


def validate_train_test_weeks_disjoint(metadata):
    """Check that training and test weeks are disjoint per disease."""
    errors = []
    
    for disease in metadata['Diagnosis'].unique():
        disease_patients = metadata[metadata['Diagnosis'] == disease]
        test_weeks = TEMPORAL_SPLITS.get(disease, set())
        all_weeks = set(disease_patients['Week'].unique())
        train_weeks = all_weeks - test_weeks
        
        # Check for overlap
        overlap = test_weeks & train_weeks
        if overlap:
            errors.append(f"Week overlap in {disease}: weeks {overlap} appear in both train and test")
        
        # Check that test weeks are actually present in the data
        missing_test_weeks = len(test_weeks - all_weeks)>2
        if missing_test_weeks:
            errors.append(f"Missing test weeks in {disease}: {missing_test_weeks} not present in data")
    
    if errors:
        print(f"❌ Week disjointness validation FAILED: {len(errors)} errors")
        for err in errors[:5]:
            print(f"   {err}")
        return False
    
    print("✅ Week disjointness validation PASSED: train and test weeks are disjoint per disease")
    return True


def validate_test_set_size(metadata):
    """Check that test set for each disease contains at least 10 samples."""
    errors = []
    
    for disease in metadata['Diagnosis'].unique():
        disease_patients = metadata[metadata['Diagnosis'] == disease]
        test_weeks = TEMPORAL_SPLITS.get(disease, set())
        
        test_patients = disease_patients[disease_patients['Week'].isin(test_weeks)]
        n_test = len(test_patients)
        
        if n_test < 10:
            errors.append(f"Test set too small in {disease}: {n_test} samples (min 10 required)")
    
    if errors:
        print(f"❌ Test set size validation FAILED: {len(errors)} errors")
        for err in errors:
            print(f"   {err}")
        return False
    
    # Print summary
    print("\nTest set sizes per disease:")
    for disease in metadata['Diagnosis'].unique():
        test_weeks = TEMPORAL_SPLITS.get(disease, set())
        disease_patients = metadata[metadata['Diagnosis'] == disease]
        test_patients = disease_patients[disease_patients['Week'].isin(test_weeks)]
        print(f"   {disease}: {len(test_patients)} samples")
    
    print("\n✅ Test set size validation PASSED: all diseases have ≥10 test samples")
    return True


def validate_manifest_consistency(metadata):
    """Check that all patients in metadata have a corresponding JSON file."""
    # Load manifest
    with open(MANIFEST_PATH, 'r') as f:
        manifest = json.load(f)
    
    manifest_ids = set(int(entry['patient_id']) for entry in manifest['files'])
    metadata_ids = set(metadata['Patient_id'])
    
    # Check missing in manifest
    missing_in_manifest = metadata_ids - manifest_ids
    if missing_in_manifest:
        print(f"⚠️  {len(missing_in_manifest)} patients in metadata not found in manifest")
        return False
    
    # Check extra in manifest
    extra_in_manifest = manifest_ids - metadata_ids
    if extra_in_manifest:
        print(f"⚠️  {len(extra_in_manifest)} patients in manifest not found in metadata")
        return False
    
    print(f"✅ Manifest consistency PASSED: {len(manifest_ids)} patients match")
    return True


def main():
    print("=" * 60)
    print("S-OH TEMPORAL SPLIT VALIDATION")
    print("=" * 60)
    
    metadata = load_metadata()
    print(f"Loaded {len(metadata)} records")
    
    all_passed = True
    
    print("\n" + "-" * 40)
    all_passed &= validate_manifest_consistency(metadata)
    
    print("\n" + "-" * 40)
    all_passed &= validate_patient_no_leakage(metadata)
    
    print("\n" + "-" * 40)
    all_passed &= validate_train_test_weeks_disjoint(metadata)
    
    print("\n" + "-" * 40)
    all_passed &= validate_test_set_size(metadata)
    
    print("\n" + "=" * 60)
    if all_passed:
        print("✅ ALL CHECKS PASSED")
    else:
        print("❌ SOME CHECKS FAILED")
    print("=" * 60)
    
    return all_passed


if __name__ == "__main__":
    main()