import os import pandas as pd import pickle from sklearn.model_selection import KFold import re # 1. Absolute Paths (Using Linux paths) CSV_PATH = "/home/user10/survivalanalysis/CMTLNet/CMTLNet/clinicaldata.csv" DATA_ROOT = "/home/user10/survivalanalysis/data/ucsf_preprocess" SAVE_DIR = "/home/user10/survivalanalysis/CMTLNet/CMTLNet" # 2. Load Clinical Data try: df = pd.read_csv(CSV_PATH) except FileNotFoundError: print(f"ERROR: Could not find {CSV_PATH}. Please check the path.") exit() valid_patients = [] labels_1p19q = [] labels_IDH = [] labels_LHG = [] for index, row in df.iterrows(): raw_id = str(row['ID']).strip() # Process the ID safely if '-' in raw_id: prefix, num_part = raw_id.rsplit("-", 1) match = re.match(r"^(\d+)", num_part) if match: clean_id = f"{prefix}-{int(match.group(1)):04d}" patient_folder = os.path.join(DATA_ROOT, clean_id) # Only process if the preprocessed folder actually exists if os.path.exists(patient_folder): # --- ROBUST STRING TO INT MAPPING LOGIC --- # 1. IDH: Map 'wildtype' -> 0, anything else (mutated) -> 1 val_idh = str(row.get('IDH', 'wildtype')).lower() idh_val = 0 if ('wildtype' in val_idh or 'unknown' in val_idh) else 1 # 2. Grade (LHG): HGG (Grade 4) -> 1, LGG (Grade 2/3) -> 0 val_grade = str(row.get('WHO CNS Grade', '2')).strip() lhg_val = 1 if ('4' in val_grade or 'IV' in val_grade.upper()) else 0 # 3. 1p19q: 'co-deletion' -> 1, 'intact' -> 0 val_1p19q = str(row.get('1p/19q', 'intact')).lower() p19q_val = 1 if 'deletion' in val_1p19q else 0 # ------------------------------------------ valid_patients.append(patient_folder) labels_IDH.append(idh_val) labels_LHG.append(lhg_val) labels_1p19q.append(p19q_val) print(f"Found {len(valid_patients)} completely preprocessed patients.") if len(valid_patients) == 0: print(f"ERROR: Found 0 patients. Check if {DATA_ROOT} has the folders.") exit() # 3. Create 5-Fold Splits kf = KFold(n_splits=5, shuffle=True, random_state=1337) def create_pkl_structure(paths, labels): data_struct = {'train': {}, 'test': {}} for fold, (train_idx, test_idx) in enumerate(kf.split(paths)): train_paths = [paths[i] for i in train_idx] train_labels = [labels[i] for i in train_idx] test_paths = [paths[i] for i in test_idx] test_labels = [labels[i] for i in test_idx] data_struct['train'][f'fold{fold}'] = {'path': train_paths, 'cls_label': train_labels} data_struct['test'][f'fold{fold}'] = {'path': test_paths, 'cls_label': test_labels} return data_struct # 4. Save to .pkl in the main directory print("Generating PKL files...") with open(os.path.join(SAVE_DIR, 'IDH.pkl'), 'wb') as f: pickle.dump(create_pkl_structure(valid_patients, labels_IDH), f) with open(os.path.join(SAVE_DIR, 'LHG.pkl'), 'wb') as f: pickle.dump(create_pkl_structure(valid_patients, labels_LHG), f) with open(os.path.join(SAVE_DIR, '1p19q.pkl'), 'wb') as f: pickle.dump(create_pkl_structure(valid_patients, labels_1p19q), f) print(f"Done! IDH.pkl, LHG.pkl, and 1p19q.pkl successfully saved in {SAVE_DIR}")