File size: 24,048 Bytes
82732bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "6642163a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:47:37.173812Z",
     "iopub.status.busy": "2025-03-25T03:47:37.173643Z",
     "iopub.status.idle": "2025-03-25T03:47:37.333991Z",
     "shell.execute_reply": "2025-03-25T03:47:37.333660Z"
    }
   },
   "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 = \"GSE94104\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Rectal_Cancer\"\n",
    "in_cohort_dir = \"../../input/GEO/Rectal_Cancer/GSE94104\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Rectal_Cancer/GSE94104.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Rectal_Cancer/gene_data/GSE94104.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Rectal_Cancer/clinical_data/GSE94104.csv\"\n",
    "json_path = \"../../output/preprocess/Rectal_Cancer/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "23d0fca2",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "2ad74920",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:47:37.335325Z",
     "iopub.status.busy": "2025-03-25T03:47:37.335192Z",
     "iopub.status.idle": "2025-03-25T03:47:37.472679Z",
     "shell.execute_reply": "2025-03-25T03:47:37.472401Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Transcriptional analysis of locally advanced rectal cancer pre-therapeutic biopsies and post-therapeutic resections\"\n",
      "!Series_summary\t\"Understanding transcriptional changes in locally advanced rectal cancer which are therapy-related and dependent upon tumour regression will drive stratified medicine in the rectal cancer paradigm\"\n",
      "!Series_overall_design\t\"Total RNA was obtained from 40 matched formalin fixed paraffin embedded (FFPE) LARC biopsy and resections specimens provided by the Northern Ireland Biobank and arrayed using the Illumina HumanHT-12 WG-DASL V4 expression beadchip\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['tissue: Locally Advanced Rectal Cancer (LARC)'], 1: ['tissue type: Biopsy', 'tissue type: Resection'], 2: ['tumour regression grade: 1', 'tumour regression grade: 2', 'tumour regression grade: 3']}\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": "0bfb6de3",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "8e808c8a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:47:37.473763Z",
     "iopub.status.busy": "2025-03-25T03:47:37.473657Z",
     "iopub.status.idle": "2025-03-25T03:47:37.481987Z",
     "shell.execute_reply": "2025-03-25T03:47:37.481713Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical features preview:\n",
      "{'GSM2469019': [0.0], 'GSM2469020': [0.0], 'GSM2469021': [0.0], 'GSM2469022': [0.0], 'GSM2469023': [0.0], 'GSM2469024': [0.0], 'GSM2469025': [0.0], 'GSM2469026': [0.0], 'GSM2469027': [1.0], 'GSM2469028': [1.0], 'GSM2469029': [0.0], 'GSM2469030': [0.0], 'GSM2469031': [1.0], 'GSM2469032': [1.0], 'GSM2469033': [1.0], 'GSM2469034': [1.0], 'GSM2469035': [0.0], 'GSM2469036': [0.0], 'GSM2469037': [0.0], 'GSM2469038': [0.0], 'GSM2469039': [1.0], 'GSM2469040': [1.0], 'GSM2469041': [0.0], 'GSM2469042': [0.0], 'GSM2469043': [0.0], 'GSM2469044': [0.0], 'GSM2469045': [0.0], 'GSM2469046': [0.0], 'GSM2469047': [0.0], 'GSM2469048': [0.0], 'GSM2469049': [0.0], 'GSM2469050': [0.0], 'GSM2469051': [0.0], 'GSM2469052': [0.0], 'GSM2469053': [0.0], 'GSM2469054': [0.0], 'GSM2469055': [0.0], 'GSM2469056': [0.0], 'GSM2469057': [0.0], 'GSM2469058': [0.0], 'GSM2469059': [0.0], 'GSM2469060': [0.0], 'GSM2469061': [1.0], 'GSM2469062': [1.0], 'GSM2469063': [1.0], 'GSM2469064': [1.0], 'GSM2469065': [0.0], 'GSM2469066': [0.0], 'GSM2469067': [0.0], 'GSM2469068': [0.0], 'GSM2469069': [0.0], 'GSM2469070': [1.0], 'GSM2469071': [0.0], 'GSM2469072': [0.0], 'GSM2469073': [0.0], 'GSM2469074': [0.0], 'GSM2469075': [0.0], 'GSM2469076': [1.0], 'GSM2469077': [0.0], 'GSM2469078': [0.0], 'GSM2469079': [0.0], 'GSM2469080': [1.0], 'GSM2469081': [1.0], 'GSM2469082': [0.0], 'GSM2469083': [1.0], 'GSM2469084': [0.0], 'GSM2469085': [0.0], 'GSM2469086': [0.0], 'GSM2469087': [1.0], 'GSM2469088': [0.0], 'GSM2469089': [1.0], 'GSM2469090': [1.0], 'GSM2469091': [0.0], 'GSM2469092': [1.0], 'GSM2469093': [0.0], 'GSM2469094': [0.0], 'GSM2469095': [0.0], 'GSM2469096': [0.0], 'GSM2469097': [0.0], 'GSM2469098': [1.0]}\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Availability\n",
    "# Based on the background information, the dataset appears to contain gene expression data\n",
    "# as it mentions \"expression beadchip\" data\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "\n",
    "# 2.1 Data Availability\n",
    "# For trait: \"tumour regression grade\" is recorded in row 2\n",
    "trait_row = 2\n",
    "\n",
    "# Age is not explicitly mentioned in the characteristics dictionary\n",
    "age_row = None\n",
    "\n",
    "# Gender is not explicitly mentioned in the characteristics dictionary\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "\n",
    "def convert_trait(value):\n",
    "    \"\"\"\n",
    "    Convert tumour regression grade to binary.\n",
    "    Grade 1-2 (good regression) -> 0, Grade 3 (poor regression) -> 1\n",
    "    \"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    try:\n",
    "        grade = int(value)\n",
    "        if grade == 1 or grade == 2:\n",
    "            return 0  # Good regression\n",
    "        elif grade == 3:\n",
    "            return 1  # Poor regression\n",
    "        else:\n",
    "            return None\n",
    "    except:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Placeholder function for age conversion, not used in this dataset\"\"\"\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Placeholder function for gender conversion, not used in this dataset\"\"\"\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait availability based on whether trait_row is None\n",
    "is_trait_available = trait_row is not None\n",
    "\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",
    "    # Extract clinical features\n",
    "    clinical_features = 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 resulting DataFrame\n",
    "    print(\"Clinical features preview:\")\n",
    "    print(preview_df(clinical_features))\n",
    "    \n",
    "    # Save to CSV\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    clinical_features.to_csv(out_clinical_data_file)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a4a74725",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "0450be96",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:47:37.482988Z",
     "iopub.status.busy": "2025-03-25T03:47:37.482889Z",
     "iopub.status.idle": "2025-03-25T03:47:37.716510Z",
     "shell.execute_reply": "2025-03-25T03:47:37.716137Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['ILMN_1343291', 'ILMN_1651209', 'ILMN_1651228', 'ILMN_1651229',\n",
      "       'ILMN_1651235', 'ILMN_1651236', 'ILMN_1651237', 'ILMN_1651238',\n",
      "       'ILMN_1651254', 'ILMN_1651260', 'ILMN_1651262', 'ILMN_1651268',\n",
      "       'ILMN_1651278', 'ILMN_1651282', 'ILMN_1651285', 'ILMN_1651286',\n",
      "       'ILMN_1651292', 'ILMN_1651303', 'ILMN_1651309', 'ILMN_1651315'],\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": "6fabf12d",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "813412ff",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:47:37.718035Z",
     "iopub.status.busy": "2025-03-25T03:47:37.717919Z",
     "iopub.status.idle": "2025-03-25T03:47:37.719699Z",
     "shell.execute_reply": "2025-03-25T03:47:37.719433Z"
    }
   },
   "outputs": [],
   "source": [
    "# These are Illumina probe IDs (ILMN_*), which are not human gene symbols\n",
    "# They need to be mapped to human gene symbols for biological interpretation\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ce20aaf7",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "3200eda8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:47:37.720780Z",
     "iopub.status.busy": "2025-03-25T03:47:37.720682Z",
     "iopub.status.idle": "2025-03-25T03:47:41.913085Z",
     "shell.execute_reply": "2025-03-25T03:47:41.912672Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['ILMN_3166687', 'ILMN_3165566', 'ILMN_3164811', 'ILMN_3165363', 'ILMN_3166511'], 'Transcript': ['ILMN_333737', 'ILMN_333646', 'ILMN_333584', 'ILMN_333628', 'ILMN_333719'], 'Species': ['ILMN Controls', 'ILMN Controls', 'ILMN Controls', 'ILMN Controls', 'ILMN Controls'], 'Source': ['ILMN_Controls', 'ILMN_Controls', 'ILMN_Controls', 'ILMN_Controls', 'ILMN_Controls'], 'Search_Key': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'ILMN_Gene': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'Source_Reference_ID': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': ['DQ516750', 'DQ883654', 'DQ668364', 'DQ516785', 'DQ854995'], 'Symbol': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'Protein_Product': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5270161.0, 4260594.0, 7610424.0, 5260356.0, 2030196.0], 'Probe_Type': ['S', 'S', 'S', 'S', 'S'], 'Probe_Start': [12.0, 224.0, 868.0, 873.0, 130.0], 'SEQUENCE': ['CCCATGTGTCCAATTCTGAATATCTTTCCAGCTAAGTGCTTCTGCCCACC', 'GGATTAACTGCTGTGGTGTGTCATACTCGGCTACCTCCTGGTTTGGCGTC', 'GACCACGCCTTGTAATCGTATGACACGCGCTTGACACGACTGAATCCAGC', 'CTGCAATGCCATTAACAACCTTAGCACGGTATTTCCAGTAGCTGGTGAGC', 'CGTGCAGACAGGGATCGTAAGGCGATCCAGCCGGTATACCTTAGTCACAT'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': ['Methanocaldococcus jannaschii spike-in control MJ-500-33 genomic sequence', 'Synthetic construct clone NISTag13 external RNA control sequence', 'Synthetic construct clone TagJ microarray control', 'Methanocaldococcus jannaschii spike-in control MJ-1000-68 genomic sequence', 'Synthetic construct clone AG006.1100 external RNA control sequence'], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': ['DQ516750', 'DQ883654', 'DQ668364', 'DQ516785', 'DQ854995']}\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": "2d9740bf",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "df678434",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:47:41.914269Z",
     "iopub.status.busy": "2025-03-25T03:47:41.914149Z",
     "iopub.status.idle": "2025-03-25T03:47:42.980585Z",
     "shell.execute_reply": "2025-03-25T03:47:42.980177Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found mapping for 29377 probes\n",
      "First few rows of mapping dataframe:\n",
      "             ID        Gene\n",
      "0  ILMN_3166687  ERCC-00162\n",
      "1  ILMN_3165566  ERCC-00071\n",
      "2  ILMN_3164811  ERCC-00009\n",
      "3  ILMN_3165363  ERCC-00053\n",
      "4  ILMN_3166511  ERCC-00144\n",
      "Converted expression data to 18407 genes\n",
      "First few genes after mapping:\n",
      "Index(['A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1', 'A4GALT',\n",
      "       'A4GNT', 'AAA1'],\n",
      "      dtype='object', name='Gene')\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the relevant columns for mapping\n",
    "# 'ID' in gene_annotation corresponds to probe IDs (ILMN_*) in gene_data\n",
    "# 'Symbol' appears to contain gene symbols to map to\n",
    "probe_col = 'ID'  # Column containing probe identifiers\n",
    "gene_col = 'Symbol'  # Column containing gene symbols\n",
    "\n",
    "# 2. Get gene mapping dataframe\n",
    "mapping_df = get_gene_mapping(gene_annotation, probe_col, gene_col)\n",
    "print(f\"Found mapping for {len(mapping_df)} probes\")\n",
    "print(\"First few rows of mapping dataframe:\")\n",
    "print(mapping_df.head())\n",
    "\n",
    "# 3. Convert probe-level measurements to gene-level expression data\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
    "print(f\"Converted expression data to {len(gene_data)} genes\")\n",
    "print(\"First few genes after mapping:\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# Save the gene expression data\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "gene_data.to_csv(out_gene_data_file)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "41563f42",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "7865d256",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:47:42.982042Z",
     "iopub.status.busy": "2025-03-25T03:47:42.981903Z",
     "iopub.status.idle": "2025-03-25T03:47:53.721759Z",
     "shell.execute_reply": "2025-03-25T03:47:53.721385Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical data saved to ../../output/preprocess/Rectal_Cancer/clinical_data/GSE94104.csv\n",
      "Normalized gene data shape: (17833, 80)\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/GSE94104.csv\n",
      "Linked data shape: (80, 17834)\n",
      "            Rectal_Cancer       A1BG  A1BG-AS1       A1CF        A2M  \\\n",
      "GSM2469019            0.0   7.395705  8.398890  28.693917  13.337807   \n",
      "GSM2469020            0.0   8.551503  8.688974  26.624397  14.148331   \n",
      "GSM2469021            0.0  10.632415  7.824079  23.596701  13.451809   \n",
      "GSM2469022            0.0   8.816704  7.720825  25.802108  13.616095   \n",
      "GSM2469023            0.0   9.020842  7.200367  30.043000  13.611848   \n",
      "\n",
      "               A2ML1     A4GALT     A4GNT       AAA1       AAAS  ...  \\\n",
      "GSM2469019  7.472346  12.487900  5.906503  37.780392  10.477635  ...   \n",
      "GSM2469020  8.259388  12.611664  5.611697  31.996606  11.295834  ...   \n",
      "GSM2469021  8.393553  10.865053  5.687393  40.876755   9.940273  ...   \n",
      "GSM2469022  5.889630  11.647056  5.497962  36.785756  10.388437  ...   \n",
      "GSM2469023  6.835435   9.823508  5.313831  48.428284   8.857288  ...   \n",
      "\n",
      "               ZWILCH      ZWINT       ZXDA       ZXDB       ZXDC    ZYG11A  \\\n",
      "GSM2469019  30.149135  37.752388  22.288420  11.764753  20.882875  8.234774   \n",
      "GSM2469020  29.069801  29.432566  22.036817  12.434532  20.963560  4.709127   \n",
      "GSM2469021  31.743675  39.536836  21.656870  12.933958  22.473772  8.849611   \n",
      "GSM2469022  31.820129  34.378828  21.310831  12.629729  21.681174  6.579239   \n",
      "GSM2469023  31.424952  35.648354  22.305948  13.162210  20.842217  8.530401   \n",
      "\n",
      "               ZYG11B        ZYX      ZZEF1       ZZZ3  \n",
      "GSM2469019  11.308405  21.453710  10.393851  22.659554  \n",
      "GSM2469020  11.738357  21.241659  11.039158  23.197248  \n",
      "GSM2469021  12.070824  21.649831   9.797775  20.884220  \n",
      "GSM2469022  12.401734  22.395284  10.095616  22.742967  \n",
      "GSM2469023  11.999437  20.363729   9.712065  21.665297  \n",
      "\n",
      "[5 rows x 17834 columns]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Shape after handling missing values: (80, 17834)\n",
      "For the feature 'Rectal_Cancer', the least common label is '1.0' with 22 occurrences. This represents 27.50% of the dataset.\n",
      "The distribution of the feature 'Rectal_Cancer' in this dataset is fine.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Rectal_Cancer/GSE94104.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
}