File size: 20,602 Bytes
736e4a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "95eebd67",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:54:14.839405Z",
     "iopub.status.busy": "2025-03-25T06:54:14.839184Z",
     "iopub.status.idle": "2025-03-25T06:54:15.002805Z",
     "shell.execute_reply": "2025-03-25T06:54:15.002474Z"
    }
   },
   "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 = \"Autoinflammatory_Disorders\"\n",
    "\n",
    "# Input paths\n",
    "tcga_root_dir = \"../../input/TCGA\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Autoinflammatory_Disorders/TCGA.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Autoinflammatory_Disorders/gene_data/TCGA.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Autoinflammatory_Disorders/clinical_data/TCGA.csv\"\n",
    "json_path = \"../../output/preprocess/Autoinflammatory_Disorders/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "56dd88d4",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "0525c11d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:54:15.004261Z",
     "iopub.status.busy": "2025-03-25T06:54:15.004126Z",
     "iopub.status.idle": "2025-03-25T06:54:15.161538Z",
     "shell.execute_reply": "2025-03-25T06:54:15.161158Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Available TCGA directories: ['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",
      "Potential matches for Autoinflammatory_Disorders: ['TCGA_Large_Bcell_Lymphoma_(DLBC)']\n",
      "\n",
      "Selected directory: TCGA_Large_Bcell_Lymphoma_(DLBC)\n",
      "Clinical data file: TCGA.DLBC.sampleMap_DLBC_clinicalMatrix\n",
      "Genetic data file: TCGA.DLBC.sampleMap_HiSeqV2_PANCAN.gz\n",
      "\n",
      "Clinical data columns:\n",
      "['_INTEGRATION', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'age_at_initial_pathologic_diagnosis', 'b_lymphocyte_genotyping_method', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'bone_marrow_biopsy_done', 'bone_marrow_involvement', 'bone_marrow_sample_histology', 'clinical_stage', 'days_to_birth', 'days_to_collection', 'days_to_death', 'days_to_initial_pathologic_diagnosis', 'days_to_last_followup', 'days_to_new_tumor_event_after_initial_treatment', 'eastern_cancer_oncology_group', 'ebv_positive_malignant_cells_percent', 'ebv_status_malignant_cells_method', 'epstein_barr_viral_status', 'extranodal_involvement', 'extranodal_involvment_site_other', 'extranodal_sites_involvement_number', 'first_progression_histology_type', 'first_progression_histology_type_other', 'first_recurrence_biopsy_confirmed', 'follicular_percent', 'followup_case_report_form_submission_reason', 'followup_treatment_success', 'form_completion_date', 'gender', 'genetic_abnormality_method_other', 'genetic_abnormality_results', 'genetic_abnormality_results_other', 'genetic_abnormality_tested', 'genetic_abnormality_tested_other', 'height', 'histological_type', 'history_immunological_disease', 'history_immunological_disease_other', 'history_immunosuppresive_rx', 'history_immunosuppressive_rx_other', 'history_of_neoadjuvant_treatment', 'history_relevant_infectious_dx', 'hiv_status', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'igh_genotype_results', 'immunophenotypic_analysis_method', 'immunophenotypic_analysis_results', 'immunophenotypic_analysis_tested', 'informed_consent_verified', 'initial_weight', 'intermediate_dimension', 'is_ffpe', 'ldh_level', 'ldh_norm_range_upper', 'longest_dimension', 'lost_follow_up', 'lymph_node_involvement_site', 'maximum_tumor_bulk_anatomic_site', 'maximum_tumor_dimension', 'mib1_positive_percentage_range', 'new_neoplasm_event_occurrence_anatomic_site', 'new_neoplasm_occurrence_anatomic_site_text', 'new_tumor_event_after_initial_treatment', 'oct_embedded', 'other_dx', 'pathology_report_file_name', 'patient_id', 'person_neoplasm_cancer_status', 'pet_scan_results', 'primary_therapy_outcome_success', 'radiation_therapy', 'sample_type', 'sample_type_id', 'shortest_dimension', 'system_version', 'targeted_molecular_therapy', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'tumor_tissue_site', 'vial_number', 'vital_status', 'weight', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_DLBC_exp_HiSeqV2', '_GENOMIC_ID_TCGA_DLBC_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_DLBC_PDMRNAseq', '_GENOMIC_ID_TCGA_DLBC_hMethyl450', '_GENOMIC_ID_TCGA_DLBC_miRNA_HiSeq', '_GENOMIC_ID_TCGA_DLBC_gistic2thd', '_GENOMIC_ID_TCGA_DLBC_PDMRNAseqCNV', '_GENOMIC_ID_data/public/TCGA/DLBC/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_DLBC_gistic2', '_GENOMIC_ID_TCGA_DLBC_mutation_bcm_gene', '_GENOMIC_ID_TCGA_DLBC_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_DLBC_RPPA', '_GENOMIC_ID_TCGA_DLBC_exp_HiSeqV2_PANCAN']\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "\n",
    "# List all subdirectories in tcga_root_dir\n",
    "subdirs = os.listdir(tcga_root_dir)\n",
    "print(f\"Available TCGA directories: {subdirs}\")\n",
    "\n",
    "# Check if there's any appropriate TCGA dataset for Autoinflammatory Disorders\n",
    "# Autoinflammatory disorders involve chronic inflammation which could be relevant to:\n",
    "# - Lymphomas (immune system cancers)\n",
    "# - Cancers with inflammatory components\n",
    "\n",
    "# Look for potential matches\n",
    "potential_matches = []\n",
    "immune_related = ['TCGA_Large_Bcell_Lymphoma_(DLBC)']  # Immune system cancers\n",
    "\n",
    "# Add immune-related cancers to potential matches\n",
    "for dir_name in subdirs:\n",
    "    if dir_name in immune_related:\n",
    "        potential_matches.append(dir_name)\n",
    "\n",
    "if potential_matches:\n",
    "    print(f\"Potential matches for {trait}: {potential_matches}\")\n",
    "    # Select the most specific match\n",
    "    selected_dir = potential_matches[0]  # First match as default\n",
    "    cohort_dir = os.path.join(tcga_root_dir, selected_dir)\n",
    "    \n",
    "    # Get paths to clinical and genetic files\n",
    "    clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n",
    "    \n",
    "    # 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",
    "    print(f\"\\nSelected directory: {selected_dir}\")\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",
    "    # Print column names of clinical data\n",
    "    print(\"\\nClinical data columns:\")\n",
    "    print(clinical_df.columns.tolist())\n",
    "    \n",
    "    # Check if gene expression and trait data are available\n",
    "    is_gene_available = not genetic_df.empty\n",
    "    is_trait_available = not clinical_df.empty\n",
    "    \n",
    "    # Only validate, don't finalize\n",
    "    validate_and_save_cohort_info(\n",
    "        is_final=False,\n",
    "        cohort=\"TCGA\",\n",
    "        info_path=json_path,\n",
    "        is_gene_available=is_gene_available,\n",
    "        is_trait_available=is_trait_available\n",
    "    )\n",
    "else:\n",
    "    print(f\"No suitable directory found for {trait}. While autoinflammatory disorders involve inflammation, TCGA datasets don't directly address these conditions.\")\n",
    "    \n",
    "    # Mark this cohort as not usable for Autoinflammatory Disorders research\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"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e9ac5294",
   "metadata": {},
   "source": [
    "### Step 2: Find Candidate Demographic Features"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "f0b27d6a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:54:15.162788Z",
     "iopub.status.busy": "2025-03-25T06:54:15.162669Z",
     "iopub.status.idle": "2025-03-25T06:54:15.168917Z",
     "shell.execute_reply": "2025-03-25T06:54:15.168624Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Age columns preview:\n",
      "{'age_at_initial_pathologic_diagnosis': [75, 67, 40, 73, 58], 'days_to_birth': [-27468, -24590, -14723, -27025, -21330]}\n",
      "\n",
      "Gender columns preview:\n",
      "{'gender': ['MALE', 'MALE', 'MALE', 'MALE', 'FEMALE']}\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify candidate columns for age and gender\n",
    "candidate_age_cols = ['age_at_initial_pathologic_diagnosis', 'days_to_birth']\n",
    "candidate_gender_cols = ['gender']\n",
    "\n",
    "# 2. Load the clinical data to preview the candidate columns\n",
    "clinical_file_path, _ = tcga_get_relevant_filepaths(os.path.join(tcga_root_dir, 'TCGA_Large_Bcell_Lymphoma_(DLBC)'))\n",
    "clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n",
    "\n",
    "# Preview age columns\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",
    "print(\"Age columns preview:\")\n",
    "print(age_preview)\n",
    "\n",
    "# Preview gender columns\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(\"\\nGender columns preview:\")\n",
    "print(gender_preview)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "09839d68",
   "metadata": {},
   "source": [
    "### Step 3: Select Demographic Features"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "5f6f8c33",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:54:15.169917Z",
     "iopub.status.busy": "2025-03-25T06:54:15.169814Z",
     "iopub.status.idle": "2025-03-25T06:54:15.172576Z",
     "shell.execute_reply": "2025-03-25T06:54:15.172300Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Selected age column: age_at_initial_pathologic_diagnosis\n",
      "Selected gender column: gender\n"
     ]
    }
   ],
   "source": [
    "# Check the age columns\n",
    "age_col = None\n",
    "if 'age_at_initial_pathologic_diagnosis' in {'age_at_initial_pathologic_diagnosis': [75, 67, 40, 73, 58], 'days_to_birth': [-27468, -24590, -14723, -27025, -21330]}:\n",
    "    # This column directly contains age values in years\n",
    "    age_col = 'age_at_initial_pathologic_diagnosis'\n",
    "elif 'days_to_birth' in {'age_at_initial_pathologic_diagnosis': [75, 67, 40, 73, 58], 'days_to_birth': [-27468, -24590, -14723, -27025, -21330]}:\n",
    "    # This column contains negative days from birth, which can be converted to age\n",
    "    age_col = 'days_to_birth'\n",
    "\n",
    "# Check the gender columns\n",
    "gender_col = None\n",
    "if 'gender' in {'gender': ['MALE', 'MALE', 'MALE', 'MALE', 'FEMALE']}:\n",
    "    gender_col = 'gender'\n",
    "\n",
    "# Print the selected columns\n",
    "print(f\"Selected age column: {age_col}\")\n",
    "print(f\"Selected gender column: {gender_col}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e5d4eae3",
   "metadata": {},
   "source": [
    "### Step 4: Feature Engineering and Validation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "2fbce4da",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:54:15.173577Z",
     "iopub.status.busy": "2025-03-25T06:54:15.173478Z",
     "iopub.status.idle": "2025-03-25T06:54:21.522870Z",
     "shell.execute_reply": "2025-03-25T06:54:21.522544Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Extracting clinical features...\n",
      "Clinical features shape: (48, 3)\n",
      "Preview of clinical features:\n",
      "                 Autoinflammatory_Disorders  Age  Gender\n",
      "sampleID                                                \n",
      "TCGA-FA-8693-01                           1   75       1\n",
      "TCGA-FA-A4BB-01                           1   67       1\n",
      "TCGA-FA-A4XK-01                           1   40       1\n",
      "TCGA-FA-A6HN-01                           1   73       1\n",
      "TCGA-FA-A6HO-01                           1   58       0\n",
      "Clinical data saved to ../../output/preprocess/Autoinflammatory_Disorders/clinical_data/TCGA.csv\n",
      "\n",
      "Normalizing gene expression data...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Original gene expression data shape: (20530, 48)\n",
      "Normalized gene expression data shape: (19848, 48)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene expression data saved to ../../output/preprocess/Autoinflammatory_Disorders/gene_data/TCGA.csv\n",
      "\n",
      "Linking clinical and genetic data...\n",
      "Number of common samples: 48\n",
      "Linked data shape: (48, 19851)\n",
      "\n",
      "Handling missing values...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Data shape after handling missing values: (48, 19851)\n",
      "\n",
      "Checking for biased features...\n",
      "Quartiles for 'Autoinflammatory_Disorders':\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 'Autoinflammatory_Disorders' in this dataset is severely biased.\n",
      "\n",
      "Quartiles for 'Age':\n",
      "  25%: 46.0\n",
      "  50% (Median): 57.5\n",
      "  75%: 67.0\n",
      "Min: 23\n",
      "Max: 82\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 22 occurrences. This represents 45.83% of the dataset.\n",
      "The distribution of the feature 'Gender' in this dataset is fine.\n",
      "\n",
      "\n",
      "Validating final data quality...\n",
      "\n",
      "Data is not usable. Linked data will not be saved.\n"
     ]
    }
   ],
   "source": [
    "# Step: Feature Engineering and Validation\n",
    "\n",
    "# 1. Extract and standardize clinical features\n",
    "print(\"\\nExtracting clinical features...\")\n",
    "clinical_features = tcga_select_clinical_features(\n",
    "    clinical_df, \n",
    "    trait=trait, \n",
    "    age_col=age_col, \n",
    "    gender_col=gender_col\n",
    ")\n",
    "\n",
    "print(f\"Clinical features shape: {clinical_features.shape}\")\n",
    "print(f\"Preview of clinical features:\\n{clinical_features.head()}\")\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",
    "\n",
    "# 2. Normalize gene symbols in the gene expression data\n",
    "print(\"\\nNormalizing gene expression data...\")\n",
    "genetic_df_normalized = normalize_gene_symbols_in_index(genetic_df)\n",
    "print(f\"Original gene expression data shape: {genetic_df.shape}\")\n",
    "print(f\"Normalized gene expression data shape: {genetic_df_normalized.shape}\")\n",
    "\n",
    "# Save the normalized gene data\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "genetic_df_normalized.to_csv(out_gene_data_file)\n",
    "print(f\"Normalized gene expression data saved to {out_gene_data_file}\")\n",
    "\n",
    "# 3. Link the clinical and genetic data on sample IDs\n",
    "print(\"\\nLinking clinical and genetic data...\")\n",
    "# Transpose genetic data to have samples as rows and genes as columns\n",
    "genetic_df_for_linking = genetic_df_normalized.T\n",
    "\n",
    "# Ensure sample IDs in clinical features match those in genetic data\n",
    "common_samples = clinical_features.index.intersection(genetic_df_for_linking.index)\n",
    "print(f\"Number of common samples: {len(common_samples)}\")\n",
    "\n",
    "# Filter both dataframes to keep only common samples\n",
    "clinical_features_common = clinical_features.loc[common_samples]\n",
    "genetic_df_common = genetic_df_for_linking.loc[common_samples]\n",
    "\n",
    "# Combine clinical and genetic data\n",
    "linked_data = pd.concat([clinical_features_common, genetic_df_common], axis=1)\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "\n",
    "# 4. Handle missing values systematically\n",
    "print(\"\\nHandling missing values...\")\n",
    "linked_data_clean = handle_missing_values(linked_data, trait_col=trait)\n",
    "print(f\"Data shape after handling missing values: {linked_data_clean.shape}\")\n",
    "\n",
    "# 5. Determine if trait or demographic features are biased\n",
    "print(\"\\nChecking for biased features...\")\n",
    "is_trait_biased, linked_data_clean = judge_and_remove_biased_features(linked_data_clean, trait)\n",
    "\n",
    "# 6. Validate data quality and save cohort information\n",
    "print(\"\\nValidating final 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=genetic_df_normalized.shape[0] > 0,\n",
    "    is_trait_available=clinical_features.shape[0] > 0,\n",
    "    is_biased=is_trait_biased,\n",
    "    df=linked_data_clean,\n",
    "    note=\"Pancreatic cancer dataset used as proxy for Type 2 Diabetes due to pancreatic involvement in diabetes.\"\n",
    ")\n",
    "\n",
    "# 7. Save the linked data if usable\n",
    "if is_usable:\n",
    "    print(f\"\\nData is usable. Saving linked data to {out_data_file}...\")\n",
    "    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "    linked_data_clean.to_csv(out_data_file)\n",
    "    print(f\"Linked data saved to {out_data_file}\")\n",
    "else:\n",
    "    print(\"\\nData is not usable. Linked data will not be 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
}