File size: 3,492 Bytes
232c308
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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}")