""" 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()