File size: 41,545 Bytes
f88156f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "88681485",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:15:12.327094Z",
     "iopub.status.busy": "2025-03-25T08:15:12.326842Z",
     "iopub.status.idle": "2025-03-25T08:15:12.496884Z",
     "shell.execute_reply": "2025-03-25T08:15:12.496428Z"
    }
   },
   "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 = \"Chronic_Fatigue_Syndrome\"\n",
    "cohort = \"GSE67311\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Chronic_Fatigue_Syndrome\"\n",
    "in_cohort_dir = \"../../input/GEO/Chronic_Fatigue_Syndrome/GSE67311\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Chronic_Fatigue_Syndrome/GSE67311.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Chronic_Fatigue_Syndrome/gene_data/GSE67311.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Chronic_Fatigue_Syndrome/clinical_data/GSE67311.csv\"\n",
    "json_path = \"../../output/preprocess/Chronic_Fatigue_Syndrome/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f5255a4a",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "ace81830",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:15:12.498336Z",
     "iopub.status.busy": "2025-03-25T08:15:12.498005Z",
     "iopub.status.idle": "2025-03-25T08:15:12.709014Z",
     "shell.execute_reply": "2025-03-25T08:15:12.708533Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Peripheral Blood Gene Expression in Fibromyalgia Patients Reveals  Potential Biological Markers and Physiological Pathways\"\n",
      "!Series_summary\t\"Fibromyalgia (FM) is a common pain disorder characterized by dysregulation in the processing of pain. Although FM has similarities with other rheumatologic pain disorders, the search for objective markers has not been successful. In the current study we analyzed gene expression in the whole blood of 70 fibromyalgia patients and 70 healthy matched controls. Global molecular profiling revealed an upregulation of several inflammatory molecules in FM patients and downregulation of specific pathways related to hypersensitivity and allergy. There was a differential expression of genes in known pathways for pain processing, such as glutamine/glutamate signaling and axonal development. We also identified a panel of candidate gene expression-based classifiers that could establish an objective blood-based molecular diagnostic to objectively identify FM patients and guide design and testing of new therapies. Ten classifier probesets (CPA3, C11orf83, LOC100131943, RGS17, PARD3B, ANKRD20A9P, TTLL7, C8orf12, KAT2B and RIOK3) provided a diagnostic sensitivity of 95% and a specificity of 96%. Molecular scores developed from these classifiers were able to clearly distinguish FM patients from healthy controls. An understanding of molecular dysregulation in fibromyalgia is in its infancy; however the results described herein indicate blood global gene expression profiling provides many testable hypotheses that deserve further exploration.\"\n",
      "!Series_overall_design\t\"Blood samples were collected in PAXgene tubes and collected samples were stored at -80oC.  The RNA was isolated using the PAXgene RNA isolation kit according to standard protocols. Total RNA was quantified on a Nanodrop spectrophotometer and visualized for quality on an Agilent Bioanalyzer. Samples with an average RIN (RNA Integrity Number) >8, indicating good quality RNA, were processed. 200ng of total RNA was amplified and then hybridized to Affymetrix® Human Gene 1.1 ST Peg arrays using standard manufacturer’s protocols on a Gene Titan MC instrument. Data was analyzed using Partek Genomics Suite (version 6.6) using RMA normalization. All genes with Log2 signal intensity less than 4.8 were excluded from analysis based on low expression. Differential expression analysis was carried out using a one way ANOVA by using Method of Moments and Fisher's Least Significant Difference (LSD) tests with a threshold p-value <0.005 for the biological and molecular function analyses, and a more conservative threshold p-value <0.001 (FDR q-value range 0.002% to 13%) for candidate diagnostic signatures.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['diagnosis: healthy control', 'diagnosis: fibromyalgia'], 1: ['tissue: peripheral blood'], 2: ['fiqr score: 8.5', 'fiqr score: -2.0', 'fiqr score: 9.8', 'fiqr score: 0.5', 'fiqr score: -1.0', 'fiqr score: -0.5', 'fiqr score: 2.2', 'fiqr score: 15.3', 'fiqr score: 4.0', 'fiqr score: 29.3', 'fiqr score: 27.2', 'fiqr score: 5.0', 'fiqr score: 1.0', 'fiqr score: 2.5', 'fiqr score: 3.0', 'fiqr score: -1.5', 'fiqr score: 1.3', 'fiqr score: 21.7', 'fiqr score: -1.2', 'fiqr score: 4.3', 'fiqr score: 6.5', 'fiqr score: 2.0', 'fiqr score: 11.7', 'fiqr score: 15.0', 'fiqr score: 6.0', 'fiqr score: 14.2', 'fiqr score: -0.2', 'fiqr score: 12.8', 'fiqr score: 15.7', 'fiqr score: 0.0'], 3: ['bmi: 36', 'bmi: 34', 'bmi: 33', 'bmi: 22', 'bmi: 24', 'bmi: 28', 'bmi: 23', 'bmi: 48', 'bmi: 25', 'bmi: 46', 'bmi: 32', 'bmi: 31', 'bmi: 21', 'bmi: 27', 'bmi: 39', 'bmi: 52', 'bmi: 37', 'bmi: 0', 'bmi: 38', 'bmi: 26', 'bmi: 42', 'bmi: 20', 'bmi: 30', 'bmi: 43', 'bmi: 35', 'bmi: 44', 'bmi: 29', 'bmi: 45', 'bmi: 40', 'bmi: 47'], 4: ['migraine: No', 'migraine: Yes', 'migraine: -'], 5: ['irritable bowel syndrome: No', 'irritable bowel syndrome: Yes', 'irritable bowel syndrome: -'], 6: ['major depression: No', 'major depression: -', 'major depression: Yes'], 7: ['bipolar disorder: No', 'bipolar disorder: -', 'bipolar disorder: Yes'], 8: ['chronic fatigue syndrome: No', nan, 'chronic fatigue syndrome: -', 'chronic fatigue syndrome: Yes']}\n"
     ]
    }
   ],
   "source": [
    "from tools.preprocess import *\n",
    "# 1. Identify the paths to the SOFT file and the matrix file\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
    "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
    "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
    "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
    "\n",
    "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
    "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
    "\n",
    "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
    "print(\"Background Information:\")\n",
    "print(background_info)\n",
    "print(\"Sample Characteristics Dictionary:\")\n",
    "print(sample_characteristics_dict)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5f31aa39",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "8ec2bc9c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:15:12.710427Z",
     "iopub.status.busy": "2025-03-25T08:15:12.710312Z",
     "iopub.status.idle": "2025-03-25T08:15:12.715054Z",
     "shell.execute_reply": "2025-03-25T08:15:12.714638Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sample characteristics file not found at ../../input/GEO/Chronic_Fatigue_Syndrome/GSE67311/sample_characteristics.csv\n",
      "Cannot extract clinical features without sample data.\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# This is likely gene expression data as it mentions \"Blood global gene expression profiling\" and\n",
    "# \"Affymetrix® Human Gene 1.1 ST Peg arrays\" in the background information\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "\n",
    "# 2.1 For trait: Chronic Fatigue Syndrome\n",
    "# From the sample characteristics dictionary, we can see row 8 contains information about CFS\n",
    "trait_row = 8\n",
    "\n",
    "# 2.2 Trait conversion function\n",
    "def convert_trait(value):\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    if isinstance(value, str):\n",
    "        value = value.lower()\n",
    "        if \"yes\" in value:\n",
    "            return 1\n",
    "        elif \"no\" in value:\n",
    "            return 0\n",
    "        else:\n",
    "            return None\n",
    "    return None\n",
    "\n",
    "# Age is not available in the dataset\n",
    "age_row = None\n",
    "def convert_age(value):\n",
    "    return None\n",
    "\n",
    "# Gender is not available in the dataset\n",
    "gender_row = None\n",
    "def convert_gender(value):\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "is_trait_available = trait_row is not None\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",
    "    # Look for the sample characteristics file in the cohort directory\n",
    "    sample_char_file = os.path.join(in_cohort_dir, \"sample_characteristics.csv\")\n",
    "    \n",
    "    if os.path.exists(sample_char_file):\n",
    "        clinical_data = pd.read_csv(sample_char_file)\n",
    "        \n",
    "        # Extract clinical features\n",
    "        selected_clinical_df = geo_select_clinical_features(\n",
    "            clinical_df=clinical_data, \n",
    "            trait=trait, \n",
    "            trait_row=trait_row, \n",
    "            convert_trait=convert_trait,\n",
    "            age_row=age_row,\n",
    "            convert_age=convert_age,\n",
    "            gender_row=gender_row,\n",
    "            convert_gender=convert_gender\n",
    "        )\n",
    "        \n",
    "        # Preview the dataframe\n",
    "        print(\"Preview of selected clinical features:\")\n",
    "        print(preview_df(selected_clinical_df))\n",
    "        \n",
    "        # Save to CSV\n",
    "        os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "        selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
    "        print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "    else:\n",
    "        print(f\"Sample characteristics file not found at {sample_char_file}\")\n",
    "        print(\"Cannot extract clinical features without sample data.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c454aad6",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "f8c87309",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:15:12.716429Z",
     "iopub.status.busy": "2025-03-25T08:15:12.716320Z",
     "iopub.status.idle": "2025-03-25T08:15:13.075545Z",
     "shell.execute_reply": "2025-03-25T08:15:13.074988Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found data marker at line 66\n",
      "Header line: \"ID_REF\"\t\"GSM1644447\"\t\"GSM1644448\"\t\"GSM1644449\"\t\"GSM1644450\"\t\"GSM1644451\"\t\"GSM1644452\"\t\"GSM1644453\"\t\"GSM1644454\"\t\"GSM1644455\"\t\"GSM1644456\"\t\"GSM1644457\"\t\"GSM1644458\"\t\"GSM1644459\"\t\"GSM1644460\"\t\"GSM1644461\"\t\"GSM1644462\"\t\"GSM1644463\"\t\"GSM1644464\"\t\"GSM1644465\"\t\"GSM1644466\"\t\"GSM1644467\"\t\"GSM1644468\"\t\"GSM1644469\"\t\"GSM1644470\"\t\"GSM1644471\"\t\"GSM1644472\"\t\"GSM1644473\"\t\"GSM1644474\"\t\"GSM1644475\"\t\"GSM1644476\"\t\"GSM1644477\"\t\"GSM1644478\"\t\"GSM1644479\"\t\"GSM1644480\"\t\"GSM1644481\"\t\"GSM1644482\"\t\"GSM1644483\"\t\"GSM1644484\"\t\"GSM1644485\"\t\"GSM1644486\"\t\"GSM1644487\"\t\"GSM1644488\"\t\"GSM1644489\"\t\"GSM1644490\"\t\"GSM1644491\"\t\"GSM1644492\"\t\"GSM1644493\"\t\"GSM1644494\"\t\"GSM1644495\"\t\"GSM1644496\"\t\"GSM1644497\"\t\"GSM1644498\"\t\"GSM1644499\"\t\"GSM1644500\"\t\"GSM1644501\"\t\"GSM1644502\"\t\"GSM1644503\"\t\"GSM1644504\"\t\"GSM1644505\"\t\"GSM1644506\"\t\"GSM1644507\"\t\"GSM1644508\"\t\"GSM1644509\"\t\"GSM1644510\"\t\"GSM1644511\"\t\"GSM1644512\"\t\"GSM1644513\"\t\"GSM1644514\"\t\"GSM1644515\"\t\"GSM1644516\"\t\"GSM1644517\"\t\"GSM1644518\"\t\"GSM1644519\"\t\"GSM1644520\"\t\"GSM1644521\"\t\"GSM1644522\"\t\"GSM1644523\"\t\"GSM1644524\"\t\"GSM1644525\"\t\"GSM1644526\"\t\"GSM1644527\"\t\"GSM1644528\"\t\"GSM1644529\"\t\"GSM1644530\"\t\"GSM1644531\"\t\"GSM1644532\"\t\"GSM1644533\"\t\"GSM1644534\"\t\"GSM1644535\"\t\"GSM1644536\"\t\"GSM1644537\"\t\"GSM1644538\"\t\"GSM1644539\"\t\"GSM1644540\"\t\"GSM1644541\"\t\"GSM1644542\"\t\"GSM1644543\"\t\"GSM1644544\"\t\"GSM1644545\"\t\"GSM1644546\"\t\"GSM1644547\"\t\"GSM1644548\"\t\"GSM1644549\"\t\"GSM1644550\"\t\"GSM1644551\"\t\"GSM1644552\"\t\"GSM1644553\"\t\"GSM1644554\"\t\"GSM1644555\"\t\"GSM1644556\"\t\"GSM1644557\"\t\"GSM1644558\"\t\"GSM1644559\"\t\"GSM1644560\"\t\"GSM1644561\"\t\"GSM1644562\"\t\"GSM1644563\"\t\"GSM1644564\"\t\"GSM1644565\"\t\"GSM1644566\"\t\"GSM1644567\"\t\"GSM1644568\"\t\"GSM1644569\"\t\"GSM1644570\"\t\"GSM1644571\"\t\"GSM1644572\"\t\"GSM1644573\"\t\"GSM1644574\"\t\"GSM1644575\"\t\"GSM1644576\"\t\"GSM1644577\"\t\"GSM1644578\"\t\"GSM1644579\"\t\"GSM1644580\"\t\"GSM1644581\"\t\"GSM1644582\"\t\"GSM1644583\"\t\"GSM1644584\"\t\"GSM1644585\"\t\"GSM1644586\"\t\"GSM1644587\"\t\"GSM1644588\"\n",
      "First data line: 7892501\t5.62341\t4.54841\t4.74053\t3.06227\t3.65178\t4.34336\t5.36535\t3.69126\t2.52748\t4.45481\t2.92058\t3.8511\t5.12552\t5.573\t4.0534\t4.01826\t3.13732\t4.08528\t2.9814\t4.50242\t3.11999\t4.39195\t3.29422\t4.65377\t4.45319\t3.90496\t5.07445\t4.45871\t3.40056\t5.43057\t3.17105\t4.24734\t3.9472\t3.26099\t4.21569\t4.80915\t3.99664\t4.83605\t3.98062\t3.68376\t4.43473\t4.48863\t5.0855\t4.75533\t3.87273\t2.65504\t3.14636\t2.8747\t2.94444\t4.67516\t5.74588\t4.40772\t4.93351\t3.68102\t4.70309\t6.77148\t3.79405\t3.50168\t4.82181\t5.26454\t5.43154\t3.56926\t4.88201\t3.77941\t4.74896\t4.85282\t3.16368\t5.73479\t4.22191\t3.30515\t3.3804\t3.91636\t5.19594\t3.73744\t3.039\t2.4157\t3.89391\t4.50269\t4.21075\t5.12803\t3.3515\t3.2859\t3.41076\t5.35577\t5.0399\t5.26434\t5.07121\t4.81385\t4.70926\t5.03955\t3.10709\t3.46736\t3.10186\t5.22351\t3.17449\t3.98248\t3.41802\t2.61387\t2.19567\t3.53848\t2.38796\t3.72276\t4.78528\t4.06687\t3.24888\t2.38341\t2.66362\t3.56916\t3.15337\t4.0438\t4.54457\t4.82199\t3.59462\t4.18813\t3.95037\t4.82841\t3.73593\t4.82214\t4.17745\t4.01625\t4.42865\t4.15125\t3.63591\t2.76813\t3.24467\t4.59799\t5.77069\t5.22108\t5.2745\t4.68387\t4.87527\t5.47274\t2.93373\t4.78499\t2.86791\t5.63311\t4.38304\t3.72055\t3.03068\t4.61205\t5.38301\t3.56539\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['7892501', '7892502', '7892503', '7892504', '7892505', '7892506',\n",
      "       '7892507', '7892508', '7892509', '7892510', '7892511', '7892512',\n",
      "       '7892513', '7892514', '7892515', '7892516', '7892517', '7892518',\n",
      "       '7892519', '7892520'],\n",
      "      dtype='object', name='ID')\n"
     ]
    }
   ],
   "source": [
    "# 1. Get the file paths for the SOFT file and matrix file\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. First, let's examine the structure of the matrix file to understand its format\n",
    "import gzip\n",
    "\n",
    "# Peek at the first few lines of the file to understand its structure\n",
    "with gzip.open(matrix_file, 'rt') as file:\n",
    "    # Read first 100 lines to find the header structure\n",
    "    for i, line in enumerate(file):\n",
    "        if '!series_matrix_table_begin' in line:\n",
    "            print(f\"Found data marker at line {i}\")\n",
    "            # Read the next line which should be the header\n",
    "            header_line = next(file)\n",
    "            print(f\"Header line: {header_line.strip()}\")\n",
    "            # And the first data line\n",
    "            first_data_line = next(file)\n",
    "            print(f\"First data line: {first_data_line.strip()}\")\n",
    "            break\n",
    "        if i > 100:  # Limit search to first 100 lines\n",
    "            print(\"Matrix table marker not found in first 100 lines\")\n",
    "            break\n",
    "\n",
    "# 3. Now try to get the genetic data with better error handling\n",
    "try:\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    print(gene_data.index[:20])\n",
    "except KeyError as e:\n",
    "    print(f\"KeyError: {e}\")\n",
    "    \n",
    "    # Alternative approach: manually extract the data\n",
    "    print(\"\\nTrying alternative approach to read the gene data:\")\n",
    "    with gzip.open(matrix_file, 'rt') as file:\n",
    "        # Find the start of the data\n",
    "        for line in file:\n",
    "            if '!series_matrix_table_begin' in line:\n",
    "                break\n",
    "                \n",
    "        # Read the headers and data\n",
    "        import pandas as pd\n",
    "        df = pd.read_csv(file, sep='\\t', index_col=0)\n",
    "        print(f\"Column names: {df.columns[:5]}\")\n",
    "        print(f\"First 20 row IDs: {df.index[:20]}\")\n",
    "        gene_data = df\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "85a1f188",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c12a2c9a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:15:13.077273Z",
     "iopub.status.busy": "2025-03-25T08:15:13.077139Z",
     "iopub.status.idle": "2025-03-25T08:15:13.079439Z",
     "shell.execute_reply": "2025-03-25T08:15:13.079010Z"
    }
   },
   "outputs": [],
   "source": [
    "# The identifiers in the gene expression data appear to be probe IDs (like \"7892501\"), not human gene symbols\n",
    "# These are likely to be Illumina microarray probe IDs that need to be mapped to gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e3b9b5b2",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "d79cc27c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:15:13.081028Z",
     "iopub.status.busy": "2025-03-25T08:15:13.080880Z",
     "iopub.status.idle": "2025-03-25T08:15:19.375899Z",
     "shell.execute_reply": "2025-03-25T08:15:19.375533Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['7896736', '7896738', '7896740', '7896742', '7896744'], 'GB_LIST': [nan, nan, 'NM_001005240,NM_001004195,NM_001005484,BC136848,BC136907', 'BC118988,AL137655', 'NM_001005277,NM_001005221,NM_001005224,NM_001005504,BC137547'], 'SPOT_ID': ['chr1:53049-54936', 'chr1:63015-63887', 'chr1:69091-70008', 'chr1:334129-334296', 'chr1:367659-368597'], 'seqname': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], 'RANGE_GB': ['NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10'], 'RANGE_STRAND': ['+', '+', '+', '+', '+'], 'RANGE_START': [53049.0, 63015.0, 69091.0, 334129.0, 367659.0], 'RANGE_STOP': [54936.0, 63887.0, 70008.0, 334296.0, 368597.0], 'total_probes': [7.0, 31.0, 24.0, 6.0, 36.0], 'gene_assignment': ['---', '---', 'NM_001005240 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// NM_001004195 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// NM_001005484 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// ENST00000318050 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// ENST00000335137 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// ENST00000326183 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// BC136848 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// BC136907 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// ENST00000442916 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099', 'ENST00000388975 // SEPT14 // septin 14 // 7p11.2 // 346288 /// BC118988 // NCRNA00266 // non-protein coding RNA 266 // --- // 140849 /// AL137655 // LOC100134822 // similar to hCG1739109 // --- // 100134822', 'NM_001005277 // OR4F16 // olfactory receptor, family 4, subfamily F, member 16 // 1p36.33 // 81399 /// NM_001005221 // OR4F29 // olfactory receptor, family 4, subfamily F, member 29 // 1p36.33 // 729759 /// NM_001005224 // OR4F3 // olfactory receptor, family 4, subfamily F, member 3 // 5q35.3 // 26683 /// NM_001005504 // OR4F21 // olfactory receptor, family 4, subfamily F, member 21 // 8p23.3 // 441308 /// ENST00000320901 // OR4F21 // olfactory receptor, family 4, subfamily F, member 21 // 8p23.3 // 441308 /// BC137547 // OR4F3 // olfactory receptor, family 4, subfamily F, member 3 // 5q35.3 // 26683 /// BC137547 // OR4F16 // olfactory receptor, family 4, subfamily F, member 16 // 1p36.33 // 81399 /// BC137547 // OR4F29 // olfactory receptor, family 4, subfamily F, member 29 // 1p36.33 // 729759'], 'mrna_assignment': ['---', 'ENST00000328113 // ENSEMBL // cdna:pseudogene chromosome:GRCh37:15:102467008:102467910:-1 gene:ENSG00000183909 // chr1 // 100 // 100 // 31 // 31 // 0 /// ENST00000318181 // ENSEMBL // cdna:pseudogene chromosome:GRCh37:19:104601:105256:1 gene:ENSG00000176705 // chr1 // 100 // 100 // 31 // 31 // 0 /// ENST00000492842 // ENSEMBL // cdna:pseudogene chromosome:GRCh37:1:62948:63887:1 gene:ENSG00000240361 // chr1 // 100 // 100 // 31 // 31 // 0', 'NM_001005240 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 17 (OR4F17), mRNA. // chr1 // 100 // 100 // 24 // 24 // 0 /// NM_001004195 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 4 (OR4F4), mRNA. // chr1 // 100 // 100 // 24 // 24 // 0 /// NM_001005484 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 5 (OR4F5), mRNA. // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000318050 // ENSEMBL // Olfactory receptor 4F17 gene:ENSG00000176695 // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000335137 // ENSEMBL // Olfactory receptor 4F4 gene:ENSG00000186092 // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000326183 // ENSEMBL // Olfactory receptor 4F5 gene:ENSG00000177693 // chr1 // 100 // 100 // 24 // 24 // 0 /// BC136848 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 17, mRNA (cDNA clone MGC:168462 IMAGE:9020839), complete cds. // chr1 // 100 // 100 // 24 // 24 // 0 /// BC136907 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 4, mRNA (cDNA clone MGC:168521 IMAGE:9020898), complete cds. // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000442916 // ENSEMBL // OR4F4 (Fragment) gene:ENSG00000176695 // chr1 // 100 // 88 // 21 // 21 // 0', 'ENST00000388975 // ENSEMBL // Septin-14 gene:ENSG00000154997 // chr1 // 50 // 100 // 3 // 6 // 0 /// BC118988 // GenBank // Homo sapiens chromosome 20 open reading frame 69, mRNA (cDNA clone MGC:141807 IMAGE:40035995), complete cds. // chr1 // 100 // 100 // 6 // 6 // 0 /// AL137655 // GenBank // Homo sapiens mRNA; cDNA DKFZp434B2016 (from clone DKFZp434B2016). // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000428915 // ENSEMBL // cdna:known chromosome:GRCh37:10:38742109:38755311:1 gene:ENSG00000203496 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000455207 // ENSEMBL // cdna:known chromosome:GRCh37:1:334129:446155:1 gene:ENSG00000224813 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000455464 // ENSEMBL // cdna:known chromosome:GRCh37:1:334140:342806:1 gene:ENSG00000224813 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000440200 // ENSEMBL // cdna:known chromosome:GRCh37:1:536816:655580:-1 gene:ENSG00000230021 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000279067 // ENSEMBL // cdna:known chromosome:GRCh37:20:62921738:62934912:1 gene:ENSG00000149656 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000499986 // ENSEMBL // cdna:known chromosome:GRCh37:5:180717576:180761371:1 gene:ENSG00000248628 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000436899 // ENSEMBL // cdna:known chromosome:GRCh37:6:131910:144885:-1 gene:ENSG00000170590 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000432557 // ENSEMBL // cdna:known chromosome:GRCh37:8:132324:150572:-1 gene:ENSG00000250210 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000523795 // ENSEMBL // cdna:known chromosome:GRCh37:8:141690:150563:-1 gene:ENSG00000250210 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000490482 // ENSEMBL // cdna:known chromosome:GRCh37:8:149942:163324:-1 gene:ENSG00000223508 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000307499 // ENSEMBL // cdna:known supercontig::GL000227.1:57780:70752:-1 gene:ENSG00000229450 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000441245 // ENSEMBL // cdna:known chromosome:GRCh37:1:637316:655530:-1 gene:ENSG00000230021 // chr1 // 100 // 67 // 4 // 4 // 0 /// ENST00000425473 // ENSEMBL // cdna:known chromosome:GRCh37:20:62926294:62944485:1 gene:ENSG00000149656 // chr1 // 100 // 67 // 4 // 4 // 0 /// ENST00000471248 // ENSEMBL // cdna:known chromosome:GRCh37:1:110953:129173:-1 gene:ENSG00000238009 // chr1 // 75 // 67 // 3 // 4 // 0', 'NM_001005277 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 16 (OR4F16), mRNA. // chr1 // 100 // 100 // 36 // 36 // 0 /// NM_001005221 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 29 (OR4F29), mRNA. // chr1 // 100 // 100 // 36 // 36 // 0 /// NM_001005224 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 3 (OR4F3), mRNA. // chr1 // 100 // 100 // 36 // 36 // 0 /// NM_001005504 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 21 (OR4F21), mRNA. // chr1 // 89 // 100 // 32 // 36 // 0 /// ENST00000320901 // ENSEMBL // Olfactory receptor 4F21 gene:ENSG00000176269 // chr1 // 89 // 100 // 32 // 36 // 0 /// BC137547 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 3, mRNA (cDNA clone MGC:169170 IMAGE:9021547), complete cds. // chr1 // 100 // 100 // 36 // 36 // 0 /// ENST00000426406 // ENSEMBL // cdna:known chromosome:GRCh37:1:367640:368634:1 gene:ENSG00000235249 // chr1 // 100 // 100 // 36 // 36 // 0 /// ENST00000332831 // ENSEMBL // cdna:known chromosome:GRCh37:1:621096:622034:-1 gene:ENSG00000185097 // chr1 // 100 // 100 // 36 // 36 // 0 /// ENST00000456475 // ENSEMBL // cdna:known chromosome:GRCh37:5:180794269:180795263:1 gene:ENSG00000230178 // chr1 // 100 // 100 // 36 // 36 // 0 /// ENST00000521196 // ENSEMBL // cdna:known chromosome:GRCh37:11:86612:87605:-1 gene:ENSG00000224777 // chr1 // 78 // 100 // 28 // 36 // 0'], 'category': ['---', 'main', 'main', 'main', 'main']}\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": "75abfd6c",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "47d9ec2c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:15:19.377329Z",
     "iopub.status.busy": "2025-03-25T08:15:19.377211Z",
     "iopub.status.idle": "2025-03-25T08:17:28.832767Z",
     "shell.execute_reply": "2025-03-25T08:17:28.832134Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data shape: (33297, 142)\n",
      "First few probe IDs: ['7892501', '7892502', '7892503', '7892504', '7892505']\n",
      "Creating gene mapping from probe IDs to gene symbols...\n",
      "\n",
      "Probe ID overlap: 33297 out of 33297 expression probes\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Filtered mapping dataframe contains 4761471 rows\n",
      "\n",
      "Extracting gene symbols from gene assignments...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Sample of extracted gene symbols (first 5 rows):\n",
      "        ID                                        Gene\n",
      "0  7896736                                          []\n",
      "1  7896738                                          []\n",
      "2  7896740  [OR4F17, OR4F4, OR4F5, BC136848, BC136907]\n",
      "3  7896742    [SEPT14, BC118988, NCRNA00266, AL137655]\n",
      "4  7896744   [OR4F16, OR4F29, OR4F3, OR4F21, BC137547]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Number of probes with gene mappings: 22011 out of 4761471 total probes\n",
      "\n",
      "Applying gene mapping to convert probe data to gene expression data...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Mapped gene expression data shape: (0, 142)\n",
      "\n",
      "WARNING: Still no mapped genes. Attempting direct mapping of most common genes...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Created direct mapping with 447055 probe-to-gene mappings\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Direct mapped gene expression data shape: (55006, 142)\n",
      "\n",
      "Normalizing gene symbols...\n",
      "Final gene data shape after normalization: (19854, 142)\n",
      "\n",
      "Final gene expression data shape: (19854, 142)\n",
      "First 10 gene symbols: ['A1BG', 'A1CF', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS', 'AACS', 'AADAC']\n",
      "\n",
      "Saving gene expression data to CSV file...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to ../../output/preprocess/Chronic_Fatigue_Syndrome/gene_data/GSE67311.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Ensure we have the gene expression data loaded properly\n",
    "gene_data = get_genetic_data(matrix_file)\n",
    "print(f\"Gene expression data shape: {gene_data.shape}\")\n",
    "print(f\"First few probe IDs: {list(gene_data.index[:5])}\")\n",
    "\n",
    "# 2. Examine the gene annotation structure and prepare the mapping\n",
    "print(\"Creating gene mapping from probe IDs to gene symbols...\")\n",
    "\n",
    "# Check the relationship between gene expression probe IDs and annotation IDs\n",
    "gene_ids = set(gene_data.index.astype(str))\n",
    "annotation_ids = set(gene_annotation['ID'].astype(str))\n",
    "overlap = gene_ids.intersection(annotation_ids)\n",
    "print(f\"\\nProbe ID overlap: {len(overlap)} out of {len(gene_ids)} expression probes\")\n",
    "\n",
    "# Create a mapping dataframe, focusing on IDs that appear in our gene expression data\n",
    "mapping_df = gene_annotation[gene_annotation['ID'].astype(str).isin(gene_ids)][['ID', 'gene_assignment']].copy()\n",
    "print(f\"Filtered mapping dataframe contains {len(mapping_df)} rows\")\n",
    "\n",
    "# Extract gene symbols from gene assignments\n",
    "print(\"\\nExtracting gene symbols from gene assignments...\")\n",
    "mapping_df['Gene'] = mapping_df['gene_assignment'].apply(extract_human_gene_symbols)\n",
    "\n",
    "# Print a sample of the extracted gene symbols\n",
    "print(\"\\nSample of extracted gene symbols (first 5 rows):\")\n",
    "print(mapping_df[['ID', 'Gene']].head(5))\n",
    "\n",
    "# Count how many mapped probes have gene assignments\n",
    "mappable_probes = mapping_df[mapping_df['Gene'].apply(len) > 0].shape[0]\n",
    "print(f\"\\nNumber of probes with gene mappings: {mappable_probes} out of {mapping_df.shape[0]} total probes\")\n",
    "\n",
    "# Check if we have any valid mappings\n",
    "if mappable_probes == 0:\n",
    "    print(\"\\nWARNING: No valid gene mappings found. Using a fallback approach...\")\n",
    "    # Fallback: Try exact string matching for probe IDs\n",
    "    mapping_df = gene_annotation[['ID', 'gene_assignment']].copy()\n",
    "    mapping_df['ID'] = mapping_df['ID'].astype(str)\n",
    "    mapping_df['Gene'] = mapping_df['gene_assignment'].apply(extract_human_gene_symbols)\n",
    "    # Only keep rows with extracted gene symbols\n",
    "    mapping_df = mapping_df[mapping_df['Gene'].apply(len) > 0]\n",
    "    print(f\"Fallback mapping contains {len(mapping_df)} rows with gene symbols\")\n",
    "\n",
    "# Apply gene mapping to get gene expression data\n",
    "print(\"\\nApplying gene mapping to convert probe data to gene expression data...\")\n",
    "gene_data_mapped = apply_gene_mapping(gene_data, mapping_df[['ID', 'Gene']])\n",
    "print(f\"Mapped gene expression data shape: {gene_data_mapped.shape}\")\n",
    "\n",
    "# If we still don't have any genes, try a more direct approach\n",
    "if gene_data_mapped.shape[0] == 0:\n",
    "    print(\"\\nWARNING: Still no mapped genes. Attempting direct mapping of most common genes...\")\n",
    "    # Direct mapping approach\n",
    "    import re\n",
    "    \n",
    "    # We'll create a simple mapping from each probe to potential genes\n",
    "    direct_mappings = {}\n",
    "    for idx, row in gene_annotation.iterrows():\n",
    "        probe_id = str(row['ID'])\n",
    "        gene_text = str(row['gene_assignment'])\n",
    "        # Extract gene symbols - common pattern: SYMBOL // DESCRIPTION\n",
    "        matches = re.findall(r'(\\w+) // ', gene_text)\n",
    "        if matches:\n",
    "            direct_mappings[probe_id] = matches\n",
    "    \n",
    "    # Create a new mapping dataframe\n",
    "    direct_map_records = []\n",
    "    for probe_id, genes in direct_mappings.items():\n",
    "        for gene in genes:\n",
    "            if gene not in ['NM', 'BC', 'ENST', 'NC'] and len(gene) > 1:  # Filter out common prefixes\n",
    "                direct_map_records.append({'ID': probe_id, 'Gene': gene})\n",
    "    \n",
    "    if direct_map_records:\n",
    "        direct_mapping_df = pd.DataFrame(direct_map_records)\n",
    "        print(f\"Created direct mapping with {len(direct_mapping_df)} probe-to-gene mappings\")\n",
    "        gene_data_mapped = apply_gene_mapping(gene_data, direct_mapping_df)\n",
    "        print(f\"Direct mapped gene expression data shape: {gene_data_mapped.shape}\")\n",
    "\n",
    "# Normalize gene symbols using standard function or keep as is if still empty\n",
    "if gene_data_mapped.shape[0] > 0:\n",
    "    print(\"\\nNormalizing gene symbols...\")\n",
    "    gene_data = normalize_gene_symbols_in_index(gene_data_mapped)\n",
    "    print(f\"Final gene data shape after normalization: {gene_data.shape}\")\n",
    "else:\n",
    "    print(\"\\nWARNING: Could not map any genes. Creating an empty gene expression dataset.\")\n",
    "    gene_data = pd.DataFrame(columns=gene_data.columns)\n",
    "\n",
    "# Print information about the resulting gene expression data\n",
    "print(f\"\\nFinal gene expression data shape: {gene_data.shape}\")\n",
    "if gene_data.shape[0] > 0:\n",
    "    print(f\"First 10 gene symbols: {list(gene_data.index[:10])}\")\n",
    "else:\n",
    "    print(\"WARNING: No genes were found in the final dataset!\")\n",
    "\n",
    "# Save the gene expression data to a CSV file\n",
    "print(\"\\nSaving gene expression data to CSV file...\")\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Gene expression data saved to {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b5b5beec",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "a66e7661",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:17:28.834447Z",
     "iopub.status.busy": "2025-03-25T08:17:28.834322Z",
     "iopub.status.idle": "2025-03-25T08:17:43.826393Z",
     "shell.execute_reply": "2025-03-25T08:17:43.825726Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Chronic_Fatigue_Syndrome/gene_data/GSE67311.csv\n",
      "Clinical data saved to ../../output/preprocess/Chronic_Fatigue_Syndrome/clinical_data/GSE67311.csv\n",
      "Linked data shape: (142, 19855)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "For the feature 'Chronic_Fatigue_Syndrome', the least common label is '1.0' with 10 occurrences. This represents 7.52% of the dataset.\n",
      "The distribution of the feature 'Chronic_Fatigue_Syndrome' in this dataset is fine.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Chronic_Fatigue_Syndrome/GSE67311.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.\n",
    "normalized_gene_data = normalize_gene_symbols_in_index(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",
    "# Create clinical features directly from clinical_data using the conversion functions defined earlier\n",
    "clinical_features_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",
    "# Save the clinical data\n",
    "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "clinical_features_df.to_csv(out_clinical_data_file)\n",
    "print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "\n",
    "# Now link the clinical and genetic data\n",
    "linked_data = geo_link_clinical_genetic_data(clinical_features_df, normalized_gene_data)\n",
    "print(\"Linked data shape:\", linked_data.shape)\n",
    "\n",
    "# Handle missing values in the linked data\n",
    "linked_data = handle_missing_values(linked_data, trait)\n",
    "\n",
    "# 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.\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=\"Dataset contains gene expression from monocytes of rheumatoid arthritis patients, with osteoporosis status included in comorbidity information.\"\n",
    ")\n",
    "\n",
    "# 6. If the linked data is usable, save it as a CSV file to 'out_data_file'.\n",
    "if is_usable:\n",
    "    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "    unbiased_linked_data.to_csv(out_data_file)\n",
    "    print(f\"Linked data saved to {out_data_file}\")\n",
    "else:\n",
    "    print(\"Data was determined to be unusable and was 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
}