File size: 40,811 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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "686d0db4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:46:12.445430Z",
     "iopub.status.busy": "2025-03-25T03:46:12.445325Z",
     "iopub.status.idle": "2025-03-25T03:46:12.611754Z",
     "shell.execute_reply": "2025-03-25T03:46:12.611413Z"
    }
   },
   "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 = \"GSE109057\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Rectal_Cancer\"\n",
    "in_cohort_dir = \"../../input/GEO/Rectal_Cancer/GSE109057\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Rectal_Cancer/GSE109057.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Rectal_Cancer/gene_data/GSE109057.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Rectal_Cancer/clinical_data/GSE109057.csv\"\n",
    "json_path = \"../../output/preprocess/Rectal_Cancer/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "13d79464",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "2f74101c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:46:12.613170Z",
     "iopub.status.busy": "2025-03-25T03:46:12.613028Z",
     "iopub.status.idle": "2025-03-25T03:46:12.829610Z",
     "shell.execute_reply": "2025-03-25T03:46:12.829270Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Transcriptome analysis by expression microarrays of rectal cancer derived from the Cancer Institute Hospital of Japanese Foundation for Cancer Research\"\n",
      "!Series_summary\t\"We performed the expression microrarray experiments for mRNA of rectal cancer tissue.\"\n",
      "!Series_overall_design\t\"Messenger RNA were extracted from primary tumor of 90 rectal cancer patients, hybridized and scanned with Affymetrix PrimeView Human Gene Expression Array. There are 91 samples because one sample was hybridized twice, once in each batch, and is represented by GSM2928780 and GSM2928794.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['tissue: rectal cancer'], 1: ['Sex: M', 'Sex: F'], 2: ['age: 35 <= age < 40', 'age: 30 <= age < 35', 'age: 55 <= age < 60', 'age: 45 <= age < 50', 'age: 65 <= age < 70', 'age: 75 <= age < 80', 'age: 70 <= age < 75', 'age: 60 <= age < 65', 'age: 50 <= age < 55', 'age: 80 <= age < 85', 'age: 40 <= age < 45'], 3: ['batch: Batch 1', 'batch: Batch 2']}\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": "cd2dfc76",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "1780f85d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:46:12.830740Z",
     "iopub.status.busy": "2025-03-25T03:46:12.830634Z",
     "iopub.status.idle": "2025-03-25T03:46:12.844674Z",
     "shell.execute_reply": "2025-03-25T03:46:12.844399Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical Data Preview:\n",
      "{'GSM2928730': [1.0, 37.5, 1.0], 'GSM2928731': [1.0, 32.5, 1.0], 'GSM2928732': [1.0, 57.5, 1.0], 'GSM2928733': [1.0, 47.5, 1.0], 'GSM2928734': [1.0, 67.5, 0.0], 'GSM2928735': [1.0, 77.5, 1.0], 'GSM2928736': [1.0, 57.5, 1.0], 'GSM2928737': [1.0, 47.5, 1.0], 'GSM2928738': [1.0, 72.5, 1.0], 'GSM2928739': [1.0, 62.5, 1.0], 'GSM2928740': [1.0, 52.5, 1.0], 'GSM2928741': [1.0, 32.5, 1.0], 'GSM2928742': [1.0, 67.5, 1.0], 'GSM2928743': [1.0, 47.5, 1.0], 'GSM2928744': [1.0, 67.5, 1.0], 'GSM2928745': [1.0, 57.5, 1.0], 'GSM2928746': [1.0, 47.5, 1.0], 'GSM2928747': [1.0, 47.5, 1.0], 'GSM2928748': [1.0, 72.5, 1.0], 'GSM2928749': [1.0, 67.5, 1.0], 'GSM2928750': [1.0, 47.5, 1.0], 'GSM2928751': [1.0, 67.5, 1.0], 'GSM2928752': [1.0, 67.5, 0.0], 'GSM2928753': [1.0, 57.5, 1.0], 'GSM2928754': [1.0, 52.5, 1.0], 'GSM2928755': [1.0, 67.5, 1.0], 'GSM2928756': [1.0, 47.5, 1.0], 'GSM2928757': [1.0, 62.5, 1.0], 'GSM2928758': [1.0, 62.5, 1.0], 'GSM2928759': [1.0, 67.5, 0.0], 'GSM2928760': [1.0, 62.5, 1.0], 'GSM2928761': [1.0, 67.5, 0.0], 'GSM2928762': [1.0, 57.5, 1.0], 'GSM2928763': [1.0, 57.5, 1.0], 'GSM2928764': [1.0, 62.5, 1.0], 'GSM2928765': [1.0, 52.5, 1.0], 'GSM2928766': [1.0, 82.5, 0.0], 'GSM2928767': [1.0, 57.5, 0.0], 'GSM2928768': [1.0, 47.5, 0.0], 'GSM2928769': [1.0, 72.5, 1.0], 'GSM2928770': [1.0, 42.5, 1.0], 'GSM2928771': [1.0, 67.5, 0.0], 'GSM2928772': [1.0, 62.5, 1.0], 'GSM2928773': [1.0, 57.5, 1.0], 'GSM2928774': [1.0, 62.5, 1.0], 'GSM2928775': [1.0, 52.5, 1.0], 'GSM2928776': [1.0, 52.5, 1.0], 'GSM2928777': [1.0, 62.5, 0.0], 'GSM2928778': [1.0, 47.5, 1.0], 'GSM2928779': [1.0, 62.5, 1.0], 'GSM2928780': [1.0, 67.5, 1.0], 'GSM2928781': [1.0, 67.5, 1.0], 'GSM2928782': [1.0, 67.5, 1.0], 'GSM2928783': [1.0, 62.5, 1.0], 'GSM2928784': [1.0, 77.5, 0.0], 'GSM2928785': [1.0, 62.5, 0.0], 'GSM2928786': [1.0, 57.5, 1.0], 'GSM2928787': [1.0, 62.5, 0.0], 'GSM2928788': [1.0, 57.5, 0.0], 'GSM2928789': [1.0, 77.5, 0.0], 'GSM2928790': [1.0, 62.5, 0.0], 'GSM2928791': [1.0, 47.5, 1.0], 'GSM2928792': [1.0, 62.5, 1.0], 'GSM2928793': [1.0, 62.5, 1.0], 'GSM2928794': [1.0, 67.5, 1.0], 'GSM2928795': [1.0, 47.5, 0.0], 'GSM2928796': [1.0, 32.5, 1.0], 'GSM2928797': [1.0, 47.5, 1.0], 'GSM2928798': [1.0, 52.5, 0.0], 'GSM2928799': [1.0, 57.5, 1.0], 'GSM2928800': [1.0, 67.5, 1.0], 'GSM2928801': [1.0, 47.5, 1.0], 'GSM2928802': [1.0, 62.5, 0.0], 'GSM2928803': [1.0, 52.5, 0.0], 'GSM2928804': [1.0, 72.5, 0.0], 'GSM2928805': [1.0, 67.5, 1.0], 'GSM2928806': [1.0, 57.5, 0.0], 'GSM2928807': [1.0, 62.5, 0.0], 'GSM2928808': [1.0, 47.5, 0.0], 'GSM2928809': [1.0, 42.5, 1.0], 'GSM2928810': [1.0, 37.5, 0.0], 'GSM2928811': [1.0, 72.5, 0.0], 'GSM2928812': [1.0, 72.5, 1.0], 'GSM2928813': [1.0, 72.5, 1.0], 'GSM2928814': [1.0, 77.5, 0.0], 'GSM2928815': [1.0, 77.5, 0.0], 'GSM2928816': [1.0, 72.5, 1.0], 'GSM2928817': [1.0, 62.5, 1.0], 'GSM2928818': [1.0, 37.5, 1.0], 'GSM2928819': [1.0, 52.5, 1.0], 'GSM2928820': [1.0, 72.5, 1.0]}\n",
      "Clinical data saved to ../../output/preprocess/Rectal_Cancer/clinical_data/GSE109057.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Based on background information, this dataset contains gene expression data from Affymetrix arrays\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# Rectal Cancer is the trait we're studying, and it's available in row 0\n",
    "trait_row = 0\n",
    "\n",
    "# Gender data is available in row 1\n",
    "gender_row = 1\n",
    "\n",
    "# Age data is available in row 2\n",
    "age_row = 2\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "def convert_trait(value):\n",
    "    # All samples are rectal cancer \"tissue: rectal cancer\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after colon\n",
    "    parts = value.split(\": \")\n",
    "    if len(parts) < 2:\n",
    "        return None\n",
    "    \n",
    "    tissue = parts[1].strip()\n",
    "    if \"rectal cancer\" in tissue.lower():\n",
    "        return 1\n",
    "    else:\n",
    "        return 0\n",
    "\n",
    "def convert_gender(value):\n",
    "    # Gender data in format \"Sex: M\" or \"Sex: F\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after colon\n",
    "    parts = value.split(\": \")\n",
    "    if len(parts) < 2:\n",
    "        return None\n",
    "    \n",
    "    gender = parts[1].strip()\n",
    "    if gender == 'M':\n",
    "        return 1\n",
    "    elif gender == 'F':\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    # Age data in format \"age: X <= age < Y\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after colon\n",
    "    parts = value.split(\": \")\n",
    "    if len(parts) < 2:\n",
    "        return None\n",
    "    \n",
    "    age_range = parts[1].strip()\n",
    "    # Extract the lower and upper bounds of the age range\n",
    "    try:\n",
    "        age_parts = age_range.split(\" \")\n",
    "        lower_bound = int(age_parts[0])\n",
    "        upper_bound = int(age_parts[-1])\n",
    "        # Return the midpoint of the age range\n",
    "        return (lower_bound + upper_bound) / 2\n",
    "    except:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# trait_row is not None, so is_trait_available should be True\n",
    "is_trait_available = trait_row is not None\n",
    "\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",
    "# Since trait_row is not None, we proceed with clinical feature extraction\n",
    "if trait_row is not None:\n",
    "    # Extract clinical features\n",
    "    clinical_df = 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",
    "    # Preview and save clinical data\n",
    "    print(\"Clinical Data Preview:\")\n",
    "    print(preview_df(clinical_df))\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 clinical data to CSV\n",
    "    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": "259cabe1",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "2606920f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:46:12.845694Z",
     "iopub.status.busy": "2025-03-25T03:46:12.845593Z",
     "iopub.status.idle": "2025-03-25T03:46:13.215570Z",
     "shell.execute_reply": "2025-03-25T03:46:13.215202Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['11715100_at', '11715101_s_at', '11715102_x_at', '11715103_x_at',\n",
      "       '11715104_s_at', '11715105_at', '11715106_x_at', '11715107_s_at',\n",
      "       '11715108_x_at', '11715109_at', '11715110_at', '11715111_s_at',\n",
      "       '11715112_at', '11715113_x_at', '11715114_x_at', '11715115_s_at',\n",
      "       '11715116_s_at', '11715117_x_at', '11715118_s_at', '11715119_s_at'],\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": "9e0f8f4c",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "94682d46",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:46:13.216852Z",
     "iopub.status.busy": "2025-03-25T03:46:13.216733Z",
     "iopub.status.idle": "2025-03-25T03:46:13.218560Z",
     "shell.execute_reply": "2025-03-25T03:46:13.218284Z"
    }
   },
   "outputs": [],
   "source": [
    "# These appear to be probe set IDs from an Affymetrix microarray platform, not human gene symbols.\n",
    "# The format \"11715100_at\" is typical of Affymetrix probe identifiers.\n",
    "# These will need to be mapped to standard human gene symbols for analysis.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "49f7a5e2",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "b55cc2b8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:46:13.219537Z",
     "iopub.status.busy": "2025-03-25T03:46:13.219437Z",
     "iopub.status.idle": "2025-03-25T03:46:25.748864Z",
     "shell.execute_reply": "2025-03-25T03:46:25.748471Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['11715100_at', '11715101_s_at', '11715102_x_at', '11715103_x_at', '11715104_s_at'], 'GeneChip Array': ['Human Genome PrimeView Array', 'Human Genome PrimeView Array', 'Human Genome PrimeView Array', 'Human Genome PrimeView Array', 'Human Genome PrimeView Array'], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['30-Mar-16', '30-Mar-16', '30-Mar-16', '30-Mar-16', '30-Mar-16'], 'Sequence Type': ['Consensus sequence', 'Consensus sequence', 'Consensus sequence', 'Consensus sequence', 'Consensus sequence'], 'Sequence Source': ['Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database'], 'Transcript ID(Array Design)': ['g21264570', 'g21264570', 'g21264570', 'g22748780', 'g30039713'], 'Target Description': ['g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g22748780 /TID=g22748780 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g22748780 /REP_ORG=Homo sapiens', 'g30039713 /TID=g30039713 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g30039713 /REP_ORG=Homo sapiens'], 'GB_ACC': [nan, nan, nan, nan, nan], 'GI': [21264570.0, 21264570.0, 21264570.0, 22748780.0, 30039713.0], 'Representative Public ID': ['g21264570', 'g21264570', 'g21264570', 'g22748780', 'g30039713'], 'Archival UniGene Cluster': ['---', '---', '---', '---', '---'], 'UniGene ID': ['Hs.247813', 'Hs.247813', 'Hs.247813', 'Hs.465643', 'Hs.352515'], 'Genome Version': ['February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)'], 'Alignments': ['chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr19:4639529-5145579 (+) // 48.53 // p13.3', 'chr17:72920369-72929640 (+) // 100.0 // q25.1'], 'Gene Title': ['histone cluster 1, H3g', 'histone cluster 1, H3g', 'histone cluster 1, H3g', 'tumor necrosis factor, alpha-induced protein 8-like 1', 'otopetrin 2'], 'Gene Symbol': ['HIST1H3G', 'HIST1H3G', 'HIST1H3G', 'TNFAIP8L1', 'OTOP2'], 'Chromosomal Location': ['chr6p22.2', 'chr6p22.2', 'chr6p22.2', 'chr19p13.3', 'chr17q25.1'], 'Unigene Cluster Type': ['full length', 'full length', 'full length', 'full length', 'full length'], 'Ensembl': ['ENSG00000273983 /// OTTHUMG00000014436', 'ENSG00000273983 /// OTTHUMG00000014436', 'ENSG00000273983 /// OTTHUMG00000014436', 'ENSG00000185361 /// OTTHUMG00000182013', 'ENSG00000183034 /// OTTHUMG00000179215'], 'Entrez Gene': ['8355', '8355', '8355', '126282', '92736'], 'SwissProt': ['P68431', 'P68431', 'P68431', 'Q8WVP5', 'Q7RTS6'], 'EC': ['---', '---', '---', '---', '---'], 'OMIM': ['602815', '602815', '602815', '615869', '607827'], 'RefSeq Protein ID': ['NP_003525', 'NP_003525', 'NP_003525', 'NP_001161414 /// NP_689575 /// XP_005259544 /// XP_011525982', 'NP_835454 /// XP_011523781'], 'RefSeq Transcript ID': ['NM_003534', 'NM_003534', 'NM_003534', 'NM_001167942 /// NM_152362 /// XM_005259487 /// XM_011527680', 'NM_178160 /// XM_011525479'], 'Gene Ontology Biological Process': ['0000183 // chromatin silencing at rDNA // traceable author statement /// 0002230 // positive regulation of defense response to virus by host // inferred from mutant phenotype /// 0006325 // chromatin organization // traceable author statement /// 0006334 // nucleosome assembly // inferred from direct assay /// 0006334 // nucleosome assembly // inferred from mutant phenotype /// 0006335 // DNA replication-dependent nucleosome assembly // inferred from direct assay /// 0007264 // small GTPase mediated signal transduction // traceable author statement /// 0007596 // blood coagulation // traceable author statement /// 0010467 // gene expression // traceable author statement /// 0031047 // gene silencing by RNA // traceable author statement /// 0032776 // DNA methylation on cytosine // traceable author statement /// 0040029 // regulation of gene expression, epigenetic // traceable author statement /// 0044267 // cellular protein metabolic process // traceable author statement /// 0045814 // negative regulation of gene expression, epigenetic // traceable author statement /// 0051290 // protein heterotetramerization // inferred from direct assay /// 0060968 // regulation of gene silencing // inferred from direct assay /// 0098792 // xenophagy // inferred from mutant phenotype', '0000183 // chromatin silencing at rDNA // traceable author statement /// 0002230 // positive regulation of defense response to virus by host // inferred from mutant phenotype /// 0006325 // chromatin organization // traceable author statement /// 0006334 // nucleosome assembly // inferred from direct assay /// 0006334 // nucleosome assembly // inferred from mutant phenotype /// 0006335 // DNA replication-dependent nucleosome assembly // inferred from direct assay /// 0007264 // small GTPase mediated signal transduction // traceable author statement /// 0007596 // blood coagulation // traceable author statement /// 0010467 // gene expression // traceable author statement /// 0031047 // gene silencing by RNA // traceable author statement /// 0032776 // DNA methylation on cytosine // traceable author statement /// 0040029 // regulation of gene expression, epigenetic // traceable author statement /// 0044267 // cellular protein metabolic process // traceable author statement /// 0045814 // negative regulation of gene expression, epigenetic // traceable author statement /// 0051290 // protein heterotetramerization // inferred from direct assay /// 0060968 // regulation of gene silencing // inferred from direct assay /// 0098792 // xenophagy // inferred from mutant phenotype', '0000183 // chromatin silencing at rDNA // traceable author statement /// 0002230 // positive regulation of defense response to virus by host // inferred from mutant phenotype /// 0006325 // chromatin organization // traceable author statement /// 0006334 // nucleosome assembly // inferred from direct assay /// 0006334 // nucleosome assembly // inferred from mutant phenotype /// 0006335 // DNA replication-dependent nucleosome assembly // inferred from direct assay /// 0007264 // small GTPase mediated signal transduction // traceable author statement /// 0007596 // blood coagulation // traceable author statement /// 0010467 // gene expression // traceable author statement /// 0031047 // gene silencing by RNA // traceable author statement /// 0032776 // DNA methylation on cytosine // traceable author statement /// 0040029 // regulation of gene expression, epigenetic // traceable author statement /// 0044267 // cellular protein metabolic process // traceable author statement /// 0045814 // negative regulation of gene expression, epigenetic // traceable author statement /// 0051290 // protein heterotetramerization // inferred from direct assay /// 0060968 // regulation of gene silencing // inferred from direct assay /// 0098792 // xenophagy // inferred from mutant phenotype', '0032007 // negative regulation of TOR signaling // not recorded /// 0032007 // negative regulation of TOR signaling // inferred from sequence or structural similarity', '---'], 'Gene Ontology Cellular Component': ['0000228 // nuclear chromosome // inferred from direct assay /// 0000786 // nucleosome // inferred from direct assay /// 0000788 // nuclear nucleosome // inferred from direct assay /// 0005576 // extracellular region // traceable author statement /// 0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // traceable author statement /// 0005694 // chromosome // inferred from electronic annotation /// 0016020 // membrane // inferred from direct assay /// 0043234 // protein complex // inferred from direct assay /// 0070062 // extracellular exosome // inferred from direct assay', '0000228 // nuclear chromosome // inferred from direct assay /// 0000786 // nucleosome // inferred from direct assay /// 0000788 // nuclear nucleosome // inferred from direct assay /// 0005576 // extracellular region // traceable author statement /// 0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // traceable author statement /// 0005694 // chromosome // inferred from electronic annotation /// 0016020 // membrane // inferred from direct assay /// 0043234 // protein complex // inferred from direct assay /// 0070062 // extracellular exosome // inferred from direct assay', '0000228 // nuclear chromosome // inferred from direct assay /// 0000786 // nucleosome // inferred from direct assay /// 0000788 // nuclear nucleosome // inferred from direct assay /// 0005576 // extracellular region // traceable author statement /// 0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // traceable author statement /// 0005694 // chromosome // inferred from electronic annotation /// 0016020 // membrane // inferred from direct assay /// 0043234 // protein complex // inferred from direct assay /// 0070062 // extracellular exosome // inferred from direct assay', '0005737 // cytoplasm // not recorded /// 0005737 // cytoplasm // inferred from sequence or structural similarity', '0016020 // membrane // inferred from electronic annotation /// 0016021 // integral component of membrane // inferred from electronic annotation'], 'Gene Ontology Molecular Function': ['0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0042393 // histone binding // inferred from physical interaction /// 0046982 // protein heterodimerization activity // inferred from electronic annotation', '0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0042393 // histone binding // inferred from physical interaction /// 0046982 // protein heterodimerization activity // inferred from electronic annotation', '0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0042393 // histone binding // inferred from physical interaction /// 0046982 // protein heterodimerization activity // inferred from electronic annotation', '0005515 // protein binding // inferred from physical interaction', '---'], 'Pathway': ['---', '---', '---', '---', '---'], 'InterPro': ['IPR007125 // Histone H2A/H2B/H3 // 9.3E-34 /// IPR007125 // Histone H2A/H2B/H3 // 1.7E-37', 'IPR007125 // Histone H2A/H2B/H3 // 9.3E-34 /// IPR007125 // Histone H2A/H2B/H3 // 1.7E-37', 'IPR007125 // Histone H2A/H2B/H3 // 9.3E-34 /// IPR007125 // Histone H2A/H2B/H3 // 1.7E-37', 'IPR008477 // Protein of unknown function DUF758 // 8.4E-86 /// IPR008477 // Protein of unknown function DUF758 // 6.8E-90', 'IPR004878 // Otopetrin // 9.4E-43 /// IPR004878 // Otopetrin // 9.4E-43 /// IPR004878 // Otopetrin // 9.4E-43 /// IPR004878 // Otopetrin // 3.9E-18 /// IPR004878 // Otopetrin // 3.8E-20 /// IPR004878 // Otopetrin // 5.2E-16'], 'Annotation Description': ['This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 4 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 4 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 4 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 9 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 6 transcripts. // false // Matching Probes // A'], 'Annotation Transcript Cluster': ['ENST00000614378(11),NM_003534(11),OTTHUMT00000040099(11),uc003nhi.3', 'ENST00000614378(11),NM_003534(11),OTTHUMT00000040099(11),uc003nhi.3', 'ENST00000614378(11),NM_003534(11),OTTHUMT00000040099(11),uc003nhi.3', 'BC017672(11),BC044250(9),ENST00000327473(11),ENST00000536716(11),NM_001167942(11),NM_152362(11),OTTHUMT00000458662(11),uc002max.3,uc021une.1', 'ENST00000331427(11),ENST00000580223(11),NM_178160(11),OTTHUMT00000445306(11),uc010wrp.2,XM_011525479(11)'], 'Transcript Assignments': ['ENST00000614378 // ensembl_havana_transcript:known chromosome:GRCh38:6:26269405:26271815:-1 gene:ENSG00000273983 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // --- /// OTTHUMT00000040099 // otter:known chromosome:VEGA61:6:26269405:26271815:-1 gene:OTTHUMG00000014436 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc003nhi.3 // --- // ucsc_genes // 11 // ---', 'ENST00000614378 // ensembl_havana_transcript:known chromosome:GRCh38:6:26269405:26271815:-1 gene:ENSG00000273983 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// GENSCAN00000029819 // cdna:genscan chromosome:GRCh38:6:26270974:26271384:-1 transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // --- /// OTTHUMT00000040099 // otter:known chromosome:VEGA61:6:26269405:26271815:-1 gene:OTTHUMG00000014436 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc003nhi.3 // --- // ucsc_genes // 11 // ---', 'ENST00000614378 // ensembl_havana_transcript:known chromosome:GRCh38:6:26269405:26271815:-1 gene:ENSG00000273983 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // --- /// OTTHUMT00000040099 // otter:known chromosome:VEGA61:6:26269405:26271815:-1 gene:OTTHUMG00000014436 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc003nhi.3 // --- // ucsc_genes // 11 // ---', 'BC017672 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1, mRNA (cDNA clone MGC:17791 IMAGE:3885999), complete cds. // gb // 11 // --- /// BC044250 // accn=BC044250 class=mRNAlike lncRNA name=Human lncRNA ref=JounralRNA transcriptId=673 cpcScore=-0.1526100 cnci=-0.1238602 // noncode // 9 // --- /// BC044250 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1, mRNA (cDNA clone IMAGE:5784807). // gb // 9 // --- /// ENST00000327473 // ensembl_havana_transcript:known chromosome:GRCh38:19:4639518:4655568:1 gene:ENSG00000185361 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// ENST00000536716 // ensembl:known chromosome:GRCh38:19:4640017:4655568:1 gene:ENSG00000185361 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_001167942 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1 (TNFAIP8L1), transcript variant 1, mRNA. // refseq // 11 // --- /// NM_152362 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1 (TNFAIP8L1), transcript variant 2, mRNA. // refseq // 11 // --- /// NONHSAT060631 // Non-coding transcript identified by NONCODE: Exonic // noncode // 9 // --- /// OTTHUMT00000458662 // otter:known chromosome:VEGA61:19:4639518:4655568:1 gene:OTTHUMG00000182013 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc002max.3 // --- // ucsc_genes // 11 // --- /// uc021une.1 // --- // ucsc_genes // 11 // ---', 'ENST00000331427 // ensembl:known chromosome:GRCh38:17:74924275:74933911:1 gene:ENSG00000183034 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// ENST00000580223 // havana:known chromosome:GRCh38:17:74924603:74933912:1 gene:ENSG00000183034 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// GENSCAN00000013715 // cdna:genscan chromosome:GRCh38:17:74924633:74933545:1 transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_178160 // Homo sapiens otopetrin 2 (OTOP2), mRNA. // refseq // 11 // --- /// OTTHUMT00000445306 // otter:known chromosome:VEGA61:17:74924603:74933912:1 gene:OTTHUMG00000179215 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc010wrp.2 // --- // ucsc_genes // 11 // --- /// XM_011525479 // PREDICTED: Homo sapiens otopetrin 2 (OTOP2), transcript variant X1, mRNA. // refseq // 11 // ---'], 'Annotation Notes': ['---', '---', 'GENSCAN00000029819 // ensembl // 4 // Cross Hyb Matching Probes', '---', '---'], 'SPOT_ID': [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": "baddc99a",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "0370eecd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:46:25.750123Z",
     "iopub.status.busy": "2025-03-25T03:46:25.749994Z",
     "iopub.status.idle": "2025-03-25T03:46:26.181913Z",
     "shell.execute_reply": "2025-03-25T03:46:26.181583Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping preview (first 5 rows):\n",
      "              ID       Gene\n",
      "0    11715100_at   HIST1H3G\n",
      "1  11715101_s_at   HIST1H3G\n",
      "2  11715102_x_at   HIST1H3G\n",
      "3  11715103_x_at  TNFAIP8L1\n",
      "4  11715104_s_at      OTOP2\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene data preview (first 10 genes):\n",
      "Index(['A1BG', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAAS',\n",
      "       'AACS', 'AACSP1'],\n",
      "      dtype='object', name='Gene')\n",
      "\n",
      "Gene data shape: (19963, 91)\n"
     ]
    }
   ],
   "source": [
    "# 1. Based on the preview, it looks like:\n",
    "# - 'ID' column in gene_annotation contains the same probe IDs as seen in the gene expression data\n",
    "# - 'Gene Symbol' column contains the gene symbols we want to map to\n",
    "\n",
    "# 2. Get a gene mapping dataframe by extracting these two columns\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')\n",
    "\n",
    "# Print a preview of the mapping data for verification\n",
    "print(\"Gene mapping preview (first 5 rows):\")\n",
    "print(gene_mapping.head())\n",
    "\n",
    "# 3. Convert probe-level measurements to gene expression data by applying the gene mapping\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "\n",
    "# Print the first 10 gene symbols to verify the conversion\n",
    "print(\"\\nGene data preview (first 10 genes):\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# Print the shape of the converted dataset\n",
    "print(f\"\\nGene data shape: {gene_data.shape}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7d8dbdac",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "f906846f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:46:26.183217Z",
     "iopub.status.busy": "2025-03-25T03:46:26.183103Z",
     "iopub.status.idle": "2025-03-25T03:46:27.391910Z",
     "shell.execute_reply": "2025-03-25T03:46:27.391559Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data shape: (19758, 91)\n",
      "First few normalized gene symbols: ['A1BG', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAAS', 'AACS', 'AACSP1']\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Rectal_Cancer/gene_data/GSE109057.csv\n",
      "Clinical features loaded from ../../output/preprocess/Rectal_Cancer/clinical_data/GSE109057.csv\n",
      "Clinical features shape: (3, 91)\n",
      "Linked data shape: (94, 19849)\n",
      "First few columns: ['GSM2928730', 'GSM2928731', 'GSM2928732', 'GSM2928733', 'GSM2928734']\n",
      "Columns in linked_data: ['GSM2928730', 'GSM2928731', 'GSM2928732', 'GSM2928733', 'GSM2928734']\n",
      "Using trait column: GSM2928730\n",
      "Shape after handling missing values: (3, 91)\n",
      "For the feature 'GSM2928730', the least common label is '37.5' with 1 occurrences. This represents 33.33% of the dataset.\n",
      "The distribution of the feature 'GSM2928730' in this dataset is fine.\n",
      "\n",
      "A new JSON file was created at: ../../output/preprocess/Rectal_Cancer/cohort_info.json\n",
      "Linked data saved to ../../output/preprocess/Rectal_Cancer/GSE109057.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the obtained 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",
    "# Get clinical data from previous step\n",
    "# Load the clinical features from the saved file\n",
    "clinical_file_path = out_clinical_data_file\n",
    "if os.path.exists(clinical_file_path):\n",
    "    clinical_features = pd.read_csv(clinical_file_path)\n",
    "    print(f\"Clinical features loaded from {clinical_file_path}\")\n",
    "    print(f\"Clinical features shape: {clinical_features.shape}\")\n",
    "else:\n",
    "    # If file doesn't exist, we need to extract it again\n",
    "    clinical_features = geo_select_clinical_features(\n",
    "        clinical_df=clinical_data,\n",
    "        trait=trait,\n",
    "        trait_row=2,\n",
    "        convert_trait=convert_trait,\n",
    "        age_row=3,\n",
    "        convert_age=convert_age,\n",
    "        gender_row=None,\n",
    "        convert_gender=None\n",
    "    )\n",
    "    print(f\"Clinical features re-extracted\")\n",
    "    print(f\"Clinical features shape: {clinical_features.shape}\")\n",
    "\n",
    "# 2. Link the clinical and genetic data\n",
    "linked_data = geo_link_clinical_genetic_data(clinical_features.T, normalized_gene_data)\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "print(f\"First few columns: {list(linked_data.columns[:5])}\")\n",
    "\n",
    "# Check what columns are available in the linked data\n",
    "print(f\"Columns in linked_data: {list(linked_data.columns[:5])}\")\n",
    "\n",
    "# 3. Handle missing values in the linked data\n",
    "# Find the correct trait column name (it should be the first column)\n",
    "trait_column = linked_data.columns[0]\n",
    "print(f\"Using trait column: {trait_column}\")\n",
    "\n",
    "linked_data_processed = handle_missing_values(linked_data, trait_column)\n",
    "print(f\"Shape after handling missing values: {linked_data_processed.shape}\")\n",
    "\n",
    "# Add validation check - if no samples remain, note the issue\n",
    "if linked_data_processed.shape[0] == 0:\n",
    "    print(\"No samples remain after handling missing values. The dataset cannot be processed further.\")\n",
    "    is_trait_biased = True  # Mark as biased since we can't use it\n",
    "    unbiased_linked_data = linked_data_processed\n",
    "else:\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_processed, trait_column)\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=\"Dataset contains gene expression data from rectal cancer patients with treatment response data (sensitive/resistant).\"\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
}