File size: 31,694 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
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "a95b4e07",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:54:22.466046Z",
     "iopub.status.busy": "2025-03-25T06:54:22.465630Z",
     "iopub.status.idle": "2025-03-25T06:54:22.629564Z",
     "shell.execute_reply": "2025-03-25T06:54:22.629238Z"
    }
   },
   "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 = \"Bile_Duct_Cancer\"\n",
    "cohort = \"GSE107754\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Bile_Duct_Cancer\"\n",
    "in_cohort_dir = \"../../input/GEO/Bile_Duct_Cancer/GSE107754\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Bile_Duct_Cancer/GSE107754.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Bile_Duct_Cancer/gene_data/GSE107754.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Bile_Duct_Cancer/clinical_data/GSE107754.csv\"\n",
    "json_path = \"../../output/preprocess/Bile_Duct_Cancer/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a541ad13",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "d762c8dd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:54:22.630953Z",
     "iopub.status.busy": "2025-03-25T06:54:22.630822Z",
     "iopub.status.idle": "2025-03-25T06:54:22.851668Z",
     "shell.execute_reply": "2025-03-25T06:54:22.851243Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"A novel genomic signature predicting FDG uptake in diverse metastatic tumors\"\n",
      "!Series_summary\t\"Purpose: Building a universal genomic signature predicting the intensity of FDG uptake in diverse metastatic tumors may allow us to understand better the biological processes underlying this phenomenon and their requirements of glucose uptake.\"\n",
      "!Series_summary\t\"Methods: A balanced training set (n=71) of metastatic tumors including some of the most frequent histologies, with matched PET/CT quantification measurements and whole human genome gene expression microarrays, was used to build the signature. Selection of microarray features was carried out exclusively on the basis of their strong association with FDG uptake (as measured by SUVmean35) by means of univariate linear regression. A thorough bioinformatics study of these genes was performed and multivariable models were built by fitting several state of the art regression techniques to the training set for comparison.\"\n",
      "!Series_summary\t\"Results: The 909 probes with the strongest association with the SUVmean35 (comprising 742 identifiable genes and 62 probes not matched to a symbol) were used to build the signature. Partial Least Squares using 3 components (PLS-3) was the best performing model in the training dataset cross-validation (Root Mean Square Error, RMSE=0.443) and was validated further in an independent validation dataset (n=13) obtaining a performance within the 95% CI of that obtained in the training dataset (RMSE=0.645). Significantly overrepresented biological processes correlating with the SUVmean35 were identified beyond glycolysis, such as ribosome biogenesis and DNA replication (correlating with a higher SUVmean35), and cytoskeleton reorganization and autophagy (correlating with a lower SUVmean35), among others.\"\n",
      "!Series_summary\t\"Conclusions: PLS-3 is a signature predicting accurately the intensity of FDG uptake in diverse metastatic tumors. FDG-PET might help in the design of specific targeted therapies directed to counteract the identified malignant biological processes more likely activated in a tumor as inferred from the SUVmean35 and also from its variations in response to antineoplastic treatments.\"\n",
      "!Series_overall_design\t\"Whole human genome microarrays from biopsies of human metastatic tumors (71 patients) with matched SUVmean35 measurements, this submission includes the 71 patients of the training set used to build the genomic signature predicting FDG uptake in diverse metastatic tumors. This dataset is complemented with a validation set comprised of 13 patients.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['gender: Male', 'gender: Female'], 1: ['dataset: Validation set', 'dataset: Training set'], 2: ['biopsy location: Lung', 'biopsy location: Lymph node', 'biopsy location: Primary', 'biopsy location: Liver', 'biopsy location: Retroperitoneal implant', 'tissue: Pancreatic cancer', 'tissue: Esophagus cancer', 'tissue: Breast cancer', 'tissue: Colorectal cancer', 'tissue: Ovarian cancer', 'tissue: Head&neck cancer', 'tissue: Lung cancer', 'tissue: Malignant Melanoma', 'tissue: Endometrial cancer', 'tissue: Cervix cancer', 'tissue: Soft tissue sarcoma', 'tissue: Gastric cancer', 'tissue: Unknown primary', 'tissue: Malignant Mesothelioma', 'tissue: Thyroid cancer', 'tissue: Testes cancer', 'tissue: Non Hodgkin lymphoma', 'tissue: Merkel cell carcinoma', 'tissue: Vaginal cancer', 'tissue: Kidney cancer', 'tissue: Cervical cancer', 'tissue: Bile duct cancer', 'tissue: Urothelial cancer'], 3: ['suvmean35: 4.09', 'suvmean35: 8.36', 'suvmean35: 5.18', 'suvmean35: 10.74', 'suvmean35: 8.62', 'suvmean35: 8.02', 'suvmean35: 6.87', 'suvmean35: 4.93', 'suvmean35: 1.96', 'suvmean35: 8.83', 'suvmean35: 3.96', 'suvmean35: 3.38', 'suvmean35: 9.95', 'suvmean35: 5.19', 'suvmean35: 7.22', 'suvmean35: 5.02', 'suvmean35: 4.92', 'suvmean35: 4.99', 'suvmean35: 4.01', 'suvmean35: 2.52', 'suvmean35: 5.52', 'suvmean35: 8.38', 'suvmean35: 3.46', 'suvmean35: 4.07', 'suvmean35: 4.67', 'suvmean35: 7.09', 'suvmean35: 4.83', 'suvmean35: 6.7', 'suvmean35: 3.95', 'suvmean35: 5.03']}\n"
     ]
    }
   ],
   "source": [
    "from tools.preprocess import *\n",
    "# 1. Identify the paths to the SOFT file and the matrix file\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
    "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
    "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
    "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
    "\n",
    "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
    "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
    "\n",
    "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
    "print(\"Background Information:\")\n",
    "print(background_info)\n",
    "print(\"Sample Characteristics Dictionary:\")\n",
    "print(sample_characteristics_dict)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "78d03c00",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "e915b9d3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:54:22.853247Z",
     "iopub.status.busy": "2025-03-25T06:54:22.853145Z",
     "iopub.status.idle": "2025-03-25T06:54:22.864238Z",
     "shell.execute_reply": "2025-03-25T06:54:22.863954Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of clinical features: {'GSM2878070': [0.0, 1.0], 'GSM2878071': [0.0, 0.0], 'GSM2878072': [0.0, 1.0], 'GSM2878073': [0.0, 1.0], 'GSM2878074': [0.0, 0.0], 'GSM2878075': [0.0, 1.0], 'GSM2878076': [0.0, 0.0], 'GSM2878077': [0.0, 0.0], 'GSM2878078': [0.0, 0.0], 'GSM2878079': [0.0, 0.0], 'GSM2878080': [0.0, 0.0], 'GSM2878081': [0.0, 0.0], 'GSM2878082': [0.0, 0.0], 'GSM2891194': [0.0, 1.0], 'GSM2891195': [0.0, 1.0], 'GSM2891196': [0.0, 0.0], 'GSM2891197': [0.0, 0.0], 'GSM2891198': [0.0, 0.0], 'GSM2891199': [0.0, 0.0], 'GSM2891200': [0.0, 0.0], 'GSM2891201': [0.0, 1.0], 'GSM2891202': [0.0, 1.0], 'GSM2891203': [0.0, 0.0], 'GSM2891204': [0.0, 0.0], 'GSM2891205': [0.0, 1.0], 'GSM2891206': [0.0, 0.0], 'GSM2891207': [0.0, 0.0], 'GSM2891208': [0.0, 1.0], 'GSM2891209': [0.0, 1.0], 'GSM2891210': [0.0, 0.0], 'GSM2891211': [0.0, 0.0], 'GSM2891212': [0.0, 0.0], 'GSM2891213': [0.0, 0.0], 'GSM2891214': [0.0, 0.0], 'GSM2891215': [0.0, 1.0], 'GSM2891216': [0.0, 0.0], 'GSM2891217': [0.0, 1.0], 'GSM2891218': [0.0, 0.0], 'GSM2891219': [0.0, 0.0], 'GSM2891220': [0.0, 1.0], 'GSM2891221': [0.0, 0.0], 'GSM2891222': [0.0, 1.0], 'GSM2891223': [0.0, 0.0], 'GSM2891224': [0.0, 1.0], 'GSM2891225': [0.0, 1.0], 'GSM2891226': [0.0, 0.0], 'GSM2891227': [0.0, 1.0], 'GSM2891228': [0.0, 0.0], 'GSM2891229': [0.0, 0.0], 'GSM2891230': [0.0, 1.0], 'GSM2891231': [0.0, 1.0], 'GSM2891232': [0.0, 1.0], 'GSM2891233': [0.0, 1.0], 'GSM2891234': [0.0, 0.0], 'GSM2891235': [0.0, 0.0], 'GSM2891236': [0.0, 1.0], 'GSM2891237': [0.0, 0.0], 'GSM2891238': [0.0, 0.0], 'GSM2891239': [0.0, 0.0], 'GSM2891240': [0.0, 1.0], 'GSM2891241': [0.0, 1.0], 'GSM2891242': [0.0, 1.0], 'GSM2891243': [0.0, 0.0], 'GSM2891244': [0.0, 0.0], 'GSM2891245': [0.0, 0.0], 'GSM2891246': [0.0, 0.0], 'GSM2891247': [0.0, 1.0], 'GSM2891248': [0.0, 0.0], 'GSM2891249': [0.0, 0.0], 'GSM2891250': [0.0, 0.0], 'GSM2891251': [0.0, 0.0], 'GSM2891252': [0.0, 0.0], 'GSM2891253': [0.0, 0.0], 'GSM2891254': [0.0, 0.0], 'GSM2891255': [0.0, 1.0], 'GSM2891256': [1.0, 1.0], 'GSM2891257': [0.0, 1.0], 'GSM2891258': [0.0, 1.0], 'GSM2891259': [0.0, 0.0], 'GSM2891260': [1.0, 1.0], 'GSM2891261': [0.0, 0.0], 'GSM2891262': [0.0, 1.0], 'GSM2891263': [0.0, 1.0], 'GSM2891264': [0.0, 1.0]}\n",
      "Clinical features saved to ../../output/preprocess/Bile_Duct_Cancer/clinical_data/GSE107754.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Analyze gene expression data availability\n",
    "# From the background information, this dataset appears to contain whole human genome gene expression microarrays,\n",
    "# which suggests gene expression data is available\n",
    "is_gene_available = True\n",
    "\n",
    "# 2.1 Identify available data rows\n",
    "# For trait data: looking at row 2 which contains tissue information including \"Bile duct cancer\"\n",
    "trait_row = 2  # This contains tissue types including bile duct cancer\n",
    "\n",
    "# Age is not available in the sample characteristics dictionary\n",
    "age_row = None\n",
    "\n",
    "# Gender is available in row 0\n",
    "gender_row = 0\n",
    "\n",
    "# 2.2 Define conversion functions\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert tissue values to binary for bile duct cancer.\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon if it exists\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Check if the value indicates bile duct cancer\n",
    "    # The exact match in the data is 'tissue: Bile duct cancer'\n",
    "    if 'bile duct cancer' in value.lower():\n",
    "        return 1\n",
    "    else:\n",
    "        return 0\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"\n",
    "    Since age data is not available, this function is a placeholder.\n",
    "    In real use, it would convert age values to a continuous format.\n",
    "    \"\"\"\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender values to binary (0 for female, 1 for male).\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon if it exists\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Convert to lowercase for case-insensitive comparison\n",
    "    value_lower = value.lower()\n",
    "    \n",
    "    if 'female' in value_lower:\n",
    "        return 0\n",
    "    elif 'male' in value_lower:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save metadata\n",
    "is_trait_available = trait_row is not None\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. If trait data is available, extract clinical features\n",
    "if trait_row is not None:\n",
    "    # Create directory for clinical data if it doesn't exist\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    \n",
    "    # Select clinical features from clinical_data DataFrame\n",
    "    clinical_features = geo_select_clinical_features(\n",
    "        clinical_df=clinical_data,  # Assumed to be pre-loaded from previous step\n",
    "        trait=trait,\n",
    "        trait_row=trait_row,\n",
    "        convert_trait=convert_trait,\n",
    "        age_row=age_row,\n",
    "        convert_age=convert_age,\n",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender\n",
    "    )\n",
    "    \n",
    "    # Preview the selected clinical features\n",
    "    preview = preview_df(clinical_features)\n",
    "    print(f\"Preview of clinical features: {preview}\")\n",
    "    \n",
    "    # Save the clinical features to the output file\n",
    "    clinical_features.to_csv(out_clinical_data_file)\n",
    "    print(f\"Clinical features saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "29d5c98c",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "2853e70a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:54:22.865436Z",
     "iopub.status.busy": "2025-03-25T06:54:22.865336Z",
     "iopub.status.idle": "2025-03-25T06:54:23.224308Z",
     "shell.execute_reply": "2025-03-25T06:54:23.223888Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056',\n",
      "       'A_23_P100074', 'A_23_P100092', 'A_23_P100103', 'A_23_P100111',\n",
      "       'A_23_P100127', 'A_23_P100133', 'A_23_P100141', 'A_23_P100156',\n",
      "       'A_23_P100177', 'A_23_P100189', 'A_23_P100196', 'A_23_P100203',\n",
      "       'A_23_P100220', 'A_23_P100240', 'A_23_P10025', 'A_23_P100263'],\n",
      "      dtype='object', name='ID')\n"
     ]
    }
   ],
   "source": [
    "# 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.\n",
    "gene_data = get_genetic_data(matrix_file)\n",
    "\n",
    "# 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.\n",
    "print(gene_data.index[:20])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b5a45ec0",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "abbd6391",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:54:23.225868Z",
     "iopub.status.busy": "2025-03-25T06:54:23.225752Z",
     "iopub.status.idle": "2025-03-25T06:54:23.227617Z",
     "shell.execute_reply": "2025-03-25T06:54:23.227339Z"
    }
   },
   "outputs": [],
   "source": [
    "# Looking at the gene identifiers, I can see that they start with \"A_23_P\" followed by numbers\n",
    "# These are not standard human gene symbols (like BRCA1, TP53, etc.)\n",
    "# Instead, these appear to be Agilent microarray probe IDs which need to be mapped to gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "11a860d3",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "9abaacd4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:54:23.228812Z",
     "iopub.status.busy": "2025-03-25T06:54:23.228710Z",
     "iopub.status.idle": "2025-03-25T06:54:28.112183Z",
     "shell.execute_reply": "2025-03-25T06:54:28.111794Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074'], 'SPOT_ID': ['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074'], 'CONTROL_TYPE': ['FALSE', 'FALSE', 'FALSE', 'FALSE', 'FALSE'], 'REFSEQ': ['NM_207446', 'NM_005829', 'NM_014848', 'NM_194272', 'NM_020371'], 'GB_ACC': ['NM_207446', 'NM_005829', 'NM_014848', 'NM_194272', 'NM_020371'], 'GENE': [400451.0, 10239.0, 9899.0, 348093.0, 57099.0], 'GENE_SYMBOL': ['FAM174B', 'AP3S2', 'SV2B', 'RBPMS2', 'AVEN'], 'GENE_NAME': ['family with sequence similarity 174, member B', 'adaptor-related protein complex 3, sigma 2 subunit', 'synaptic vesicle glycoprotein 2B', 'RNA binding protein with multiple splicing 2', 'apoptosis, caspase activation inhibitor'], 'UNIGENE_ID': ['Hs.27373', 'Hs.632161', 'Hs.21754', 'Hs.436518', 'Hs.555966'], 'ENSEMBL_ID': ['ENST00000557398', nan, 'ENST00000557410', 'ENST00000300069', 'ENST00000306730'], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': ['ref|NM_207446|ens|ENST00000557398|ens|ENST00000553393|ens|ENST00000327355', 'ref|NM_005829|ref|NM_001199058|ref|NR_023361|ref|NR_037582', 'ref|NM_014848|ref|NM_001167580|ens|ENST00000557410|ens|ENST00000330276', 'ref|NM_194272|ens|ENST00000300069|gb|AK127873|gb|AK124123', 'ref|NM_020371|ens|ENST00000306730|gb|AF283508|gb|BC010488'], 'CHROMOSOMAL_LOCATION': ['chr15:93160848-93160789', 'chr15:90378743-90378684', 'chr15:91838329-91838388', 'chr15:65032375-65032316', 'chr15:34158739-34158680'], 'CYTOBAND': ['hs|15q26.1', 'hs|15q26.1', 'hs|15q26.1', 'hs|15q22.31', 'hs|15q14'], 'DESCRIPTION': ['Homo sapiens family with sequence similarity 174, member B (FAM174B), mRNA [NM_207446]', 'Homo sapiens adaptor-related protein complex 3, sigma 2 subunit (AP3S2), transcript variant 1, mRNA [NM_005829]', 'Homo sapiens synaptic vesicle glycoprotein 2B (SV2B), transcript variant 1, mRNA [NM_014848]', 'Homo sapiens RNA binding protein with multiple splicing 2 (RBPMS2), mRNA [NM_194272]', 'Homo sapiens apoptosis, caspase activation inhibitor (AVEN), mRNA [NM_020371]'], 'GO_ID': ['GO:0016020(membrane)|GO:0016021(integral to membrane)', 'GO:0005794(Golgi apparatus)|GO:0006886(intracellular protein transport)|GO:0008565(protein transporter activity)|GO:0016020(membrane)|GO:0016192(vesicle-mediated transport)|GO:0030117(membrane coat)|GO:0030659(cytoplasmic vesicle membrane)|GO:0031410(cytoplasmic vesicle)', 'GO:0001669(acrosomal vesicle)|GO:0006836(neurotransmitter transport)|GO:0016020(membrane)|GO:0016021(integral to membrane)|GO:0022857(transmembrane transporter activity)|GO:0030054(cell junction)|GO:0030672(synaptic vesicle membrane)|GO:0031410(cytoplasmic vesicle)|GO:0045202(synapse)', 'GO:0000166(nucleotide binding)|GO:0003676(nucleic acid binding)', 'GO:0005515(protein binding)|GO:0005622(intracellular)|GO:0005624(membrane fraction)|GO:0006915(apoptosis)|GO:0006916(anti-apoptosis)|GO:0012505(endomembrane system)|GO:0016020(membrane)'], 'SEQUENCE': ['ATCTCATGGAAAAGCTGGATTCCTCTGCCTTACGCAGAAACACCCGGGCTCCATCTGCCA', 'TCAAGTATTGGCCTGACATAGAGTCCTTAAGACAAGCAAAGACAAGCAAGGCAAGCACGT', 'ATGTCGGCTGTGGAGGGTTAAAGGGATGAGGCTTTCCTTTGTTTAGCAAATCTGTTCACA', 'CCCTGTCAGATAAGTTTAATGTTTAGTTTGAGGCATGAAGAAGAAAAGGGTTTCCATTCT', 'GACCAGCCAGTTTACAAGCATGTCTCAAGCTAGTGTGTTCCATTATGCTCACAGCAGTAA']}\n"
     ]
    }
   ],
   "source": [
    "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "\n",
    "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
    "print(\"Gene annotation preview:\")\n",
    "print(preview_df(gene_annotation))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "13be5f90",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "d4eb996f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:54:28.113532Z",
     "iopub.status.busy": "2025-03-25T06:54:28.113412Z",
     "iopub.status.idle": "2025-03-25T06:54:28.362503Z",
     "shell.execute_reply": "2025-03-25T06:54:28.362076Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data preview (after mapping):\n",
      "(18488, 84)\n",
      "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT',\n",
      "       'AAAS', 'AACS', 'AADAC', 'AADACL2', 'AADAT', 'AAGAB', 'AAK1', 'AAMP',\n",
      "       'AANAT', 'AARS', 'AARS2', 'AARSD1'],\n",
      "      dtype='object', name='Gene')\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify which columns in the gene annotation dataframe contain the probe IDs and gene symbols\n",
    "probe_col = 'ID'\n",
    "gene_symbol_col = 'GENE_SYMBOL'\n",
    "\n",
    "# 2. Get the gene mapping dataframe using the two identified columns\n",
    "gene_mapping = get_gene_mapping(gene_annotation, probe_col, gene_symbol_col)\n",
    "\n",
    "# 3. Convert probe-level measurements to gene expression data\n",
    "# This applies the gene mapping and handles the many-to-many relationship between probes and genes\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "\n",
    "# Preview the resulting gene expression data\n",
    "print(\"Gene expression data preview (after mapping):\")\n",
    "print(gene_data.shape)\n",
    "print(gene_data.index[:20])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f2f3a98f",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "93822286",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:54:28.364032Z",
     "iopub.status.busy": "2025-03-25T06:54:28.363919Z",
     "iopub.status.idle": "2025-03-25T06:54:34.363245Z",
     "shell.execute_reply": "2025-03-25T06:54:34.362923Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Original gene count: 18488\n",
      "Normalized gene count: 18247\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Bile_Duct_Cancer/gene_data/GSE107754.csv\n",
      "Loaded clinical data from file.\n",
      "Clinical data shape: (2, 84)\n",
      "Clinical data sample:\n",
      "                  GSM2878070  GSM2878071  GSM2878072  GSM2878073  GSM2878074  \\\n",
      "Bile_Duct_Cancer         0.0         0.0         0.0         0.0         0.0   \n",
      "Gender                   1.0         0.0         1.0         1.0         0.0   \n",
      "\n",
      "                  GSM2878075  GSM2878076  GSM2878077  GSM2878078  GSM2878079  \\\n",
      "Bile_Duct_Cancer         0.0         0.0         0.0         0.0         0.0   \n",
      "Gender                   1.0         0.0         0.0         0.0         0.0   \n",
      "\n",
      "                  ...  GSM2891255  GSM2891256  GSM2891257  GSM2891258  \\\n",
      "Bile_Duct_Cancer  ...         0.0         1.0         0.0         0.0   \n",
      "Gender            ...         1.0         1.0         1.0         1.0   \n",
      "\n",
      "                  GSM2891259  GSM2891260  GSM2891261  GSM2891262  GSM2891263  \\\n",
      "Bile_Duct_Cancer         0.0         1.0         0.0         0.0         0.0   \n",
      "Gender                   0.0         1.0         0.0         1.0         1.0   \n",
      "\n",
      "                  GSM2891264  \n",
      "Bile_Duct_Cancer         0.0  \n",
      "Gender                   1.0  \n",
      "\n",
      "[2 rows x 84 columns]\n",
      "Clinical data shape before linking: (2, 84)\n",
      "First few sample IDs in clinical data:\n",
      "['GSM2878070', 'GSM2878071', 'GSM2878072', 'GSM2878073', 'GSM2878074']\n",
      "First few sample IDs in gene data:\n",
      "['GSM2878070', 'GSM2878071', 'GSM2878072', 'GSM2878073', 'GSM2878074']\n",
      "Number of common samples between clinical and gene data: 84\n",
      "Linked data shape: (84, 18249)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data shape after handling missing values: (84, 18249)\n",
      "For the feature 'Bile_Duct_Cancer', the least common label is '1.0' with 2 occurrences. This represents 2.38% of the dataset.\n",
      "The distribution of the feature 'Bile_Duct_Cancer' in this dataset is severely biased.\n",
      "\n",
      "For the feature 'Gender', the least common label is '1.0' with 35 occurrences. This represents 41.67% of the dataset.\n",
      "The distribution of the feature 'Gender' in this dataset is fine.\n",
      "\n",
      "A new JSON file was created at: ../../output/preprocess/Bile_Duct_Cancer/cohort_info.json\n",
      "The dataset was determined to be not usable for analysis due to bias in the trait distribution.\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "# First, normalize gene symbols using the function from the library\n",
    "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Original gene count: {len(gene_data)}\")\n",
    "print(f\"Normalized gene count: {len(normalized_gene_data)}\")\n",
    "\n",
    "# Create directory for the gene data file if it doesn't exist\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "\n",
    "# Save the normalized gene data to a CSV file\n",
    "normalized_gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
    "\n",
    "# 2. We need to first load or recreate the selected_clinical_df\n",
    "try:\n",
    "    # Try to load the previously saved clinical data\n",
    "    selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)\n",
    "    # Fix index to ensure proper row names\n",
    "    selected_clinical_df.index = [trait, 'Gender']\n",
    "    print(\"Loaded clinical data from file.\")\n",
    "    print(f\"Clinical data shape: {selected_clinical_df.shape}\")\n",
    "    print(\"Clinical data sample:\")\n",
    "    print(selected_clinical_df.head())\n",
    "except Exception as e:\n",
    "    print(f\"Error loading clinical data: {e}\")\n",
    "    # If loading fails, recreate the clinical features\n",
    "    print(\"Recreating clinical features from raw data...\")\n",
    "    selected_clinical_df = geo_select_clinical_features(\n",
    "        clinical_df=clinical_data,\n",
    "        trait=trait,\n",
    "        trait_row=trait_row,\n",
    "        convert_trait=convert_trait,\n",
    "        age_row=age_row,\n",
    "        convert_age=convert_age,\n",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender\n",
    "    )\n",
    "\n",
    "# Link the clinical and genetic data\n",
    "print(f\"Clinical data shape before linking: {selected_clinical_df.shape}\")\n",
    "print(\"First few sample IDs in clinical data:\")\n",
    "print(list(selected_clinical_df.columns)[:5])\n",
    "print(\"First few sample IDs in gene data:\")\n",
    "print(list(normalized_gene_data.columns)[:5])\n",
    "\n",
    "# Check for column overlap\n",
    "common_samples = set(selected_clinical_df.columns).intersection(set(normalized_gene_data.columns))\n",
    "print(f\"Number of common samples between clinical and gene data: {len(common_samples)}\")\n",
    "\n",
    "# Link the clinical and genetic data\n",
    "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "\n",
    "# Check if linking was successful\n",
    "if len(linked_data) == 0 or trait not in linked_data.columns:\n",
    "    print(\"Linking clinical and genetic data failed - no valid rows or trait column missing\")\n",
    "    \n",
    "    # Check what columns are in the linked data\n",
    "    if len(linked_data.columns) > 0:\n",
    "        print(\"Columns in linked data:\")\n",
    "        print(list(linked_data.columns)[:10])  # Print first 10 columns\n",
    "    \n",
    "    # Set is_usable to False and save cohort info\n",
    "    is_usable = validate_and_save_cohort_info(\n",
    "        is_final=True, \n",
    "        cohort=cohort, \n",
    "        info_path=json_path, \n",
    "        is_gene_available=True, \n",
    "        is_trait_available=True, \n",
    "        is_biased=True,  # Consider it biased if linking fails\n",
    "        df=pd.DataFrame({trait: [], 'Gender': []}), \n",
    "        note=\"Data linking failed - unable to process gene expression data appropriately.\"\n",
    "    )\n",
    "    print(\"The dataset was determined to be not usable for analysis.\")\n",
    "else:\n",
    "    # 3. Handle missing values in the linked data\n",
    "    linked_data = handle_missing_values(linked_data, trait)\n",
    "    \n",
    "    print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
    "    \n",
    "    # 4. Determine whether the trait and demographic features are severely biased\n",
    "    is_trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "    \n",
    "    # 5. Conduct quality check and save the cohort information.\n",
    "    note = \"Dataset contains gene expression data from metastatic tumors including bile duct cancer samples with matched FDG uptake measurements.\"\n",
    "    is_usable = validate_and_save_cohort_info(\n",
    "        is_final=True, \n",
    "        cohort=cohort, \n",
    "        info_path=json_path, \n",
    "        is_gene_available=True, \n",
    "        is_trait_available=True, \n",
    "        is_biased=is_trait_biased, \n",
    "        df=linked_data, \n",
    "        note=note\n",
    "    )\n",
    "    \n",
    "    # 6. If the linked data is usable, save it as a CSV file.\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(\"The dataset was determined to be not usable for analysis due to bias in the trait distribution.\")"
   ]
  }
 ],
 "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
}