File size: 31,676 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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "2db3d5cc",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:57:28.978042Z",
     "iopub.status.busy": "2025-03-25T06:57:28.977867Z",
     "iopub.status.idle": "2025-03-25T06:57:29.145250Z",
     "shell.execute_reply": "2025-03-25T06:57:29.144893Z"
    }
   },
   "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 = \"Bladder_Cancer\"\n",
    "cohort = \"GSE222073\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Bladder_Cancer\"\n",
    "in_cohort_dir = \"../../input/GEO/Bladder_Cancer/GSE222073\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Bladder_Cancer/GSE222073.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Bladder_Cancer/gene_data/GSE222073.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Bladder_Cancer/clinical_data/GSE222073.csv\"\n",
    "json_path = \"../../output/preprocess/Bladder_Cancer/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "408fde1c",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "bf1b0f8b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:57:29.146536Z",
     "iopub.status.busy": "2025-03-25T06:57:29.146394Z",
     "iopub.status.idle": "2025-03-25T06:57:29.284560Z",
     "shell.execute_reply": "2025-03-25T06:57:29.284207Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Patterns of metastasis and recurrence in urothelial cancer molecular subtypes\"\n",
      "!Series_summary\t\"This series contains the gene expression data from urothelial bladder cancer samples from Swedish patients that were used to analyze metastatic sites. Included patients have a recurrence or distant metastasis before or after treatment with chemotherapy. Patients with only lymph-node metastases are not included. A previous series (GSE169455) contains data from all patients that recieved two or more cycles of neoadjuvant chemotherapy with curative intent. Patients in that series that developed distant recurrence are re-analyzed here. A few samples from a previous cystectomy series (GSE83586) are also included as re-analysis. In addition, the current series contains data from patients treated with palliative first-line chemotherapy, curative adjuvant chemotherapy, or < 2 cycles of neoadjuvant chemotherapy.\"\n",
      "!Series_summary\t\"Raw data should be adjusted in data processing for batch variables: Labeling batch and Labeling kit.\"\n",
      "!Series_overall_design\t\"Retrospective cohort study aiming to study metastatic sites and  chemotherapy response in muscle-invasive bladder cancer.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['labeling kit: SensationPlus FFPE Amplification and WT labeling kit', 'labeling kit: GeneChip WT Pico kit'], 1: ['labeling batch: 3', 'labeling batch: 4', 'labeling batch: 5', 'labeling batch: 6', 'labeling batch: 7', 'labeling batch: 8', 'labeling batch: 9', 'labeling batch: 10', 'labeling batch: 11', 'labeling batch: 13', 'labeling batch: 14', 'labeling batch: 15', 'labeling batch: 16', 'labeling batch: 17', 'labeling batch: 18', 'labeling batch: 19', 'labeling batch: 20', 'labeling batch: 21', 'labeling batch: 22', 'labeling batch: 23', 'labeling batch: 24', 'labeling batch: 25', 'labeling batch: 26', 'labeling batch: 27'], 2: ['clinical tnm staging: cTxN0M1', 'clinical tnm staging: cT3N0M0', 'clinical tnm staging: pT4aN1M0', 'clinical tnm staging: cT2N0M0', 'clinical tnm staging: cT4bN0M0', 'clinical tnm staging: cTxN2M1', 'clinical tnm staging: cTxN3M1', 'clinical tnm staging: cT3bN0M0', 'clinical tnm staging: cTxNxM1', 'clinical tnm staging: cT2N2M0', 'clinical tnm staging: CT3bN0M0', 'clinical tnm staging: cT4bN1M0', 'clinical tnm staging: pT3bN2M0', 'clinical tnm staging: cT1N3M1', 'clinical tnm staging: cT3N1M0', 'clinical tnm staging: cT4aN0M0', 'clinical tnm staging: cT4bN2M0', 'clinical tnm staging: cT4N0M0', 'clinical tnm staging: cT1N0M1', 'clinical tnm staging: cT2N0M1', 'clinical tnm staging: cT2N1M0', 'clinical tnm staging: cT3bN0M1', 'clinical tnm staging: cT3N1M1', 'clinical tnm staging: pT1N2M0', 'clinical tnm staging: pT4aN2M0', 'clinical tnm staging: cT3N2M1', 'clinical tnm staging: cT3aN2M0', 'clinical tnm staging: cT2N3M1', 'clinical tnm staging: pT2N2M0', 'clinical tnm staging: cT2N2M1'], 3: ['chemotherapy type: palliative', 'chemotherapy type: neoadjuvant', 'chemotherapy type: adjuvant', 'chemotherapy type: induction', 'chemotherapy type: curative radiochemotherapy', 'chemotherapy type: induction + radiotherapy'], 4: ['lundtax rna-subtype: UroC', 'lundtax rna-subtype: GU', 'lundtax rna-subtype: UroB', 'lundtax rna-subtype: UroA', 'lundtax rna-subtype: ScNE', 'lundtax rna-subtype: BASQ', 'lundtax rna-subtype: Mes'], 5: ['lundtax ihc-subtype: Uro', 'lundtax ihc-subtype: GU', 'lundtax ihc-subtype: BASQ', 'lundtax ihc-subtype: ScNE', 'lundtax ihc-subtype: Mes'], 6: ['consensus classifier subtype: LumNS', 'consensus classifier subtype: LumU', 'consensus classifier subtype: BASQ', 'consensus classifier subtype: StromaRich', 'consensus classifier subtype: LumP', 'consensus classifier subtype: NE_like'], 7: ['rm-lymphnode: no', 'rm-lymphnode: yes'], 8: ['rm-local: no', 'rm-local: yes'], 9: ['rm-lung: no', 'rm-lung: yes'], 10: ['rm-liver: no', 'rm-liver: yes'], 11: ['rm-bone: yes', 'rm-bone: no'], 12: ['rm-other: no', 'rm-other: yes']}\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": "caacbf57",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "61f0d6f2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:57:29.286163Z",
     "iopub.status.busy": "2025-03-25T06:57:29.286048Z",
     "iopub.status.idle": "2025-03-25T06:57:29.290774Z",
     "shell.execute_reply": "2025-03-25T06:57:29.290465Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical data file not found at ../../input/GEO/Bladder_Cancer/GSE222073/clinical_data.csv\n",
      "Skipping clinical feature extraction.\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# From the background information, it appears this dataset contains gene expression data for urothelial bladder cancer\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# For trait (Bladder Cancer)\n",
    "# From the provided sample characteristics, we can use bone metastasis information as our trait\n",
    "trait_row = 11  # Key 11 contains 'rm-bone: yes/no' data\n",
    "\n",
    "# Age is not explicitly mentioned in the sample characteristics\n",
    "age_row = None  \n",
    "\n",
    "# Gender is not explicitly mentioned in the sample characteristics\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "# For trait (bone metastasis in bladder cancer)\n",
    "def convert_trait(value):\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary (1 for yes, 0 for no)\n",
    "    if value.lower() == 'yes':\n",
    "        return 1\n",
    "    elif value.lower() == 'no':\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# Age conversion function (not used as age is not available)\n",
    "def convert_age(value):\n",
    "    return None\n",
    "\n",
    "# Gender conversion function (not used as gender is not available)\n",
    "def convert_gender(value):\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine if trait data is available\n",
    "is_trait_available = trait_row is not None\n",
    "# Initial filtering on usability\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. Clinical Feature Extraction\n",
    "if trait_row is not None:\n",
    "    try:\n",
    "        # Check if the clinical data file exists\n",
    "        if os.path.exists(f\"{in_cohort_dir}/clinical_data.csv\"):\n",
    "            # Load the clinical data and extract features\n",
    "            clinical_data = pd.read_csv(f\"{in_cohort_dir}/clinical_data.csv\")\n",
    "            \n",
    "            # Use the library function to extract features\n",
    "            selected_clinical = 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",
    "            # Preview the extracted features\n",
    "            print(preview_df(selected_clinical))\n",
    "            \n",
    "            # Save the clinical data\n",
    "            os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "            selected_clinical.to_csv(out_clinical_data_file, index=False)\n",
    "            print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "        else:\n",
    "            print(f\"Clinical data file not found at {in_cohort_dir}/clinical_data.csv\")\n",
    "            print(\"Skipping clinical feature extraction.\")\n",
    "    except Exception as e:\n",
    "        print(f\"Error processing clinical data: {e}\")\n",
    "        is_trait_available = False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4f106830",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "766f954b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:57:29.292252Z",
     "iopub.status.busy": "2025-03-25T06:57:29.292140Z",
     "iopub.status.idle": "2025-03-25T06:57:29.520354Z",
     "shell.execute_reply": "2025-03-25T06:57:29.520015Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['1-Mar', '2-Mar', '3-Mar', '4-Mar', '5-Mar', '6-Mar', '7-Mar', 'A2M',\n",
      "       'A2ML1', 'A4GALT', 'A4GNT', 'AAAS', 'AACS', 'AADAT', 'AAGAB', 'AAK1',\n",
      "       'AAMDC', 'AAMP', 'AANAT', 'AAR2'],\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": "b9310392",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "ff9e60c8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:57:29.522077Z",
     "iopub.status.busy": "2025-03-25T06:57:29.521946Z",
     "iopub.status.idle": "2025-03-25T06:57:29.524189Z",
     "shell.execute_reply": "2025-03-25T06:57:29.523869Z"
    }
   },
   "outputs": [],
   "source": [
    "# Examining the gene identifiers in the expression data\n",
    "\n",
    "# Based on the sample of gene identifiers shown, I observe:\n",
    "# - Many entries like \"A2M\", \"AAAS\", \"AAMP\" which appear to be standard HGNC gene symbols\n",
    "# - Some unusual entries like \"1-Mar\", \"2-Mar\" etc. which are not standard gene symbols \n",
    "#   (these are likely MARCH family genes that have been incorrectly formatted)\n",
    "\n",
    "# Since most identifiers appear to be gene symbols already but with some formatting issues,\n",
    "# I'll recommend mapping to ensure consistency\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c966be05",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "98aace6e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:57:29.525732Z",
     "iopub.status.busy": "2025-03-25T06:57:29.525626Z",
     "iopub.status.idle": "2025-03-25T06:57:31.658348Z",
     "shell.execute_reply": "2025-03-25T06:57:31.657934Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['LOC100287497', 'SAMD11', 'KLHL17', 'PLEKHN1', 'ISG15'], 'ORF': ['LOC100287497', 'SAMD11', 'KLHL17', 'PLEKHN1', 'ISG15']}\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": "1ba0d055",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "ca948e83",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:57:31.660042Z",
     "iopub.status.busy": "2025-03-25T06:57:31.659909Z",
     "iopub.status.idle": "2025-03-25T06:57:35.348166Z",
     "shell.execute_reply": "2025-03-25T06:57:35.347772Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Mapped gene data preview (first 5 genes):\n",
      "Index(['A2M', 'A2ML1', 'A4GALT', 'A4GNT', 'AAAS'], dtype='object', name='Gene')\n",
      "Total number of genes after mapping: 13409\n"
     ]
    }
   ],
   "source": [
    "# 1. After observing the data, it seems that:\n",
    "# - The gene expression data uses gene symbols directly as identifiers (e.g., A2M, AAAS)\n",
    "# - The gene annotation data has 'ID' and 'ORF' columns which both contain gene identifiers\n",
    "\n",
    "# Since the gene annotation preview data shows symbols like 'SAMD11', 'KLHL17', etc.\n",
    "# which are standard gene symbols, I'll use 'ID' as both the probe column and the gene column\n",
    "# for consistent mapping\n",
    "\n",
    "# 2. Get a gene mapping dataframe\n",
    "mapping_data = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='ORF')\n",
    "\n",
    "# 3. Apply the gene mapping to convert probe-level measurements to gene-level expression\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_data)\n",
    "\n",
    "# Preview the mapped gene data\n",
    "print(\"Mapped gene data preview (first 5 genes):\")\n",
    "print(gene_data.index[:5])\n",
    "print(f\"Total number of genes after mapping: {len(gene_data)}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8ff31fc0",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "8fbe72eb",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:57:35.349862Z",
     "iopub.status.busy": "2025-03-25T06:57:35.349750Z",
     "iopub.status.idle": "2025-03-25T06:57:44.799217Z",
     "shell.execute_reply": "2025-03-25T06:57:44.798822Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Original gene count: 13409\n",
      "Normalized gene count: 13362\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Bladder_Cancer/gene_data/GSE222073.csv\n",
      "Clinical data structure:\n",
      "(13, 147)\n",
      "First few rows of clinical data:\n",
      "         !Sample_geo_accession  \\\n",
      "0  !Sample_characteristics_ch1   \n",
      "1  !Sample_characteristics_ch1   \n",
      "2  !Sample_characteristics_ch1   \n",
      "3  !Sample_characteristics_ch1   \n",
      "4  !Sample_characteristics_ch1   \n",
      "\n",
      "                                          GSM6914278  \\\n",
      "0  labeling kit: SensationPlus FFPE Amplification...   \n",
      "1                                  labeling batch: 3   \n",
      "2                      clinical tnm staging: cTxN0M1   \n",
      "3                      chemotherapy type: palliative   \n",
      "4                          lundtax rna-subtype: UroC   \n",
      "\n",
      "                                          GSM6914279  \\\n",
      "0  labeling kit: SensationPlus FFPE Amplification...   \n",
      "1                                  labeling batch: 4   \n",
      "2                      clinical tnm staging: cT3N0M0   \n",
      "3                     chemotherapy type: neoadjuvant   \n",
      "4                            lundtax rna-subtype: GU   \n",
      "\n",
      "                                          GSM6914280  \\\n",
      "0  labeling kit: SensationPlus FFPE Amplification...   \n",
      "1                                  labeling batch: 4   \n",
      "2                     clinical tnm staging: pT4aN1M0   \n",
      "3                        chemotherapy type: adjuvant   \n",
      "4                            lundtax rna-subtype: GU   \n",
      "\n",
      "                                          GSM6914281  \\\n",
      "0  labeling kit: SensationPlus FFPE Amplification...   \n",
      "1                                  labeling batch: 5   \n",
      "2                      clinical tnm staging: cT3N0M0   \n",
      "3                     chemotherapy type: neoadjuvant   \n",
      "4                          lundtax rna-subtype: UroB   \n",
      "\n",
      "                                          GSM6914282  \\\n",
      "0  labeling kit: SensationPlus FFPE Amplification...   \n",
      "1                                  labeling batch: 6   \n",
      "2                      clinical tnm staging: cT2N0M0   \n",
      "3                     chemotherapy type: neoadjuvant   \n",
      "4                            lundtax rna-subtype: GU   \n",
      "\n",
      "                                          GSM6914283  \\\n",
      "0  labeling kit: SensationPlus FFPE Amplification...   \n",
      "1                                  labeling batch: 6   \n",
      "2                     clinical tnm staging: cT4bN0M0   \n",
      "3                       chemotherapy type: induction   \n",
      "4                            lundtax rna-subtype: GU   \n",
      "\n",
      "                                          GSM6914284  \\\n",
      "0  labeling kit: SensationPlus FFPE Amplification...   \n",
      "1                                  labeling batch: 7   \n",
      "2                      clinical tnm staging: cTxN2M1   \n",
      "3                      chemotherapy type: palliative   \n",
      "4                          lundtax rna-subtype: UroA   \n",
      "\n",
      "                                          GSM6914285  \\\n",
      "0  labeling kit: SensationPlus FFPE Amplification...   \n",
      "1                                  labeling batch: 8   \n",
      "2                      clinical tnm staging: cT2N0M0   \n",
      "3                     chemotherapy type: neoadjuvant   \n",
      "4                          lundtax rna-subtype: UroA   \n",
      "\n",
      "                                          GSM6914286  ...  \\\n",
      "0  labeling kit: SensationPlus FFPE Amplification...  ...   \n",
      "1                                  labeling batch: 8  ...   \n",
      "2                      clinical tnm staging: cTxN0M1  ...   \n",
      "3                      chemotherapy type: palliative  ...   \n",
      "4                            lundtax rna-subtype: GU  ...   \n",
      "\n",
      "                           GSM6914414                          GSM6914415  \\\n",
      "0  labeling kit: GeneChip WT Pico kit  labeling kit: GeneChip WT Pico kit   \n",
      "1                  labeling batch: 25                  labeling batch: 25   \n",
      "2      clinical tnm staging: cT3bN0M1       clinical tnm staging: cT4N2M1   \n",
      "3       chemotherapy type: palliative       chemotherapy type: palliative   \n",
      "4            lundtax rna-subtype: Mes           lundtax rna-subtype: BASQ   \n",
      "\n",
      "                           GSM6914416                          GSM6914417  \\\n",
      "0  labeling kit: GeneChip WT Pico kit  labeling kit: GeneChip WT Pico kit   \n",
      "1                  labeling batch: 25                  labeling batch: 26   \n",
      "2      clinical tnm staging: cT4aN0M1       clinical tnm staging: cTxN0M1   \n",
      "3       chemotherapy type: palliative       chemotherapy type: palliative   \n",
      "4           lundtax rna-subtype: UroA           lundtax rna-subtype: UroA   \n",
      "\n",
      "                           GSM6914418                          GSM6914419  \\\n",
      "0  labeling kit: GeneChip WT Pico kit  labeling kit: GeneChip WT Pico kit   \n",
      "1                  labeling batch: 26                  labeling batch: 27   \n",
      "2      clinical tnm staging: cT3bN0M0      clinical tnm staging: pT3bN1M0   \n",
      "3      chemotherapy type: neoadjuvant         chemotherapy type: adjuvant   \n",
      "4           lundtax rna-subtype: UroB             lundtax rna-subtype: GU   \n",
      "\n",
      "                           GSM6914420                          GSM6914421  \\\n",
      "0  labeling kit: GeneChip WT Pico kit  labeling kit: GeneChip WT Pico kit   \n",
      "1                  labeling batch: 27                  labeling batch: 27   \n",
      "2       clinical tnm staging: cTxN0M1       clinical tnm staging: cTxN3M1   \n",
      "3       chemotherapy type: palliative       chemotherapy type: palliative   \n",
      "4           lundtax rna-subtype: BASQ           lundtax rna-subtype: UroB   \n",
      "\n",
      "                           GSM6914422                          GSM6914423  \n",
      "0  labeling kit: GeneChip WT Pico kit  labeling kit: GeneChip WT Pico kit  \n",
      "1                  labeling batch: 27                  labeling batch: 27  \n",
      "2      clinical tnm staging: pT2aN1M0       clinical tnm staging: cT3N1M1  \n",
      "3         chemotherapy type: adjuvant       chemotherapy type: palliative  \n",
      "4           lundtax rna-subtype: UroC           lundtax rna-subtype: BASQ  \n",
      "\n",
      "[5 rows x 147 columns]\n",
      "Clinical data shape after extraction: (1, 146)\n",
      "First few sample IDs in clinical data:\n",
      "['GSM6914278', 'GSM6914279', 'GSM6914280', 'GSM6914281', 'GSM6914282']\n",
      "First few sample IDs in gene data:\n",
      "['GSM6914278', 'GSM6914279', 'GSM6914280', 'GSM6914281', 'GSM6914282']\n",
      "Number of common samples between clinical and gene data: 146\n",
      "Clinical data saved to ../../output/preprocess/Bladder_Cancer/clinical_data/GSE222073.csv\n",
      "Linked data shape: (146, 13363)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data shape after handling missing values: (146, 13363)\n",
      "For the feature 'Bladder_Cancer', the least common label is '1.0' with 53 occurrences. This represents 36.30% of the dataset.\n",
      "The distribution of the feature 'Bladder_Cancer' in this dataset is fine.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Bladder_Cancer/GSE222073.csv\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. Load clinical data from the matrix file again to ensure we have the correct sample IDs\n",
    "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
    "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
    "_, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
    "\n",
    "print(\"Clinical data structure:\")\n",
    "print(clinical_data.shape)\n",
    "print(\"First few rows of clinical data:\")\n",
    "print(clinical_data.head())\n",
    "\n",
    "# Extract clinical features with the correct sample IDs\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",
    "print(f\"Clinical data shape after extraction: {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",
    "# Save the clinical data for inspection\n",
    "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "selected_clinical_df.to_csv(out_clinical_data_file)\n",
    "print(f\"Clinical data saved to {out_clinical_data_file}\")\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 match sample IDs between clinical and gene expression data.\"\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 bladder cancer samples with molecular subtyping information.\"\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
}