File size: 28,135 Bytes
736e4a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "fab1f182",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:30:23.199213Z",
     "iopub.status.busy": "2025-03-25T06:30:23.198707Z",
     "iopub.status.idle": "2025-03-25T06:30:23.365181Z",
     "shell.execute_reply": "2025-03-25T06:30:23.364843Z"
    }
   },
   "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 = \"Ankylosing_Spondylitis\"\n",
    "cohort = \"GSE25101\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Ankylosing_Spondylitis\"\n",
    "in_cohort_dir = \"../../input/GEO/Ankylosing_Spondylitis/GSE25101\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Ankylosing_Spondylitis/GSE25101.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Ankylosing_Spondylitis/gene_data/GSE25101.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Ankylosing_Spondylitis/clinical_data/GSE25101.csv\"\n",
    "json_path = \"../../output/preprocess/Ankylosing_Spondylitis/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "46b318b9",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "26ee1954",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:30:23.366608Z",
     "iopub.status.busy": "2025-03-25T06:30:23.366461Z",
     "iopub.status.idle": "2025-03-25T06:30:23.433821Z",
     "shell.execute_reply": "2025-03-25T06:30:23.433524Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Expression profiling in whole blood in ankylosing spondylitis patients and controls\"\n",
      "!Series_summary\t\"Introduction: A number of genetic-association studies have identified genes contributing to AS susceptibility but such approaches provide little information as to the gene activity changes occurring during the disease process. Transcriptional profiling generates a “snapshot” of the sampled cells activity and thus can provide insights into the molecular processes driving the disease process. We undertook a whole-genome microarray approach to identify candidate genes associated with AS and validated these gene-expression changes in a larger sample cohort.  Methods: 18 active AS patients, classified according to the New York criteria. and 18 gender-and age-matched controls were profiled using Illumina HT-12 Whole-Genome Expression BeadChips which carry cDNAs for 48000 genes and transcripts. Class comparison analysis identified a number of differentially expressed candidate genes. These candidate genes were then validated in a larger cohort using qPCR-based TaqMan Low Density Arrays (TLDAs).  Results: 239 probes corresponding to 221 genes were identified as being significantly different between patients and controls with a p-value <0.0005 (80% confidence level of false discovery rate). Forty seven genes were then selected for validation studies, using the TLDAs. Thirteen of these genes were validated in the second patient cohort with 12 down-regulated 1.3-2-fold and only 1 upregulated (1.6-fold). Among a number of identified genes with well-documented inflammatory roles we also validated genes that might be of great interest to the understanding of AS progression such as SPOCK2 (osteonectin) and EP300 which modulate cartilage and bone metabolism.  Conclusion: We have validated a gene expression signature for AS from whole blood and identified strong candidate genes that may play roles in both the inflammatory and joint destruction aspects of the disease.\"\n",
      "!Series_overall_design\t\"RNA was extracted from whole blood using PAXGene tubes. 16 AS patients with active disease and 16 gender- and age-matched controls were analysed.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['tissue: Whole blood'], 1: ['cell type: PBMC'], 2: ['disease status: Ankylosing spondylitis patient', 'disease status: Normal control']}\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": "3d431616",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "048b5bc3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:30:23.434904Z",
     "iopub.status.busy": "2025-03-25T06:30:23.434796Z",
     "iopub.status.idle": "2025-03-25T06:30:23.442035Z",
     "shell.execute_reply": "2025-03-25T06:30:23.441749Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of selected clinical data:\n",
      "{'GSM616668': [1.0], 'GSM616669': [1.0], 'GSM616670': [1.0], 'GSM616671': [1.0], 'GSM616672': [1.0], 'GSM616673': [1.0], 'GSM616674': [1.0], 'GSM616675': [1.0], 'GSM616676': [1.0], 'GSM616677': [1.0], 'GSM616678': [1.0], 'GSM616679': [1.0], 'GSM616680': [1.0], 'GSM616681': [1.0], 'GSM616682': [1.0], 'GSM616683': [1.0], 'GSM616684': [0.0], 'GSM616685': [0.0], 'GSM616686': [0.0], 'GSM616687': [0.0], 'GSM616688': [0.0], 'GSM616689': [0.0], 'GSM616690': [0.0], 'GSM616691': [0.0], 'GSM616692': [0.0], 'GSM616693': [0.0], 'GSM616694': [0.0], 'GSM616695': [0.0], 'GSM616696': [0.0], 'GSM616697': [0.0], 'GSM616698': [0.0], 'GSM616699': [0.0]}\n",
      "Clinical data saved to ../../output/preprocess/Ankylosing_Spondylitis/clinical_data/GSE25101.csv\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "import json\n",
    "from typing import Callable, Optional, Dict, Any\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# From the background information, this is a whole-genome microarray study\n",
    "# using Illumina HT-12 Whole-Genome Expression BeadChips which carry cDNAs for 48000 genes\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Clinical Feature Extraction and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# Looking at the sample characteristics dictionary:\n",
    "# Key 2 contains disease status which relates to our trait (Ankylosing_Spondylitis)\n",
    "trait_row = 2\n",
    "\n",
    "# No age information is available in the sample characteristics\n",
    "age_row = None\n",
    "\n",
    "# No gender information is available in the sample characteristics\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "def convert_trait(value: str) -> int:\n",
    "    \"\"\"\n",
    "    Convert Ankylosing Spondylitis disease status to binary values.\n",
    "    0 = Normal control (no disease)\n",
    "    1 = Ankylosing spondylitis patient (has disease)\n",
    "    \"\"\"\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    if \"ankylosing spondylitis patient\" in value.lower():\n",
    "        return 1\n",
    "    elif \"normal control\" in value.lower():\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value: str) -> float:\n",
    "    \"\"\"\n",
    "    Convert age to continuous value.\n",
    "    Not used in this dataset as age information is not available.\n",
    "    \"\"\"\n",
    "    return None\n",
    "\n",
    "def convert_gender(value: str) -> int:\n",
    "    \"\"\"\n",
    "    Convert gender to binary value.\n",
    "    Not used in this dataset as gender information is not available.\n",
    "    \"\"\"\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait data availability\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Save initial validation information\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 (if trait_row is not None)\n",
    "if trait_row is not None:\n",
    "    # Create a directory for the clinical data if it doesn't exist\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    \n",
    "    # Assuming clinical_data is already loaded in the environment from a previous step\n",
    "    # If not, we'll need to skip this part\n",
    "    try:\n",
    "        # Extract clinical features\n",
    "        selected_clinical_df = geo_select_clinical_features(\n",
    "            clinical_df=clinical_data,  # Use the variable from the environment\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 clinical data\n",
    "        preview = preview_df(selected_clinical_df)\n",
    "        print(\"Preview of selected clinical data:\")\n",
    "        print(preview)\n",
    "        \n",
    "        # Save the 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",
    "    except NameError:\n",
    "        print(\"Clinical data not found in the environment. This step will be handled in a subsequent processing stage.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "43a92a18",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "2787cc9d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:30:23.442994Z",
     "iopub.status.busy": "2025-03-25T06:30:23.442888Z",
     "iopub.status.idle": "2025-03-25T06:30:23.520421Z",
     "shell.execute_reply": "2025-03-25T06:30:23.520099Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "First 20 gene/probe identifiers:\n",
      "Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651209', 'ILMN_1651228',\n",
      "       'ILMN_1651229', 'ILMN_1651232', 'ILMN_1651237', 'ILMN_1651254',\n",
      "       'ILMN_1651262', 'ILMN_1651268', 'ILMN_1651278', 'ILMN_1651282',\n",
      "       'ILMN_1651286', 'ILMN_1651296', 'ILMN_1651315', 'ILMN_1651316',\n",
      "       'ILMN_1651328', 'ILMN_1651336', 'ILMN_1651341', 'ILMN_1651346'],\n",
      "      dtype='object', name='ID')\n",
      "\n",
      "Gene data dimensions: 18168 genes × 32 samples\n"
     ]
    }
   ],
   "source": [
    "# 1. Re-identify the SOFT and matrix files to ensure we have the correct paths\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. Extract the gene expression data from the matrix file\n",
    "gene_data = get_genetic_data(matrix_file)\n",
    "\n",
    "# 3. Print the first 20 row IDs (gene or probe identifiers)\n",
    "print(\"\\nFirst 20 gene/probe identifiers:\")\n",
    "print(gene_data.index[:20])\n",
    "\n",
    "# 4. Print the dimensions of the gene expression data\n",
    "print(f\"\\nGene data dimensions: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
    "\n",
    "# Note: we keep is_gene_available as True since we successfully extracted gene expression data\n",
    "is_gene_available = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6101e2af",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "13ff3911",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:30:23.521619Z",
     "iopub.status.busy": "2025-03-25T06:30:23.521502Z",
     "iopub.status.idle": "2025-03-25T06:30:23.523340Z",
     "shell.execute_reply": "2025-03-25T06:30:23.523067Z"
    }
   },
   "outputs": [],
   "source": [
    "# Analyzing the gene identifiers from the previous step\n",
    "# These are Illumina BeadArray identifiers (ILMN_) which are probe IDs, not gene symbols\n",
    "# They need to be mapped to human gene symbols for proper biological interpretation\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "77c62367",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "609cdda0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:30:23.524420Z",
     "iopub.status.busy": "2025-03-25T06:30:23.524314Z",
     "iopub.status.idle": "2025-03-25T06:30:25.018442Z",
     "shell.execute_reply": "2025-03-25T06:30:25.018072Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['ILMN_1725881', 'ILMN_1910180', 'ILMN_1804174', 'ILMN_1796063', 'ILMN_1811966'], 'nuID': ['rp13_p1x6D80lNLk3c', 'NEX0oqCV8.er4HVfU4', 'KyqQynMZxJcruyylEU', 'xXl7eXuF7sbPEp.KFI', '9ckqJrioiaej9_ajeQ'], 'Species': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Source': ['RefSeq', 'Unigene', 'RefSeq', 'RefSeq', 'RefSeq'], 'Search_Key': ['ILMN_44919', 'ILMN_127219', 'ILMN_139282', 'ILMN_5006', 'ILMN_38756'], 'Transcript': ['ILMN_44919', 'ILMN_127219', 'ILMN_139282', 'ILMN_5006', 'ILMN_38756'], 'ILMN_Gene': ['LOC23117', 'HS.575038', 'FCGR2B', 'TRIM44', 'LOC653895'], 'Source_Reference_ID': ['XM_933824.1', 'Hs.575038', 'XM_938851.1', 'NM_017583.3', 'XM_936379.1'], 'RefSeq_ID': ['XM_933824.1', nan, 'XM_938851.1', 'NM_017583.3', 'XM_936379.1'], 'Unigene_ID': [nan, 'Hs.575038', nan, nan, nan], 'Entrez_Gene_ID': [23117.0, nan, 2213.0, 54765.0, 653895.0], 'GI': [89040007.0, 10437021.0, 88952550.0, 29029528.0, 89033487.0], 'Accession': ['XM_933824.1', 'AK024680', 'XM_938851.1', 'NM_017583.3', 'XM_936379.1'], 'Symbol': ['LOC23117', nan, 'FCGR2B', 'TRIM44', 'LOC653895'], 'Protein_Product': ['XP_938917.1', nan, 'XP_943944.1', 'NP_060053.2', 'XP_941472.1'], 'Array_Address_Id': [1710221.0, 5900364.0, 2480717.0, 1300239.0, 4480719.0], 'Probe_Type': ['I', 'S', 'I', 'S', 'S'], 'Probe_Start': [122.0, 1409.0, 1643.0, 2901.0, 25.0], 'SEQUENCE': ['GGCTCCTCTTTGGGCTCCTACTGGAATTTATCAGCCATCAGTGCATCTCT', 'ACACCTTCAGGAGGGAAGCCCTTATTTCTGGGTTGAACTCCCCTTCCATG', 'TAGGGGCAATAGGCTATACGCTACAGCCTAGGTGTGTAGTAGGCCACACC', 'CCTGCCTGTCTGCCTGTGACCTGTGTACGTATTACAGGCTTTAGGACCAG', 'CTAGCAGGGAGCGGTGAGGGAGAGCGGCTGGATTTCTTGCGGGATCTGCA'], 'Chromosome': ['16', nan, nan, '11', nan], 'Probe_Chr_Orientation': ['-', nan, nan, '+', nan], 'Probe_Coordinates': ['21766363-21766363:21769901-21769949', nan, nan, '35786070-35786119', nan], 'Cytoband': ['16p12.2a', nan, '1q23.3b', '11p13a', '10q11.23b'], 'Definition': ['PREDICTED: Homo sapiens KIAA0220-like protein, transcript variant 11 (LOC23117), mRNA.', 'Homo sapiens cDNA: FLJ21027 fis, clone CAE07110', 'PREDICTED: Homo sapiens Fc fragment of IgG, low affinity IIb, receptor (CD32) (FCGR2B), mRNA.', 'Homo sapiens tripartite motif-containing 44 (TRIM44), mRNA.', 'PREDICTED: Homo sapiens similar to protein geranylgeranyltransferase type I, beta subunit (LOC653895), mRNA.'], 'Ontology_Component': [nan, nan, nan, 'intracellular [goid 5622] [evidence IEA]', nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, 'zinc ion binding [goid 8270] [evidence IEA]; metal ion binding [goid 46872] [evidence IEA]', nan], 'Synonyms': [nan, nan, nan, 'MGC3490; MC7; HSA249128; DIPB', nan], 'Obsolete_Probe_Id': [nan, nan, nan, 'MGC3490; MC7; HSA249128; DIPB', nan], 'GB_ACC': ['XM_933824.1', 'AK024680', 'XM_938851.1', 'NM_017583.3', 'XM_936379.1']}\n"
     ]
    }
   ],
   "source": [
    "# 1. First get the file paths using geo_get_relevant_filepaths function\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. 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",
    "# 3. 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": "beeecafd",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "cd0a929e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:30:25.019830Z",
     "iopub.status.busy": "2025-03-25T06:30:25.019703Z",
     "iopub.status.idle": "2025-03-25T06:30:25.384239Z",
     "shell.execute_reply": "2025-03-25T06:30:25.383865Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Total probe IDs in annotation: 630984\n",
      "Total probe IDs with gene symbols: 36157\n",
      "\n",
      "Number of unique genes after mapping: 11631\n",
      "\n",
      "First 10 gene symbols:\n",
      "Index(['A26A1', 'AAAS', 'AACS', 'AACSL', 'AADACL1', 'AAK1', 'AAMP', 'AARS',\n",
      "       'AARS2', 'AARSD1'],\n",
      "      dtype='object', name='Gene')\n",
      "\n",
      "Number of genes after normalization: 11317\n",
      "\n",
      "First 10 normalized gene symbols:\n",
      "Index(['AAAS', 'AACS', 'AACSP1', 'AAK1', 'AAMDC', 'AAMP', 'AAR2', 'AARS1',\n",
      "       'AARS2', 'AARSD1'],\n",
      "      dtype='object', name='Gene')\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene expression data saved to ../../output/preprocess/Ankylosing_Spondylitis/gene_data/GSE25101.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the column names for mapping\n",
    "# From the gene annotation preview, I can see that:\n",
    "# - 'ID' column contains the ILMN identifiers (e.g., ILMN_1725881) same as in the gene expression data\n",
    "# - 'Symbol' column contains the gene symbols (e.g., LOC23117, FCGR2B, TRIM44)\n",
    "\n",
    "# 2. Extract the mapping between IDs and gene symbols\n",
    "gene_map_df = get_gene_mapping(gene_annotation, 'ID', 'Symbol')\n",
    "\n",
    "# Print mapping statistics\n",
    "print(f\"Total probe IDs in annotation: {len(gene_annotation)}\")\n",
    "print(f\"Total probe IDs with gene symbols: {len(gene_map_df)}\")\n",
    "\n",
    "# 3. Convert probe-level measurements to gene-level expression data\n",
    "gene_data = apply_gene_mapping(gene_data, gene_map_df)\n",
    "\n",
    "# 4. Print results of the gene mapping\n",
    "print(f\"\\nNumber of unique genes after mapping: {len(gene_data)}\")\n",
    "print(\"\\nFirst 10 gene symbols:\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# 5. Normalize gene symbols to handle synonyms and ensure consistency\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"\\nNumber of genes after normalization: {len(gene_data)}\")\n",
    "print(\"\\nFirst 10 normalized gene symbols:\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# 6. Create directory and 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",
    "print(f\"\\nGene expression data saved to {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cba66c58",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "76537054",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:30:25.385575Z",
     "iopub.status.busy": "2025-03-25T06:30:25.385455Z",
     "iopub.status.idle": "2025-03-25T06:30:28.997898Z",
     "shell.execute_reply": "2025-03-25T06:30:28.997267Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalizing gene symbols in the gene expression data...\n",
      "Original gene data shape: 11317 genes × 32 samples\n",
      "Normalized gene data shape: 11317 genes × 32 samples\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene expression data saved to ../../output/preprocess/Ankylosing_Spondylitis/gene_data/GSE25101.csv\n",
      "Extracting clinical features from original clinical data...\n",
      "Clinical features saved to ../../output/preprocess/Ankylosing_Spondylitis/clinical_data/GSE25101.csv\n",
      "Clinical features preview:\n",
      "{'GSM616668': [1.0], 'GSM616669': [1.0], 'GSM616670': [1.0], 'GSM616671': [1.0], 'GSM616672': [1.0], 'GSM616673': [1.0], 'GSM616674': [1.0], 'GSM616675': [1.0], 'GSM616676': [1.0], 'GSM616677': [1.0], 'GSM616678': [1.0], 'GSM616679': [1.0], 'GSM616680': [1.0], 'GSM616681': [1.0], 'GSM616682': [1.0], 'GSM616683': [1.0], 'GSM616684': [0.0], 'GSM616685': [0.0], 'GSM616686': [0.0], 'GSM616687': [0.0], 'GSM616688': [0.0], 'GSM616689': [0.0], 'GSM616690': [0.0], 'GSM616691': [0.0], 'GSM616692': [0.0], 'GSM616693': [0.0], 'GSM616694': [0.0], 'GSM616695': [0.0], 'GSM616696': [0.0], 'GSM616697': [0.0], 'GSM616698': [0.0], 'GSM616699': [0.0]}\n",
      "Linking clinical and genetic data...\n",
      "Linked data shape: (32, 11318)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Data shape after handling missing values: (32, 11318)\n",
      "\n",
      "Checking for bias in feature variables:\n",
      "For the feature 'Ankylosing_Spondylitis', the least common label is '1.0' with 16 occurrences. This represents 50.00% of the dataset.\n",
      "The distribution of the feature 'Ankylosing_Spondylitis' in this dataset is fine.\n",
      "\n",
      "A new JSON file was created at: ../../output/preprocess/Ankylosing_Spondylitis/cohort_info.json\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Ankylosing_Spondylitis/GSE25101.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "print(\"Normalizing gene symbols in the gene expression data...\")\n",
    "# From the previous step output, we can see the data already contains gene symbols\n",
    "# like 'A1BG', 'A1CF', 'A2M' which need to be normalized\n",
    "gene_data_normalized = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Original gene data shape: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
    "print(f\"Normalized gene data shape: {gene_data_normalized.shape[0]} genes × {gene_data_normalized.shape[1]} samples\")\n",
    "\n",
    "# Save the normalized gene data\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "gene_data_normalized.to_csv(out_gene_data_file)\n",
    "print(f\"Normalized gene expression data saved to {out_gene_data_file}\")\n",
    "\n",
    "# 2. Extract clinical features from scratch instead of loading the empty file\n",
    "print(\"Extracting clinical features from original clinical data...\")\n",
    "clinical_features = geo_select_clinical_features(\n",
    "    clinical_data, \n",
    "    trait, \n",
    "    trait_row,\n",
    "    convert_trait,\n",
    "    age_row,\n",
    "    convert_age,\n",
    "    gender_row,\n",
    "    convert_gender\n",
    ")\n",
    "\n",
    "# Save the extracted clinical features\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 features saved to {out_clinical_data_file}\")\n",
    "\n",
    "print(\"Clinical features preview:\")\n",
    "print(preview_df(clinical_features))\n",
    "\n",
    "# Check if clinical features were successfully extracted\n",
    "if clinical_features.empty:\n",
    "    print(\"Failed to extract clinical features. Dataset cannot be processed further.\")\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=False,\n",
    "        is_biased=True,\n",
    "        df=pd.DataFrame(),\n",
    "        note=\"Clinical features could not be extracted from the dataset.\"\n",
    "    )\n",
    "    print(\"Dataset deemed not usable due to lack of clinical features.\")\n",
    "else:\n",
    "    # 2. Link clinical and genetic data\n",
    "    print(\"Linking clinical and genetic data...\")\n",
    "    linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data_normalized)\n",
    "    print(f\"Linked data shape: {linked_data.shape}\")\n",
    "\n",
    "    # 3. Handle missing values systematically\n",
    "    linked_data = handle_missing_values(linked_data, trait_col=trait)\n",
    "    print(f\"Data shape after handling missing values: {linked_data.shape}\")\n",
    "\n",
    "    # 4. Check if the dataset is biased\n",
    "    print(\"\\nChecking for bias in feature variables:\")\n",
    "    is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "\n",
    "    # 5. Conduct final quality validation\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_biased,\n",
    "        df=linked_data,\n",
    "        note=\"Dataset contains gene expression data for aniridia patients and healthy controls.\"\n",
    "    )\n",
    "\n",
    "    # 6. Save linked data if usable\n",
    "    if is_usable:\n",
    "        os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "        linked_data.to_csv(out_data_file)\n",
    "        print(f\"Linked data saved to {out_data_file}\")\n",
    "    else:\n",
    "        print(\"Dataset deemed not usable for trait association studies, linked data not saved.\")"
   ]
  }
 ],
 "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
}