File size: 6,889 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 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 | """
Metadata Validation Script
Checks consistency of S-OH_metadata.csv:
- Age range (15-89 years)
- Gender encoding (0/1)
- ICD-10 code consistency with D_class and D_bin_class mappings
- Temporal consistency: startTimeGases < endTimeGases < durationSec
- Unique patient IDs and no duplicate entries
"""
import pandas as pd
import json
from pathlib import Path
# ============================================
# CONFIGURATION
# ============================================
METADATA_PATH = Path("../metadata.csv")
DATA_DIR = Path("../data")
MANIFEST_PATH = DATA_DIR / "manifest.json"
# ICD-10 to D_class mapping
ICD10_TO_DCLASS = {'Z00': 0, 'E11': 1, 'K29': 2, 'K76': 3, 'B18': 4, 'C34': 5, 'N18': 6, 'J44': 7, 'A15': 8}
# ICD-10 to D_bin_class mapping (for Z00-vs-rest)
ICD10_TO_BIN = {'Z00': 0, 'E11': 1, 'K29': 1, 'K76': 1, 'B18': 1, 'C34': 1, 'N18': 1, 'J44': 1, 'A15': 1}
# Expected columns in metadata
EXPECTED_COLUMNS = [
'Patient_id', 'Patient_age', 'Patient_gender',
'Diagnosis', 'D_class', 'D_bin_class',
'Datetime', 'Week', 'Site'
]
# ============================================
# VALIDATION FUNCTIONS
# ============================================
def validate_age(metadata):
"""Check age range 15-89 years."""
ages = metadata['Patient_age']
invalid = (ages < 15) | (ages > 89)
n_invalid = invalid.sum()
if n_invalid > 0:
print(f"❌ Age validation FAILED: {n_invalid} patients outside 15-89 range")
print(f" Min: {ages.min()}, Max: {ages.max()}")
return False
print(f"✅ Age validation PASSED: {len(ages)} patients, range {ages.min()}-{ages.max()} years")
return True
def validate_gender(metadata):
"""Check gender encoding (0=female, 1=male)."""
gender = metadata['Patient_gender']
invalid = ~gender.isin(['female', 'male'])
n_invalid = invalid.sum()
if n_invalid > 0:
print(f"❌ Gender validation FAILED: {n_invalid} patients with invalid gender encoding")
print(f" Unique values: {gender.unique()}")
return False
n_female = (gender == 0).sum()
n_male = (gender == 1).sum()
print(f"✅ Gender validation PASSED: {n_female} female, {n_male} male")
return True
def validate_diagnosis_mapping(metadata):
"""Check ICD-10 code consistency with D_class and D_bin_class mappings."""
errors = []
for idx, row in metadata.iterrows():
diag = row['Diagnosis']
d_class = row['D_class']
d_bin = row['D_bin_class']
expected_class = ICD10_TO_DCLASS.get(diag)
expected_bin = ICD10_TO_BIN.get(diag)
if expected_class is None:
errors.append(f"Patient {row['Patient_id']}: unknown diagnosis '{diag}'")
continue
if d_class != expected_class:
errors.append(f"Patient {row['Patient_id']}: D_class {d_class} != expected {expected_class}")
if d_bin != expected_bin:
errors.append(f"Patient {row['Patient_id']}: D_bin_class {d_bin} != expected {expected_bin}")
if errors:
print(f"❌ Diagnosis mapping validation FAILED: {len(errors)} errors")
for err in errors[:10]: # show first 10
print(f" {err}")
if len(errors) > 10:
print(f" ... and {len(errors)-10} more")
return False
print(f"✅ Diagnosis mapping validation PASSED: {len(metadata)} patients")
return True
def validate_temporal_consistency(metadata, data_dir):
"""Check startTimeGases < endTimeGases < durationSec for each patient."""
errors = []
# Load manifest to get file paths
with open(MANIFEST_PATH, 'r') as f:
manifest = json.load(f)
# Create mapping from patient_id to file path
patient_file_map = {entry['patient_id']: entry['file'] for entry in manifest['files']}
for patient_id in metadata['Patient_id']:
if patient_id not in patient_file_map:
continue
file_path = data_dir / patient_file_map[patient_id]
if not file_path.exists():
errors.append(f"Patient {patient_id}: JSON file not found: {file_path}")
continue
with open(file_path, 'r') as f:
patient_data = json.load(f)
start_time = patient_data.get('startTimeGases', 0)
end_time = patient_data.get('endTimeGases', 0)
duration = patient_data.get('durationSec', 0)
if not (start_time < end_time < duration):
errors.append(f"Patient {patient_id}: temporal inconsistency: {start_time} < {end_time} < {duration} is False")
if errors:
print(f"❌ Temporal consistency validation FAILED: {len(errors)} errors")
for err in errors[:10]:
print(f" {err}")
return False
print(f"✅ Temporal consistency validation PASSED: {len(metadata)} patients")
return True
def validate_unique_ids(metadata):
"""Check for unique patient IDs and no duplicate entries."""
patient_ids = metadata['Patient_id']
n_unique = patient_ids.nunique()
n_total = len(patient_ids)
if n_unique != n_total:
duplicates = patient_ids[patient_ids.duplicated()].tolist()
print(f"❌ Unique IDs validation FAILED: {n_total - n_unique} duplicates found")
print(f" Duplicate IDs: {duplicates[:10]}")
return False
print(f"✅ Unique IDs validation PASSED: {n_unique} unique patients")
return True
def validate_columns(metadata):
"""Check that all expected columns are present."""
missing = [col for col in EXPECTED_COLUMNS if col not in metadata.columns]
if missing:
print(f"❌ Columns validation FAILED: missing columns: {missing}")
return False
print(f"✅ Columns validation PASSED: all {len(EXPECTED_COLUMNS)} columns present")
return True
def main():
print("=" * 60)
print("S-OH METADATA VALIDATION")
print("=" * 60)
# Load metadata
print(f"\nLoading metadata from: {METADATA_PATH}")
metadata = pd.read_csv(METADATA_PATH)
print(f"Loaded {len(metadata)} records")
all_passed = True
print("\n" + "-" * 40)
all_passed &= validate_columns(metadata)
print("\n" + "-" * 40)
all_passed &= validate_unique_ids(metadata)
print("\n" + "-" * 40)
all_passed &= validate_age(metadata)
print("\n" + "-" * 40)
all_passed &= validate_gender(metadata)
print("\n" + "-" * 40)
all_passed &= validate_diagnosis_mapping(metadata)
print("\n" + "-" * 40)
all_passed &= validate_temporal_consistency(metadata, DATA_DIR)
print("\n" + "=" * 60)
if all_passed:
print("✅ ALL CHECKS PASSED")
else:
print("❌ SOME CHECKS FAILED")
print("=" * 60)
return all_passed
if __name__ == "__main__":
main() |