File size: 26,473 Bytes
82732bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "16c30f84",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:10:32.651638Z",
     "iopub.status.busy": "2025-03-25T05:10:32.651529Z",
     "iopub.status.idle": "2025-03-25T05:10:32.816817Z",
     "shell.execute_reply": "2025-03-25T05:10:32.816473Z"
    }
   },
   "outputs": [],
   "source": [
    "import sys\n",
    "import os\n",
    "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
    "\n",
    "# Path Configuration\n",
    "from tools.preprocess import *\n",
    "\n",
    "# Processing context\n",
    "trait = \"Epilepsy\"\n",
    "\n",
    "# Input paths\n",
    "tcga_root_dir = \"../../input/TCGA\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Epilepsy/TCGA.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Epilepsy/gene_data/TCGA.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Epilepsy/clinical_data/TCGA.csv\"\n",
    "json_path = \"../../output/preprocess/Epilepsy/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e7755166",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "2db494d1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:10:32.818329Z",
     "iopub.status.busy": "2025-03-25T05:10:32.818187Z",
     "iopub.status.idle": "2025-03-25T05:10:34.439784Z",
     "shell.execute_reply": "2025-03-25T05:10:34.439390Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Looking for a relevant cohort directory for Epilepsy...\n",
      "Available cohorts: ['TCGA_Liver_Cancer_(LIHC)', 'TCGA_Lower_Grade_Glioma_(LGG)', 'TCGA_lower_grade_glioma_and_glioblastoma_(GBMLGG)', 'TCGA_Lung_Adenocarcinoma_(LUAD)', 'TCGA_Lung_Cancer_(LUNG)', 'TCGA_Lung_Squamous_Cell_Carcinoma_(LUSC)', 'TCGA_Melanoma_(SKCM)', 'TCGA_Mesothelioma_(MESO)', 'TCGA_Ocular_melanomas_(UVM)', 'TCGA_Ovarian_Cancer_(OV)', 'TCGA_Pancreatic_Cancer_(PAAD)', 'TCGA_Pheochromocytoma_Paraganglioma_(PCPG)', 'TCGA_Prostate_Cancer_(PRAD)', 'TCGA_Rectal_Cancer_(READ)', 'TCGA_Sarcoma_(SARC)', 'TCGA_Stomach_Cancer_(STAD)', 'TCGA_Testicular_Cancer_(TGCT)', 'TCGA_Thymoma_(THYM)', 'TCGA_Thyroid_Cancer_(THCA)', 'TCGA_Uterine_Carcinosarcoma_(UCS)', '.DS_Store', 'CrawlData.ipynb', 'TCGA_Acute_Myeloid_Leukemia_(LAML)', 'TCGA_Adrenocortical_Cancer_(ACC)', 'TCGA_Bile_Duct_Cancer_(CHOL)', 'TCGA_Bladder_Cancer_(BLCA)', 'TCGA_Breast_Cancer_(BRCA)', 'TCGA_Cervical_Cancer_(CESC)', 'TCGA_Colon_and_Rectal_Cancer_(COADREAD)', 'TCGA_Colon_Cancer_(COAD)', 'TCGA_Endometrioid_Cancer_(UCEC)', 'TCGA_Esophageal_Cancer_(ESCA)', 'TCGA_Glioblastoma_(GBM)', 'TCGA_Head_and_Neck_Cancer_(HNSC)', 'TCGA_Kidney_Chromophobe_(KICH)', 'TCGA_Kidney_Clear_Cell_Carcinoma_(KIRC)', 'TCGA_Kidney_Papillary_Cell_Carcinoma_(KIRP)', 'TCGA_Large_Bcell_Lymphoma_(DLBC)']\n",
      "Epilepsy/neurological disease-related cohorts: ['TCGA_Lower_Grade_Glioma_(LGG)', 'TCGA_lower_grade_glioma_and_glioblastoma_(GBMLGG)', 'TCGA_Pheochromocytoma_Paraganglioma_(PCPG)', 'TCGA_Glioblastoma_(GBM)']\n",
      "Selected cohort: TCGA_lower_grade_glioma_and_glioblastoma_(GBMLGG)\n",
      "Clinical data file: TCGA.GBMLGG.sampleMap_GBMLGG_clinicalMatrix\n",
      "Genetic data file: TCGA.GBMLGG.sampleMap_HiSeqV2_PANCAN.gz\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Clinical data columns:\n",
      "['_INTEGRATION', '_PANCAN_CNA_PANCAN_K8', '_PANCAN_Cluster_Cluster_PANCAN', '_PANCAN_DNAMethyl_PANCAN', '_PANCAN_RPPA_PANCAN_K8', '_PANCAN_UNC_RNAseq_PANCAN_K16', '_PANCAN_mutation_PANCAN', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'additional_pharmaceutical_therapy', 'additional_radiation_therapy', 'additional_surgery_locoregional_procedure', 'additional_surgery_metastatic_procedure', 'age_at_initial_pathologic_diagnosis', 'animal_insect_allergy_history', 'animal_insect_allergy_types', 'asthma_history', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'days_to_additional_surgery_locoregional_procedure', 'days_to_additional_surgery_metastatic_procedure', 'days_to_birth', 'days_to_collection', 'days_to_death', 'days_to_initial_pathologic_diagnosis', 'days_to_last_followup', 'days_to_new_tumor_event_additional_surgery_procedure', 'days_to_new_tumor_event_after_initial_treatment', 'days_to_performance_status_assessment', 'eastern_cancer_oncology_group', 'eczema_history', 'family_history_of_cancer', 'family_history_of_primary_brain_tumor', 'first_diagnosis_age_asth_ecz_hay_fev_mold_dust', 'first_diagnosis_age_of_animal_insect_allergy', 'first_diagnosis_age_of_food_allergy', 'first_presenting_symptom', 'first_presenting_symptom_longest_duration', 'followup_case_report_form_submission_reason', 'followup_treatment_success', 'food_allergy_history', 'food_allergy_types', 'form_completion_date', 'gender', 'hay_fever_history', 'headache_history', 'histological_type', 'history_ionizing_rt_to_head', 'history_of_neoadjuvant_treatment', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'inherited_genetic_syndrome_found', 'inherited_genetic_syndrome_result', 'initial_pathologic_diagnosis_method', 'initial_weight', 'intermediate_dimension', 'is_ffpe', 'karnofsky_performance_score', 'laterality', 'ldh1_mutation_found', 'ldh1_mutation_test_method', 'ldh1_mutation_tested', 'longest_dimension', 'lost_follow_up', 'mental_status_changes', 'mold_or_dust_allergy_history', 'motor_movement_changes', 'neoplasm_histologic_grade', 'new_neoplasm_event_type', 'new_tumor_event_additional_surgery_procedure', 'new_tumor_event_after_initial_treatment', 'oct_embedded', 'other_dx', 'pathology_report_file_name', 'patient_id', 'performance_status_scale_timing', 'person_neoplasm_cancer_status', 'postoperative_rx_tx', 'preoperative_antiseizure_meds', 'preoperative_corticosteroids', 'primary_therapy_outcome_success', 'prior_glioma', 'radiation_therapy', 'sample_type', 'sample_type_id', 'seizure_history', 'sensory_changes', 'shortest_dimension', 'supratentorial_localization', 'targeted_molecular_therapy', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'tumor_location', 'tumor_tissue_site', 'vial_number', 'visual_changes', 'vital_status', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_GBMLGG_exp_HiSeqV2', '_GENOMIC_ID_TCGA_GBMLGG_PDMarrayCNV', '_GENOMIC_ID_TCGA_GBMLGG_mutation', '_GENOMIC_ID_TCGA_GBMLGG_hMethyl450', '_GENOMIC_ID_TCGA_GBMLGG_PDMarray', '_GENOMIC_ID_TCGA_GBMLGG_gistic2', '_GENOMIC_ID_TCGA_GBMLGG_PDMRNAseq', '_GENOMIC_ID_TCGA_GBMLGG_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_GBMLGG_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_GBMLGG_gistic2thd', '_GENOMIC_ID_TCGA_GBMLGG_exp_HiSeqV2_exon']\n",
      "\n",
      "Clinical data shape: (1148, 115)\n",
      "Genetic data shape: (20530, 702)\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "\n",
    "# Check if there's a suitable cohort directory for Epilepsy\n",
    "print(f\"Looking for a relevant cohort directory for {trait}...\")\n",
    "\n",
    "# Check available cohorts\n",
    "available_dirs = os.listdir(tcga_root_dir)\n",
    "print(f\"Available cohorts: {available_dirs}\")\n",
    "\n",
    "# Epilepsy-related keywords (looking for neurological/brain conditions that could be related to epilepsy)\n",
    "epilepsy_keywords = ['epilepsy', 'seizure', 'neurological', 'brain', 'glioma', 'gbm', 'lgg']\n",
    "\n",
    "# Look for epilepsy/neurological disease-related directories\n",
    "epilepsy_related_dirs = []\n",
    "for d in available_dirs:\n",
    "    if any(keyword in d.lower() for keyword in epilepsy_keywords):\n",
    "        epilepsy_related_dirs.append(d)\n",
    "\n",
    "print(f\"Epilepsy/neurological disease-related cohorts: {epilepsy_related_dirs}\")\n",
    "\n",
    "if not epilepsy_related_dirs:\n",
    "    print(f\"No suitable cohort found for {trait}.\")\n",
    "    # Mark the task as completed by recording the unavailability\n",
    "    validate_and_save_cohort_info(\n",
    "        is_final=False,\n",
    "        cohort=\"TCGA\",\n",
    "        info_path=json_path,\n",
    "        is_gene_available=False,\n",
    "        is_trait_available=False\n",
    "    )\n",
    "    # Exit the script early since no suitable cohort was found\n",
    "    selected_cohort = None\n",
    "else:\n",
    "    # For epilepsy, the lower grade glioma and glioblastoma combined dataset might be most relevant\n",
    "    # as these brain tumors are often associated with seizures\n",
    "    if 'TCGA_lower_grade_glioma_and_glioblastoma_(GBMLGG)' in epilepsy_related_dirs:\n",
    "        selected_cohort = 'TCGA_lower_grade_glioma_and_glioblastoma_(GBMLGG)'\n",
    "    else:\n",
    "        selected_cohort = epilepsy_related_dirs[0]  # Use the first match if the preferred one isn't available\n",
    "\n",
    "if selected_cohort:\n",
    "    print(f\"Selected cohort: {selected_cohort}\")\n",
    "    \n",
    "    # Get the full path to the selected cohort directory\n",
    "    cohort_dir = os.path.join(tcga_root_dir, selected_cohort)\n",
    "    \n",
    "    # Get the clinical and genetic data file paths\n",
    "    clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n",
    "    \n",
    "    print(f\"Clinical data file: {os.path.basename(clinical_file_path)}\")\n",
    "    print(f\"Genetic data file: {os.path.basename(genetic_file_path)}\")\n",
    "    \n",
    "    # Load the clinical and genetic data\n",
    "    clinical_df = pd.read_csv(clinical_file_path, index_col=0, sep='\\t')\n",
    "    genetic_df = pd.read_csv(genetic_file_path, index_col=0, sep='\\t')\n",
    "    \n",
    "    # Print the column names of the clinical data\n",
    "    print(\"\\nClinical data columns:\")\n",
    "    print(clinical_df.columns.tolist())\n",
    "    \n",
    "    # Basic info about the datasets\n",
    "    print(f\"\\nClinical data shape: {clinical_df.shape}\")\n",
    "    print(f\"Genetic data shape: {genetic_df.shape}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "199e7ebd",
   "metadata": {},
   "source": [
    "### Step 2: Find Candidate Demographic Features"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "df0f42a1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:10:34.441126Z",
     "iopub.status.busy": "2025-03-25T05:10:34.441012Z",
     "iopub.status.idle": "2025-03-25T05:10:34.455950Z",
     "shell.execute_reply": "2025-03-25T05:10:34.455645Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Age columns preview:\n",
      "{'age_at_initial_pathologic_diagnosis': [44.0, 50.0, 59.0, 56.0, 40.0], 'days_to_birth': [-16179.0, -18341.0, -21617.0, -20516.0, -14806.0], 'first_diagnosis_age_asth_ecz_hay_fev_mold_dust': [nan, nan, nan, nan, nan], 'first_diagnosis_age_of_animal_insect_allergy': [nan, nan, nan, nan, nan], 'first_diagnosis_age_of_food_allergy': [nan, nan, nan, nan, nan]}\n",
      "\n",
      "Gender columns preview:\n",
      "{'gender': ['FEMALE', 'MALE', 'MALE', 'FEMALE', 'FEMALE']}\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify candidate columns for age and gender\n",
    "candidate_age_cols = ['age_at_initial_pathologic_diagnosis', 'days_to_birth', 'first_diagnosis_age_asth_ecz_hay_fev_mold_dust', \n",
    "                     'first_diagnosis_age_of_animal_insect_allergy', 'first_diagnosis_age_of_food_allergy']\n",
    "candidate_gender_cols = ['gender']\n",
    "\n",
    "# 2. Get the clinical data file path\n",
    "cohort_dir = os.path.join(tcga_root_dir, 'TCGA_lower_grade_glioma_and_glioblastoma_(GBMLGG)')\n",
    "clinical_file_path, _ = tcga_get_relevant_filepaths(cohort_dir)\n",
    "\n",
    "# Load the clinical data\n",
    "clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n",
    "\n",
    "# Extract candidate columns and preview\n",
    "age_preview = {}\n",
    "for col in candidate_age_cols:\n",
    "    if col in clinical_df.columns:\n",
    "        age_preview[col] = clinical_df[col].head(5).tolist()\n",
    "\n",
    "gender_preview = {}\n",
    "for col in candidate_gender_cols:\n",
    "    if col in clinical_df.columns:\n",
    "        gender_preview[col] = clinical_df[col].head(5).tolist()\n",
    "\n",
    "print(\"Age columns preview:\")\n",
    "print(age_preview)\n",
    "print(\"\\nGender columns preview:\")\n",
    "print(gender_preview)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c2137589",
   "metadata": {},
   "source": [
    "### Step 3: Select Demographic Features"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "05ac3b28",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:10:34.457235Z",
     "iopub.status.busy": "2025-03-25T05:10:34.457121Z",
     "iopub.status.idle": "2025-03-25T05:10:34.460372Z",
     "shell.execute_reply": "2025-03-25T05:10:34.460076Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Selected age column: age_at_initial_pathologic_diagnosis\n",
      "Age column preview: [44.0, 50.0, 59.0, 56.0, 40.0]\n",
      "Selected gender column: gender\n",
      "Gender column preview: ['FEMALE', 'MALE', 'MALE', 'FEMALE', 'FEMALE']\n"
     ]
    }
   ],
   "source": [
    "# Analyze age columns\n",
    "age_columns = {\n",
    "    'age_at_initial_pathologic_diagnosis': [44.0, 50.0, 59.0, 56.0, 40.0], \n",
    "    'days_to_birth': [-16179.0, -18341.0, -21617.0, -20516.0, -14806.0], \n",
    "    'first_diagnosis_age_asth_ecz_hay_fev_mold_dust': [float('nan'), float('nan'), float('nan'), float('nan'), float('nan')], \n",
    "    'first_diagnosis_age_of_animal_insect_allergy': [float('nan'), float('nan'), float('nan'), float('nan'), float('nan')], \n",
    "    'first_diagnosis_age_of_food_allergy': [float('nan'), float('nan'), float('nan'), float('nan'), float('nan')]\n",
    "}\n",
    "\n",
    "# Select age column - choose between age_at_initial_pathologic_diagnosis and days_to_birth\n",
    "# age_at_initial_pathologic_diagnosis is more directly usable than days_to_birth (which is negative)\n",
    "age_col = 'age_at_initial_pathologic_diagnosis'\n",
    "\n",
    "# Analyze gender columns\n",
    "gender_columns = {'gender': ['FEMALE', 'MALE', 'MALE', 'FEMALE', 'FEMALE']}\n",
    "\n",
    "# Select gender column - only one candidate is available\n",
    "gender_col = 'gender'\n",
    "\n",
    "# Print the selected columns and their values\n",
    "print(f\"Selected age column: {age_col}\")\n",
    "print(f\"Age column preview: {age_columns[age_col]}\")\n",
    "print(f\"Selected gender column: {gender_col}\")\n",
    "print(f\"Gender column preview: {gender_columns[gender_col]}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e5c27a96",
   "metadata": {},
   "source": [
    "### Step 4: Feature Engineering and Validation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "f6ad9274",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:10:34.461455Z",
     "iopub.status.busy": "2025-03-25T05:10:34.461349Z",
     "iopub.status.idle": "2025-03-25T05:11:46.863514Z",
     "shell.execute_reply": "2025-03-25T05:11:46.863122Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical features (first 5 rows):\n",
      "                 Epilepsy   Age  Gender\n",
      "sampleID                               \n",
      "TCGA-02-0001-01         1  44.0     0.0\n",
      "TCGA-02-0003-01         1  50.0     1.0\n",
      "TCGA-02-0004-01         1  59.0     1.0\n",
      "TCGA-02-0006-01         1  56.0     0.0\n",
      "TCGA-02-0007-01         1  40.0     0.0\n",
      "\n",
      "Processing gene expression data...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Original gene data shape: (20530, 702)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Attempting to normalize gene symbols...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape after normalization: (19848, 702)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data saved to: ../../output/preprocess/Epilepsy/gene_data/TCGA.csv\n",
      "\n",
      "Linking clinical and genetic data...\n",
      "Clinical data shape: (1148, 3)\n",
      "Genetic data shape: (19848, 702)\n",
      "Number of common samples: 702\n",
      "\n",
      "Linked data shape: (702, 19851)\n",
      "Linked data preview (first 5 rows, first few columns):\n",
      "                 Epilepsy   Age  Gender      A1BG  A1BG-AS1\n",
      "TCGA-FG-A4MU-01         1  58.0     1.0  4.236714 -1.467213\n",
      "TCGA-HT-7478-01         1  36.0     1.0  2.646014 -2.607613\n",
      "TCGA-DU-A6S2-01         1  37.0     0.0  2.751714 -2.326013\n",
      "TCGA-QH-A6CZ-01         1  38.0     1.0  1.255714 -2.867213\n",
      "TCGA-DU-7292-01         1  69.0     1.0  3.046014 -1.780413\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Data shape after handling missing values: (702, 19851)\n",
      "\n",
      "Checking for bias in features:\n",
      "For the feature 'Epilepsy', the least common label is '0' with 5 occurrences. This represents 0.71% of the dataset.\n",
      "The distribution of the feature 'Epilepsy' in this dataset is fine.\n",
      "\n",
      "Quartiles for 'Age':\n",
      "  25%: 34.0\n",
      "  50% (Median): 46.0\n",
      "  75%: 59.0\n",
      "Min: 14.0\n",
      "Max: 89.0\n",
      "The distribution of the feature 'Age' in this dataset is fine.\n",
      "\n",
      "For the feature 'Gender', the least common label is '0.0' with 297 occurrences. This represents 42.31% of the dataset.\n",
      "The distribution of the feature 'Gender' in this dataset is fine.\n",
      "\n",
      "\n",
      "Performing final validation...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to: ../../output/preprocess/Epilepsy/TCGA.csv\n",
      "Clinical data saved to: ../../output/preprocess/Epilepsy/clinical_data/TCGA.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Extract and standardize clinical features\n",
    "# Use tcga_select_clinical_features which will automatically create the trait variable and add age/gender if provided\n",
    "# Use the correct cohort identified in Step 1\n",
    "cohort_dir = os.path.join(tcga_root_dir, 'TCGA_lower_grade_glioma_and_glioblastoma_(GBMLGG)')\n",
    "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n",
    "\n",
    "# Load the clinical data if not already loaded\n",
    "clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n",
    "\n",
    "linked_clinical_df = tcga_select_clinical_features(\n",
    "    clinical_df, \n",
    "    trait=trait, \n",
    "    age_col=age_col, \n",
    "    gender_col=gender_col\n",
    ")\n",
    "\n",
    "# Print preview of clinical features\n",
    "print(\"Clinical features (first 5 rows):\")\n",
    "print(linked_clinical_df.head())\n",
    "\n",
    "# 2. Process gene expression data\n",
    "print(\"\\nProcessing gene expression data...\")\n",
    "# Load genetic data from the same cohort directory\n",
    "genetic_df = pd.read_csv(genetic_file_path, sep='\\t', index_col=0)\n",
    "\n",
    "# Check gene data shape\n",
    "print(f\"Original gene data shape: {genetic_df.shape}\")\n",
    "\n",
    "# Save a version of the gene data before normalization (as a backup)\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "genetic_df.to_csv(out_gene_data_file.replace('.csv', '_original.csv'))\n",
    "\n",
    "# We need to transpose genetic data so genes are rows and samples are columns for normalization\n",
    "gene_df_for_norm = genetic_df.copy()  # Keep original orientation for now\n",
    "\n",
    "# Try to normalize gene symbols - adding debug output to understand what's happening\n",
    "print(\"Attempting to normalize gene symbols...\")\n",
    "try:\n",
    "    # First check if we need to transpose based on the data format\n",
    "    # In TCGA data, typically genes are rows and samples are columns\n",
    "    if gene_df_for_norm.shape[0] > gene_df_for_norm.shape[1]:\n",
    "        # More rows than columns, likely genes are rows already\n",
    "        normalized_gene_df = normalize_gene_symbols_in_index(gene_df_for_norm)\n",
    "    else:\n",
    "        # Need to transpose first\n",
    "        normalized_gene_df = normalize_gene_symbols_in_index(gene_df_for_norm.T)\n",
    "        \n",
    "    print(f\"Gene data shape after normalization: {normalized_gene_df.shape}\")\n",
    "    \n",
    "    # Check if normalization returned empty DataFrame\n",
    "    if normalized_gene_df.shape[0] == 0:\n",
    "        print(\"WARNING: Gene symbol normalization returned an empty DataFrame.\")\n",
    "        print(\"Using original gene data instead of normalized data.\")\n",
    "        # Use original data\n",
    "        normalized_gene_df = genetic_df\n",
    "    \n",
    "except Exception as e:\n",
    "    print(f\"Error during gene symbol normalization: {e}\")\n",
    "    print(\"Using original gene data instead.\")\n",
    "    normalized_gene_df = genetic_df\n",
    "\n",
    "# Save gene data\n",
    "normalized_gene_df.to_csv(out_gene_data_file)\n",
    "print(f\"Gene data saved to: {out_gene_data_file}\")\n",
    "\n",
    "# 3. Link clinical and genetic data\n",
    "# TCGA data uses the same sample IDs in both datasets\n",
    "print(\"\\nLinking clinical and genetic data...\")\n",
    "print(f\"Clinical data shape: {linked_clinical_df.shape}\")\n",
    "print(f\"Genetic data shape: {normalized_gene_df.shape}\")\n",
    "\n",
    "# Find common samples between clinical and genetic data\n",
    "# In TCGA, samples are typically columns in the gene data and index in the clinical data\n",
    "common_samples = set(linked_clinical_df.index).intersection(set(normalized_gene_df.columns))\n",
    "print(f\"Number of common samples: {len(common_samples)}\")\n",
    "\n",
    "if len(common_samples) == 0:\n",
    "    print(\"ERROR: No common samples found between clinical and genetic data.\")\n",
    "    # Try the alternative orientation\n",
    "    common_samples = set(linked_clinical_df.index).intersection(set(normalized_gene_df.index))\n",
    "    print(f\"Checking alternative orientation: {len(common_samples)} common samples found.\")\n",
    "    \n",
    "    if len(common_samples) == 0:\n",
    "        # Use is_final=False mode which doesn't require df and is_biased\n",
    "        validate_and_save_cohort_info(\n",
    "            is_final=False,\n",
    "            cohort=\"TCGA\",\n",
    "            info_path=json_path,\n",
    "            is_gene_available=True,\n",
    "            is_trait_available=True\n",
    "        )\n",
    "        print(\"The dataset was determined to be unusable for this trait due to no common samples. No data files were saved.\")\n",
    "else:\n",
    "    # Filter clinical data to only include common samples\n",
    "    linked_clinical_df = linked_clinical_df.loc[list(common_samples)]\n",
    "    \n",
    "    # Create linked data by merging\n",
    "    linked_data = pd.concat([linked_clinical_df, normalized_gene_df[list(common_samples)].T], axis=1)\n",
    "    \n",
    "    print(f\"\\nLinked data shape: {linked_data.shape}\")\n",
    "    print(\"Linked data preview (first 5 rows, first few columns):\")\n",
    "    display_cols = [trait, 'Age', 'Gender'] + list(linked_data.columns[3:5])\n",
    "    print(linked_data[display_cols].head())\n",
    "    \n",
    "    # 4. Handle missing values\n",
    "    linked_data = handle_missing_values(linked_data, trait)\n",
    "    print(f\"\\nData shape after handling missing values: {linked_data.shape}\")\n",
    "    \n",
    "    # 5. Check for bias in features\n",
    "    print(\"\\nChecking for bias in features:\")\n",
    "    is_trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "    \n",
    "    # 6. Validate and save cohort info\n",
    "    print(\"\\nPerforming final validation...\")\n",
    "    is_usable = validate_and_save_cohort_info(\n",
    "        is_final=True,\n",
    "        cohort=\"TCGA\",\n",
    "        info_path=json_path,\n",
    "        is_gene_available=len(linked_data.columns) > 3,  # More than just trait/age/gender columns\n",
    "        is_trait_available=trait in linked_data.columns,\n",
    "        is_biased=is_trait_biased,\n",
    "        df=linked_data,\n",
    "        note=\"Data from TCGA lower-grade glioma and glioblastoma cohort used for epilepsy analysis.\"\n",
    "    )\n",
    "    \n",
    "    # 7. Save linked data if usable\n",
    "    if is_usable:\n",
    "        os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "        linked_data.to_csv(out_data_file)\n",
    "        print(f\"Linked data saved to: {out_data_file}\")\n",
    "        \n",
    "        # Also save clinical data separately\n",
    "        os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "        clinical_columns = [col for col in linked_data.columns if col in [trait, 'Age', 'Gender']]\n",
    "        linked_data[clinical_columns].to_csv(out_clinical_data_file)\n",
    "        print(f\"Clinical data saved to: {out_clinical_data_file}\")\n",
    "    else:\n",
    "        print(\"The dataset was determined to be unusable for this trait. No data files were saved.\")"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}