File size: 29,390 Bytes
9fe78b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "d11dcd1e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:47:10.917755Z",
     "iopub.status.busy": "2025-03-25T03:47:10.917395Z",
     "iopub.status.idle": "2025-03-25T03:47:11.084834Z",
     "shell.execute_reply": "2025-03-25T03:47:11.084431Z"
    }
   },
   "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 = \"Rectal_Cancer\"\n",
    "cohort = \"GSE150082\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Rectal_Cancer\"\n",
    "in_cohort_dir = \"../../input/GEO/Rectal_Cancer/GSE150082\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Rectal_Cancer/GSE150082.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Rectal_Cancer/gene_data/GSE150082.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Rectal_Cancer/clinical_data/GSE150082.csv\"\n",
    "json_path = \"../../output/preprocess/Rectal_Cancer/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7de2e8b1",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "b3dbf9cb",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:47:11.086337Z",
     "iopub.status.busy": "2025-03-25T03:47:11.086191Z",
     "iopub.status.idle": "2025-03-25T03:47:11.230327Z",
     "shell.execute_reply": "2025-03-25T03:47:11.229926Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Pre-existing tumoral B cell infiltration and impaired genome maintenance correlate with response to chemoradiotherapy in locally advanced rectal cancer (LARC)\"\n",
      "!Series_summary\t\"Using Human Genome 4x44 two-color Agilent microarrays, we established the expression profiling of 39 LARC pretreatment tumor samples to elucidate the molecular features associated with response to treatment after neoadjuvant chemoradiotherapy (nCRT).\"\n",
      "!Series_overall_design\t\"Two color microarrays where Cy5= tumor sample and Cy3= Stratagene Universal Human RNA Reference. This dataset comprises the transcriptomic profiling of 39 consecutive eligible LARC patients who underwent therapy at the Oncology Unit at Bonorino Udaondo Hospital (Buenos Aires, Argentina) from November 2015 to September 2018. This study was approved by the Udaondo Hospital Ethics Committee and the Instituto Leloir Institutional Review Board. All patients signed the approved Informed Consent.  All patients were assigned to standard pelvic long course radiotherapy (LCRT: 50.4 Gy in 28 fractions of three-dimensional conformal radiotherapy, 1.8 Gy per fraction, per day) with concurrent capecitabine (825 mg/m2/bid for 28 days), termed hereafter CRT. Patients with a high risk of systemic relapse (EMVI, high mesorectal node burden and LLND) underwent TNT, which comprises pre-treatment before the CRT with three cycles of CAPOX (130 mg/m² of oxaliplatin on day 1 and capecitabine 1000 mg/m²/bid, days 1-14 every 3 weeks). Two cycles of capecitabine monotherapy (850 mg/m²/bid, days 1-14 every 3 weeks) was then administered until response assessment for all patients. Together, TNT and CRT are referred to as nCRT. Response to nCRT was evaluated on the surgical specimen by the  pathological tumor regression (pTRG) score proposed by  the seventh edition manual of the American Joint Committee on Cancer (AJCC), except for cases where pTRG was unavailable due to complete clinical response or unresectability. pTRG=0-1 and complete clinical responders were considered good responders, while pTRG=2-3 and unresectable patients were considered poor responders. The most relevant clinical variables are summarized in the metadata file; in case you require further information, do not hesitate to contact the authors.\"\n",
      "!Series_overall_design\t\"contributor: GENUIT consortium\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['Sex: M', 'Sex: F'], 1: ['tissue: rectal cancer'], 2: ['age: 70', 'age: 74', 'age: 45', 'age: 54', 'age: 72', 'age: 57', 'age: 66', 'age: 71', 'age: 47', 'age: 61', 'age: 64', 'age: 59', 'age: 34', 'age: 63', 'age: 46', 'age: 55', 'age: 75', 'age: 42', 'age: 69', 'age: 49', 'age: 68', 'age: 60', 'age: 58', 'age: 30', 'age: 56'], 3: ['ptrg: Complete_clinical_response_nonOperative', 'ptrg: 1', 'ptrg: NA', 'ptrg: 0', 'ptrg: 3', 'ptrg: 2', 'ptrg: Unresectable'], 4: ['response: Good', 'response: Poor']}\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": "539c3ebe",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "edec9b7d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:47:11.231573Z",
     "iopub.status.busy": "2025-03-25T03:47:11.231464Z",
     "iopub.status.idle": "2025-03-25T03:47:11.241808Z",
     "shell.execute_reply": "2025-03-25T03:47:11.241415Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of selected clinical features:\n",
      "{'GSM4523129': [1.0, 70.0, 1.0], 'GSM4523130': [1.0, 74.0, 1.0], 'GSM4523131': [1.0, 45.0, 0.0], 'GSM4523132': [1.0, 45.0, 0.0], 'GSM4523133': [1.0, 54.0, 1.0], 'GSM4523134': [1.0, 72.0, 1.0], 'GSM4523135': [1.0, 57.0, 1.0], 'GSM4523136': [1.0, 66.0, 1.0], 'GSM4523137': [1.0, 71.0, 0.0], 'GSM4523138': [1.0, 47.0, 1.0], 'GSM4523139': [1.0, 66.0, 1.0], 'GSM4523140': [1.0, 61.0, 1.0], 'GSM4523141': [1.0, 64.0, 1.0], 'GSM4523142': [1.0, 61.0, 1.0], 'GSM4523143': [1.0, 59.0, 1.0], 'GSM4523144': [0.0, 34.0, 0.0], 'GSM4523145': [0.0, 63.0, 1.0], 'GSM4523146': [0.0, 66.0, 0.0], 'GSM4523147': [0.0, 46.0, 1.0], 'GSM4523148': [0.0, 57.0, 1.0], 'GSM4523149': [0.0, 64.0, 1.0], 'GSM4523150': [0.0, 55.0, 1.0], 'GSM4523151': [0.0, 75.0, 1.0], 'GSM4523152': [0.0, 61.0, 1.0], 'GSM4523153': [0.0, 42.0, 0.0], 'GSM4523154': [0.0, 63.0, 1.0], 'GSM4523155': [0.0, 42.0, 1.0], 'GSM4523156': [0.0, 69.0, 1.0], 'GSM4523157': [0.0, 49.0, 0.0], 'GSM4523158': [0.0, 68.0, 0.0], 'GSM4523159': [0.0, 60.0, 0.0], 'GSM4523160': [0.0, 69.0, 1.0], 'GSM4523161': [0.0, 58.0, 1.0], 'GSM4523162': [0.0, 30.0, 1.0], 'GSM4523163': [0.0, 49.0, 0.0], 'GSM4523164': [1.0, 74.0, 1.0], 'GSM4523165': [0.0, 56.0, 1.0], 'GSM4523166': [0.0, 64.0, 1.0], 'GSM4523167': [0.0, 66.0, 1.0]}\n",
      "Clinical data saved to ../../output/preprocess/Rectal_Cancer/clinical_data/GSE150082.csv\n"
     ]
    }
   ],
   "source": [
    "# Analyze gene expression data availability\n",
    "is_gene_available = True  # Based on Series_summary mentioning \"expression profiling\" and \"Agilent microarrays\"\n",
    "\n",
    "# Define trait row and conversion function\n",
    "trait_row = 4  # 'response' field contains binary Good/Poor response data\n",
    "age_row = 2    # Age data is available\n",
    "gender_row = 0  # Sex data is available\n",
    "\n",
    "# Define conversion functions for clinical features\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait value to binary: Good response = 1, Poor response = 0\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    value_part = value.split(': ')[-1].strip() if ': ' in value else value.strip()\n",
    "    \n",
    "    if value_part == 'Good':\n",
    "        return 1\n",
    "    elif value_part == 'Poor':\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age value to continuous numeric value\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    value_part = value.split(': ')[-1].strip() if ': ' in value else value.strip()\n",
    "    \n",
    "    try:\n",
    "        return float(value_part)\n",
    "    except ValueError:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender value to binary: Female = 0, Male = 1\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    value_part = value.split(': ')[-1].strip() if ': ' in value else value.strip()\n",
    "    \n",
    "    if value_part == 'F':\n",
    "        return 0\n",
    "    elif value_part == 'M':\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# Determine trait availability\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Save metadata for initial filtering\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",
    "# Extract clinical features if trait data is available\n",
    "if trait_row is not None:\n",
    "    # Assuming clinical_data is already in memory from previous steps\n",
    "    # Extract clinical features\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",
    "    # Preview the extracted data\n",
    "    preview_data = preview_df(selected_clinical_df)\n",
    "    print(\"Preview of selected clinical features:\")\n",
    "    print(preview_data)\n",
    "    \n",
    "    # Create directory if it doesn't exist\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    \n",
    "    # Save the extracted clinical data\n",
    "    selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7e8ef31d",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "97c9dc74",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:47:11.242904Z",
     "iopub.status.busy": "2025-03-25T03:47:11.242800Z",
     "iopub.status.idle": "2025-03-25T03:47:11.467749Z",
     "shell.execute_reply": "2025-03-25T03:47:11.467299Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['A_23_P100001', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074',\n",
      "       'A_23_P100127', 'A_23_P100141', 'A_23_P100189', 'A_23_P100196',\n",
      "       'A_23_P100203', 'A_23_P100220', 'A_23_P100240', 'A_23_P10025',\n",
      "       'A_23_P100292', 'A_23_P100315', 'A_23_P100326', 'A_23_P100344',\n",
      "       'A_23_P100355', 'A_23_P100386', 'A_23_P100392', 'A_23_P100420'],\n",
      "      dtype='object', name='ID')\n"
     ]
    }
   ],
   "source": [
    "# 1. First get the file paths\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. Use the get_genetic_data function from the library to get the gene_data\n",
    "gene_data = get_genetic_data(matrix_file)\n",
    "\n",
    "# 3. Print the first 20 row IDs (gene or probe identifiers) for future observation\n",
    "print(gene_data.index[:20])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc2c7cdd",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c7cdf591",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:47:11.469034Z",
     "iopub.status.busy": "2025-03-25T03:47:11.468916Z",
     "iopub.status.idle": "2025-03-25T03:47:11.471099Z",
     "shell.execute_reply": "2025-03-25T03:47:11.470670Z"
    }
   },
   "outputs": [],
   "source": [
    "# Reviewing the gene identifiers in the dataset\n",
    "# These identifiers (A_23_P100001, etc.) are Agilent microarray probe IDs\n",
    "# They are not human gene symbols and will need to be mapped to gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9cfcae17",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "55129674",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:47:11.472186Z",
     "iopub.status.busy": "2025-03-25T03:47:11.472080Z",
     "iopub.status.idle": "2025-03-25T03:47:14.177330Z",
     "shell.execute_reply": "2025-03-25T03:47:14.176858Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107', '(+)E1A_r60_a135'], 'SPOT_ID': ['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107', '(+)E1A_r60_a135'], 'CONTROL_TYPE': ['pos', 'pos', 'pos', 'pos', 'pos'], 'REFSEQ': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan], 'GENE': [nan, nan, nan, nan, nan], 'GENE_SYMBOL': [nan, nan, nan, nan, nan], 'GENE_NAME': [nan, nan, nan, nan, nan], 'UNIGENE_ID': [nan, nan, nan, nan, nan], 'ENSEMBL_ID': [nan, nan, nan, nan, nan], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': [nan, nan, nan, nan, nan], 'CHROMOSOMAL_LOCATION': [nan, nan, nan, nan, nan], 'CYTOBAND': [nan, nan, nan, nan, nan], 'DESCRIPTION': [nan, nan, nan, nan, nan], 'GO_ID': [nan, nan, nan, nan, nan], 'SEQUENCE': [nan, nan, nan, nan, nan]}\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": "6b20542c",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "03a16420",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:47:14.178509Z",
     "iopub.status.busy": "2025-03-25T03:47:14.178384Z",
     "iopub.status.idle": "2025-03-25T03:47:15.235127Z",
     "shell.execute_reply": "2025-03-25T03:47:15.234550Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Looking for probe IDs matching the format in gene_data:\n",
      "Found matching probe ID at row 11: A_23_P100001\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Sample rows with matching probe IDs:\n",
      "              ID GENE_SYMBOL\n",
      "11  A_23_P100001     FAM174B\n",
      "12  A_23_P100022        SV2B\n",
      "13  A_23_P100056      RBPMS2\n",
      "14  A_23_P100074        AVEN\n",
      "15  A_23_P100127       CASC5\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Preview of mapping dataframe:\n",
      "              ID     Gene\n",
      "11  A_23_P100001  FAM174B\n",
      "12  A_23_P100022     SV2B\n",
      "13  A_23_P100056   RBPMS2\n",
      "14  A_23_P100074     AVEN\n",
      "15  A_23_P100127    CASC5\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Preview of gene expression data after mapping:\n",
      "          GSM4523129  GSM4523130  GSM4523131  GSM4523132  GSM4523133  \\\n",
      "Gene                                                                   \n",
      "A1BG       -4.423492   -3.130753   -3.654191   -3.428902   -3.588846   \n",
      "A1BG-AS1   -3.023192   -1.816686   -1.816458   -2.099744   -2.114976   \n",
      "A1CF        1.322759   -1.244949    0.749600    2.108298    1.239829   \n",
      "A2M        -2.857169   -2.293804   -2.676066   -2.405703   -0.954434   \n",
      "A2ML1       0.249256   -0.328081   -0.652739   -0.052724   -0.723140   \n",
      "\n",
      "          GSM4523134  GSM4523135  GSM4523136  GSM4523137  GSM4523138  ...  \\\n",
      "Gene                                                                  ...   \n",
      "A1BG       -3.866785   -3.539964   -3.925691   -1.980177   -4.693128  ...   \n",
      "A1BG-AS1   -2.179731   -1.799732   -2.380574   -1.746726   -2.501482  ...   \n",
      "A1CF        1.464439    2.489900    1.403291   -1.993101    1.871084  ...   \n",
      "A2M        -2.226460   -2.769710   -1.788050   -1.903759   -2.913644  ...   \n",
      "A2ML1      -0.985901   -0.794128    2.343952    0.553369   -0.219188  ...   \n",
      "\n",
      "          GSM4523158  GSM4523159  GSM4523160  GSM4523161  GSM4523162  \\\n",
      "Gene                                                                   \n",
      "A1BG       -3.618253   -1.541513   -2.763218   -4.417670   -2.412677   \n",
      "A1BG-AS1   -2.682453   -0.780151   -1.392280   -2.468921   -1.123779   \n",
      "A1CF        0.487051    1.694411   -0.263418    0.849508    1.679830   \n",
      "A2M        -3.666401    0.043144   -2.926064   -4.051856   -1.817957   \n",
      "A2ML1      -0.040744    0.022845   -0.531561   -0.087179   -0.118195   \n",
      "\n",
      "          GSM4523163  GSM4523164  GSM4523165  GSM4523166  GSM4523167  \n",
      "Gene                                                                  \n",
      "A1BG       -3.035999   -4.153402   -2.865329   -4.097455   -4.675679  \n",
      "A1BG-AS1   -1.450171   -2.586337   -2.895995   -2.170560   -2.026514  \n",
      "A1CF        0.859313    1.705023   -0.792009    0.456869    1.294504  \n",
      "A2M        -1.778456   -2.321148   -3.245357   -2.060726   -1.217995  \n",
      "A2ML1       0.173105    0.351994    0.240639   -0.603942   -0.479412  \n",
      "\n",
      "[5 rows x 39 columns]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene expression data saved to ../../output/preprocess/Rectal_Cancer/gene_data/GSE150082.csv\n"
     ]
    }
   ],
   "source": [
    "# Looking at the gene identifiers in gene_data (from step 3) like 'A_23_P100001'\n",
    "# and the gene annotation preview (from step 5)\n",
    "# We need to find the appropriate columns for mapping\n",
    "\n",
    "# First examine the annotation columns that potentially map to gene identifiers in gene_data\n",
    "# Let's print more rows to find example of probe IDs that match our gene_data format\n",
    "print(\"Looking for probe IDs matching the format in gene_data:\")\n",
    "for i in range(20):\n",
    "    if i < len(gene_annotation):\n",
    "        if str(gene_annotation['ID'].iloc[i]).startswith('A_23_P'):\n",
    "            print(f\"Found matching probe ID at row {i}: {gene_annotation['ID'].iloc[i]}\")\n",
    "            break\n",
    "\n",
    "# Get a sample to see what column contains the gene symbols\n",
    "sample_rows = gene_annotation[gene_annotation['ID'].str.startswith('A_23_P', na=False)].head(5)\n",
    "print(\"\\nSample rows with matching probe IDs:\")\n",
    "print(sample_rows[['ID', 'GENE_SYMBOL']])\n",
    "\n",
    "# Now create the mapping dataframe using the identified columns\n",
    "# The 'ID' column in gene_annotation corresponds to probe IDs in gene_data\n",
    "# The 'GENE_SYMBOL' column contains the gene symbols\n",
    "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')\n",
    "print(\"\\nPreview of mapping dataframe:\")\n",
    "print(mapping_df.head())\n",
    "\n",
    "# Apply the gene mapping to convert probe-level measurements to gene expression\n",
    "gene_expression_data = apply_gene_mapping(gene_data, mapping_df)\n",
    "\n",
    "# Normalize gene symbols to ensure consistency\n",
    "gene_data = normalize_gene_symbols_in_index(gene_expression_data)\n",
    "\n",
    "# Preview the gene expression data\n",
    "print(\"\\nPreview of gene expression data after mapping:\")\n",
    "print(gene_data.head())\n",
    "\n",
    "# Save the processed gene data to the output file\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"\\nGene expression data saved to {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "70f167bf",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "002cc2c7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:47:15.236753Z",
     "iopub.status.busy": "2025-03-25T03:47:15.236506Z",
     "iopub.status.idle": "2025-03-25T03:47:24.435564Z",
     "shell.execute_reply": "2025-03-25T03:47:24.435141Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical data saved to ../../output/preprocess/Rectal_Cancer/clinical_data/GSE150082.csv\n",
      "Normalized gene data shape: (19447, 39)\n",
      "First few normalized gene symbols: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS', 'AACS']\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Rectal_Cancer/gene_data/GSE150082.csv\n",
      "Linked data shape: (39, 19450)\n",
      "            Rectal_Cancer   Age  Gender      A1BG  A1BG-AS1      A1CF  \\\n",
      "GSM4523129            1.0  70.0     1.0 -4.423492 -3.023192  1.322759   \n",
      "GSM4523130            1.0  74.0     1.0 -3.130753 -1.816686 -1.244949   \n",
      "GSM4523131            1.0  45.0     0.0 -3.654191 -1.816458  0.749600   \n",
      "GSM4523132            1.0  45.0     0.0 -3.428902 -2.099744  2.108298   \n",
      "GSM4523133            1.0  54.0     1.0 -3.588846 -2.114976  1.239829   \n",
      "\n",
      "                 A2M     A2ML1    A4GALT     A4GNT  ...    ZWILCH     ZWINT  \\\n",
      "GSM4523129 -2.857169  0.249256 -0.808312  0.532630  ... -2.439972 -1.899276   \n",
      "GSM4523130 -2.293804 -0.328081 -1.429592  0.752957  ... -2.274822 -3.385446   \n",
      "GSM4523131 -2.676066 -0.652739 -1.259287  0.354724  ... -2.184009 -1.220591   \n",
      "GSM4523132 -2.405703 -0.052724 -0.942970  0.561949  ... -2.805278 -3.204676   \n",
      "GSM4523133 -0.954434 -0.723140 -0.490592  0.599406  ... -2.485352 -0.854767   \n",
      "\n",
      "                ZXDA      ZXDB      ZXDC    ZYG11A    ZYG11B       ZYX  \\\n",
      "GSM4523129  0.290684  0.651939 -1.696185 -8.779519 -0.494155  0.022449   \n",
      "GSM4523130  0.262735  0.856420  1.272290 -6.057712 -3.247352  0.097168   \n",
      "GSM4523131 -1.548108 -0.487278 -1.999048 -8.204449 -1.192964 -0.186130   \n",
      "GSM4523132 -1.903522  0.318907 -0.729945 -4.747856 -1.067676  0.008756   \n",
      "GSM4523133 -0.280135  0.925577 -1.668339 -7.598349 -2.057593 -0.379474   \n",
      "\n",
      "               ZZEF1      ZZZ3  \n",
      "GSM4523129  0.371166 -2.276865  \n",
      "GSM4523130 -0.253226 -0.469240  \n",
      "GSM4523131  0.384354 -0.018876  \n",
      "GSM4523132  2.153644 -2.316143  \n",
      "GSM4523133  0.628681 -1.538092  \n",
      "\n",
      "[5 rows x 19450 columns]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Shape after handling missing values: (39, 19450)\n",
      "For the feature 'Rectal_Cancer', the least common label is '1.0' with 16 occurrences. This represents 41.03% of the dataset.\n",
      "The distribution of the feature 'Rectal_Cancer' in this dataset is fine.\n",
      "\n",
      "Quartiles for 'Age':\n",
      "  25%: 51.5\n",
      "  50% (Median): 61.0\n",
      "  75%: 66.0\n",
      "Min: 30.0\n",
      "Max: 75.0\n",
      "The distribution of the feature 'Age' in this dataset is fine.\n",
      "\n",
      "For the feature 'Gender', the least common label is '0.0' with 10 occurrences. This represents 25.64% of the dataset.\n",
      "The distribution of the feature 'Gender' in this dataset is fine.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Rectal_Cancer/GSE150082.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Extract clinical features\n",
    "clinical_features = geo_select_clinical_features(\n",
    "    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",
    "# Save the clinical features 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",
    "# 1. Normalize gene symbols in the gene expression data\n",
    "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n",
    "print(f\"First few normalized gene symbols: {list(normalized_gene_data.index[:10])}\")\n",
    "\n",
    "# Save the normalized gene data\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "normalized_gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
    "\n",
    "# 2. Link the clinical and genetic data\n",
    "linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "print(linked_data.head())\n",
    "\n",
    "# 3. Handle missing values in the linked data\n",
    "linked_data = handle_missing_values(linked_data, trait)\n",
    "print(f\"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, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "\n",
    "# 5. Conduct quality check and save the cohort 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=unbiased_linked_data,\n",
    "    note=f\"Dataset contains gene expression data from CD4 T-cells of pSS patients and healthy controls.\"\n",
    ")\n",
    "\n",
    "# 6. Save the data if it's usable\n",
    "if is_usable:\n",
    "    # Create directory if it doesn't exist\n",
    "    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "    # Save the data\n",
    "    unbiased_linked_data.to_csv(out_data_file)\n",
    "    print(f\"Linked data saved to {out_data_file}\")\n",
    "else:\n",
    "    print(f\"Data quality check failed. The dataset is not suitable for association studies.\")"
   ]
  }
 ],
 "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
}