File size: 20,169 Bytes
d1894e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "aaaf388c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:16:35.014752Z",
     "iopub.status.busy": "2025-03-25T05:16:35.014580Z",
     "iopub.status.idle": "2025-03-25T05:16:35.206365Z",
     "shell.execute_reply": "2025-03-25T05:16:35.205892Z"
    }
   },
   "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 = \"Essential_Thrombocythemia\"\n",
    "\n",
    "# Input paths\n",
    "tcga_root_dir = \"../../input/TCGA\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Essential_Thrombocythemia/TCGA.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Essential_Thrombocythemia/gene_data/TCGA.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Essential_Thrombocythemia/clinical_data/TCGA.csv\"\n",
    "json_path = \"../../output/preprocess/Essential_Thrombocythemia/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4be07e45",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "75e0b835",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:16:35.207854Z",
     "iopub.status.busy": "2025-03-25T05:16:35.207705Z",
     "iopub.status.idle": "2025-03-25T05:16:35.458306Z",
     "shell.execute_reply": "2025-03-25T05:16:35.457854Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Available TCGA subdirectories: ['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",
      "Selected directory: TCGA_Adrenocortical_Cancer_(ACC)\n",
      "Clinical data file: ../../input/TCGA/TCGA_Adrenocortical_Cancer_(ACC)/TCGA.ACC.sampleMap_ACC_clinicalMatrix\n",
      "Genetic data file: ../../input/TCGA/TCGA_Adrenocortical_Cancer_(ACC)/TCGA.ACC.sampleMap_HiSeqV2_PANCAN.gz\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Clinical data columns:\n",
      "['_INTEGRATION', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'additional_pharmaceutical_therapy', 'additional_radiation_therapy', 'age_at_initial_pathologic_diagnosis', 'atypical_mitotic_figures', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'clinical_M', 'ct_scan_findings', 'cytoplasm_presence_less_than_equal_25_percent', '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', 'diffuse_architecture', 'distant_metastasis_anatomic_site', 'excess_adrenal_hormone_diagnosis_method_type', 'excess_adrenal_hormone_history_type', 'form_completion_date', 'gender', 'germline_testing_performed', 'histologic_disease_progression_present_indicator', 'histological_type', 'history_of_neoadjuvant_treatment', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'initial_weight', 'invasion_of_tumor_capsule', 'is_ffpe', 'laterality', 'lost_follow_up', 'lymph_node_examined_count', 'metastatic_neoplasm_confirmed_diagnosis_method_name', 'metastatic_neoplasm_confirmed_diagnosis_method_text', 'mitoses_count', 'mitotane_therapy', 'mitotane_therapy_adjuvant_setting', 'mitotane_therapy_for_macroscopic_residual_disease', 'mitotic_rate', 'necrosis', 'new_neoplasm_confirmed_diagnosis_method_name', 'new_neoplasm_event_occurrence_anatomic_site', 'new_neoplasm_event_type', 'new_neoplasm_occurrence_anatomic_site_text', 'new_tumor_event_additional_surgery_procedure', 'new_tumor_event_after_initial_treatment', 'nuclear_grade_III_IV', 'number_of_lymphnodes_positive_by_he', 'oct_embedded', 'other_dx', 'pathologic_N', 'pathologic_T', 'pathologic_stage', 'pathology_report_file_name', 'patient_id', 'person_neoplasm_cancer_status', 'post_surgical_procedure_assessment_thyroid_gland_carcinoma_stats', 'postoperative_rx_tx', 'primary_lymph_node_presentation_assessment', 'primary_therapy_outcome_success', 'radiation_therapy', 'residual_tumor', 'ret', 'sample_type', 'sample_type_id', 'sinusoid_invasion', 'therapeutic_mitotane_levels_achieved', 'therapeutic_mitotane_lvl_macroscopic_residual', 'therapeutic_mitotane_lvl_progression', 'therapeutic_mitotane_lvl_recurrence', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'tumor_tissue_site', 'vial_number', 'vital_status', 'weiss_score', 'weiss_venous_invasion', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_ACC_mutation_curated_bcm_gene', '_GENOMIC_ID_TCGA_ACC_exp_HiSeqV2_percentile', '_GENOMIC_ID_data/public/TCGA/ACC/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_ACC_miRNA_HiSeq', '_GENOMIC_ID_TCGA_ACC_RPPA', '_GENOMIC_ID_TCGA_ACC_hMethyl450', '_GENOMIC_ID_TCGA_ACC_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_ACC_exp_HiSeqV2', '_GENOMIC_ID_TCGA_ACC_gistic2thd', '_GENOMIC_ID_TCGA_ACC_PDMRNAseq', '_GENOMIC_ID_TCGA_ACC_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_ACC_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_ACC_gistic2', '_GENOMIC_ID_TCGA_ACC_mutation_bcm_gene', '_GENOMIC_ID_TCGA_ACC_mutation_curated_broad_gene']\n",
      "\n",
      "Clinical data shape: (92, 104)\n",
      "Genetic data shape: (20530, 79)\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "\n",
    "# Step 1: Look for directories related to Adrenocortical Cancer\n",
    "tcga_subdirs = os.listdir(tcga_root_dir)\n",
    "print(f\"Available TCGA subdirectories: {tcga_subdirs}\")\n",
    "\n",
    "# Look for directory related to Adrenocortical Cancer\n",
    "target_dir = None\n",
    "for subdir in tcga_subdirs:\n",
    "    # Look for exact match or synonymous terms\n",
    "    if trait.lower() in subdir.lower() or \"ACC\" in subdir:\n",
    "        target_dir = subdir\n",
    "        break\n",
    "\n",
    "if target_dir is None:\n",
    "    print(f\"No suitable directory found for {trait}.\")\n",
    "    # Mark the task as completed by creating a JSON record indicating data is not available\n",
    "    validate_and_save_cohort_info(is_final=False, cohort=\"TCGA\", info_path=json_path, \n",
    "                                 is_gene_available=False, is_trait_available=False)\n",
    "    exit()  # Exit the program\n",
    "\n",
    "# Step 2: Get file paths for the selected directory\n",
    "cohort_dir = os.path.join(tcga_root_dir, target_dir)\n",
    "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n",
    "\n",
    "print(f\"Selected directory: {target_dir}\")\n",
    "print(f\"Clinical data file: {clinical_file_path}\")\n",
    "print(f\"Genetic data file: {genetic_file_path}\")\n",
    "\n",
    "# Step 3: Load 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",
    "# Step 4: Print column names of clinical data\n",
    "print(\"\\nClinical data columns:\")\n",
    "print(clinical_df.columns.tolist())\n",
    "\n",
    "# Additional basic information\n",
    "print(f\"\\nClinical data shape: {clinical_df.shape}\")\n",
    "print(f\"Genetic data shape: {genetic_df.shape}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "817b5e19",
   "metadata": {},
   "source": [
    "### Step 2: Find Candidate Demographic Features"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "efc2fcbd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:16:35.459848Z",
     "iopub.status.busy": "2025-03-25T05:16:35.459510Z",
     "iopub.status.idle": "2025-03-25T05:16:35.466468Z",
     "shell.execute_reply": "2025-03-25T05:16:35.466092Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Age columns preview:\n",
      "{'age_at_initial_pathologic_diagnosis': [58, 44, 23, 23, 30], 'days_to_birth': [-21496, -16090, -8624, -8451, -11171]}\n",
      "Gender columns preview:\n",
      "{'gender': ['MALE', 'FEMALE', 'FEMALE', 'FEMALE', 'MALE']}\n"
     ]
    }
   ],
   "source": [
    "# Identify candidate age and gender columns\n",
    "candidate_age_cols = ['age_at_initial_pathologic_diagnosis', 'days_to_birth']\n",
    "candidate_gender_cols = ['gender']\n",
    "\n",
    "# Load the clinical data file path\n",
    "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(os.path.join(tcga_root_dir, 'TCGA_Adrenocortical_Cancer_(ACC)'))\n",
    "\n",
    "# Load the clinical data\n",
    "clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n",
    "\n",
    "# Extract and preview age columns\n",
    "if candidate_age_cols:\n",
    "    age_preview = {col: clinical_df[col].head(5).tolist() for col in candidate_age_cols}\n",
    "    print(\"Age columns preview:\")\n",
    "    print(age_preview)\n",
    "\n",
    "# Extract and preview gender columns\n",
    "if candidate_gender_cols:\n",
    "    gender_preview = {col: clinical_df[col].head(5).tolist() for col in candidate_gender_cols}\n",
    "    print(\"Gender columns preview:\")\n",
    "    print(gender_preview)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "078f1952",
   "metadata": {},
   "source": [
    "### Step 3: Select Demographic Features"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "1529ce68",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:16:35.467613Z",
     "iopub.status.busy": "2025-03-25T05:16:35.467500Z",
     "iopub.status.idle": "2025-03-25T05:16:35.471761Z",
     "shell.execute_reply": "2025-03-25T05:16:35.471295Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Evaluating age columns:\n",
      "  age_at_initial_pathologic_diagnosis: [58, 44, 23, 23, 30], Missing: 0.0%\n",
      "  days_to_birth: [-21496, -16090, -8624, -8451, -11171], Missing: 0.0%\n",
      "Evaluating gender columns:\n",
      "  gender: ['MALE', 'FEMALE', 'FEMALE', 'FEMALE', 'MALE'], Missing: 0.0%\n",
      "\n",
      "Chosen age column: age_at_initial_pathologic_diagnosis\n",
      "Chosen gender column: gender\n"
     ]
    }
   ],
   "source": [
    "# Examine potential age columns\n",
    "print(\"Evaluating age columns:\")\n",
    "for col_name, values in {'age_at_initial_pathologic_diagnosis': [58, 44, 23, 23, 30], 'days_to_birth': [-21496, -16090, -8624, -8451, -11171]}.items():\n",
    "    missing_count = sum(1 for v in values if v is None)\n",
    "    missing_percentage = missing_count / len(values) * 100 if values else 0\n",
    "    print(f\"  {col_name}: {values}, Missing: {missing_percentage}%\")\n",
    "\n",
    "# Examine potential gender columns\n",
    "print(\"Evaluating gender columns:\")\n",
    "for col_name, values in {'gender': ['MALE', 'FEMALE', 'FEMALE', 'FEMALE', 'MALE']}.items():\n",
    "    missing_count = sum(1 for v in values if v is None)\n",
    "    missing_percentage = missing_count / len(values) * 100 if values else 0\n",
    "    print(f\"  {col_name}: {values}, Missing: {missing_percentage}%\")\n",
    "\n",
    "# Select the best columns for age and gender\n",
    "age_col = \"age_at_initial_pathologic_diagnosis\"  # Contains direct age values which are easier to interpret\n",
    "gender_col = \"gender\"  # Contains standard gender information\n",
    "\n",
    "# Print the chosen columns\n",
    "print(f\"\\nChosen age column: {age_col}\")\n",
    "print(f\"Chosen gender column: {gender_col}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "82b0ab8c",
   "metadata": {},
   "source": [
    "### Step 4: Feature Engineering and Validation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "2f30cf98",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:16:35.473025Z",
     "iopub.status.busy": "2025-03-25T05:16:35.472908Z",
     "iopub.status.idle": "2025-03-25T05:16:42.955055Z",
     "shell.execute_reply": "2025-03-25T05:16:42.954730Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical data saved to ../../output/preprocess/Essential_Thrombocythemia/clinical_data/TCGA.csv\n",
      "Clinical data shape: (92, 3)\n",
      "                 Essential_Thrombocythemia  Age  Gender\n",
      "sampleID                                               \n",
      "TCGA-OR-A5J1-01                          1   58       1\n",
      "TCGA-OR-A5J2-01                          1   44       0\n",
      "TCGA-OR-A5J3-01                          1   23       0\n",
      "TCGA-OR-A5J4-01                          1   23       0\n",
      "TCGA-OR-A5J5-01                          1   30       1\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Essential_Thrombocythemia/gene_data/TCGA.csv\n",
      "Normalized gene data shape: (19848, 79)\n",
      "Linked data shape: (79, 19851)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "After handling missing values - linked data shape: (79, 19851)\n",
      "Quartiles for 'Essential_Thrombocythemia':\n",
      "  25%: 1.0\n",
      "  50% (Median): 1.0\n",
      "  75%: 1.0\n",
      "Min: 1\n",
      "Max: 1\n",
      "The distribution of the feature 'Essential_Thrombocythemia' in this dataset is severely biased.\n",
      "\n",
      "Quartiles for 'Age':\n",
      "  25%: 35.0\n",
      "  50% (Median): 49.0\n",
      "  75%: 59.5\n",
      "Min: 14\n",
      "Max: 77\n",
      "The distribution of the feature 'Age' in this dataset is fine.\n",
      "\n",
      "For the feature 'Gender', the least common label is '1' with 31 occurrences. This represents 39.24% of the dataset.\n",
      "The distribution of the feature 'Gender' in this dataset is fine.\n",
      "\n",
      "After removing biased features - linked data shape: (79, 19851)\n",
      "Linked data not saved due to quality concerns\n"
     ]
    }
   ],
   "source": [
    "# Step 1: Extract and standardize the clinical features\n",
    "# Get file paths\n",
    "cohort_dir = os.path.join(tcga_root_dir, 'TCGA_Adrenocortical_Cancer_(ACC)')\n",
    "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n",
    "\n",
    "# Load data\n",
    "clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n",
    "genetic_df = pd.read_csv(genetic_file_path, sep='\\t', index_col=0)\n",
    "\n",
    "# Create standardized clinical features dataframe with trait, age, and gender\n",
    "# The trait for Adrenocortical Cancer is based on tumor/normal classification\n",
    "clinical_features = tcga_select_clinical_features(\n",
    "    clinical_df, \n",
    "    trait=trait,  # Using predefined trait variable\n",
    "    age_col=age_col, \n",
    "    gender_col=gender_col\n",
    ")\n",
    "\n",
    "# Save clinical data\n",
    "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "clinical_features.to_csv(out_clinical_data_file)\n",
    "print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "print(f\"Clinical data shape: {clinical_features.shape}\")\n",
    "print(clinical_features.head())\n",
    "\n",
    "# Step 2: Normalize gene symbols in gene expression data\n",
    "# Transpose the genetic data to have genes as rows\n",
    "genetic_data = genetic_df.copy()\n",
    "\n",
    "# Normalize gene symbols using the NCBI Gene database synonyms\n",
    "normalized_gene_data = normalize_gene_symbols_in_index(genetic_data)\n",
    "\n",
    "# Save normalized gene data\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "normalized_gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
    "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n",
    "\n",
    "# Step 3: Link clinical and genetic data\n",
    "# Transpose genetic data to get samples as rows, genes as columns\n",
    "genetic_data_transposed = normalized_gene_data.T\n",
    "\n",
    "# Ensure clinical and genetic data have the same samples (index values)\n",
    "common_samples = clinical_features.index.intersection(genetic_data_transposed.index)\n",
    "clinical_subset = clinical_features.loc[common_samples]\n",
    "genetic_subset = genetic_data_transposed.loc[common_samples]\n",
    "\n",
    "# Combine clinical and genetic data\n",
    "linked_data = pd.concat([clinical_subset, genetic_subset], axis=1)\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "\n",
    "# Step 4: Handle missing values\n",
    "linked_data = handle_missing_values(linked_data, trait_col=trait)\n",
    "print(f\"After handling missing values - linked data shape: {linked_data.shape}\")\n",
    "\n",
    "# Step 5: Determine biased features\n",
    "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait=trait)\n",
    "print(f\"After removing biased features - linked data shape: {linked_data.shape}\")\n",
    "\n",
    "# Step 6: Validate data quality and save cohort info\n",
    "# First check if we have both gene and trait data\n",
    "is_gene_available = linked_data.shape[1] > 3  # More than just trait, Age, Gender\n",
    "is_trait_available = trait in linked_data.columns\n",
    "\n",
    "# Take notes of special findings\n",
    "notes = f\"TCGA Adrenocortical Cancer dataset processed. Used tumor/normal classification as the trait.\"\n",
    "\n",
    "# Validate the data quality\n",
    "is_usable = validate_and_save_cohort_info(\n",
    "    is_final=True,\n",
    "    cohort=\"TCGA\",\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available,\n",
    "    is_biased=is_biased,\n",
    "    df=linked_data,\n",
    "    note=notes\n",
    ")\n",
    "\n",
    "# Step 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",
    "else:\n",
    "    print(\"Linked data not saved due to quality concerns\")"
   ]
  }
 ],
 "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
}