File size: 28,774 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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "1aa794af",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:15:08.917302Z",
     "iopub.status.busy": "2025-03-25T08:15:08.916769Z",
     "iopub.status.idle": "2025-03-25T08:15:09.083153Z",
     "shell.execute_reply": "2025-03-25T08:15:09.082842Z"
    }
   },
   "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 = \"GSE251792\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Chronic_Fatigue_Syndrome\"\n",
    "in_cohort_dir = \"../../input/GEO/Chronic_Fatigue_Syndrome/GSE251792\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Chronic_Fatigue_Syndrome/GSE251792.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Chronic_Fatigue_Syndrome/gene_data/GSE251792.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Chronic_Fatigue_Syndrome/clinical_data/GSE251792.csv\"\n",
    "json_path = \"../../output/preprocess/Chronic_Fatigue_Syndrome/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "35be2c95",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "bf7c698a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:15:09.084546Z",
     "iopub.status.busy": "2025-03-25T08:15:09.084400Z",
     "iopub.status.idle": "2025-03-25T08:15:09.108513Z",
     "shell.execute_reply": "2025-03-25T08:15:09.108250Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Deep phenotyping of Post-infectious Myalgic Encephalomyelitis/Chronic Fatigue Syndrome\"\n",
      "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n",
      "!Series_overall_design\t\"Refer to individual Series\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['Sex: Female', 'Sex: Male'], 1: ['age: 61', 'age: 37', 'age: 56', 'age: 24', 'age: 58', 'age: 43', 'age: 26', 'age: 40', 'age: 47', 'age: 22', 'age: 54', 'age: 44', 'age: 20', 'age: 23', 'age: 33', 'age: 25', 'age: 51', 'age: 48', 'age: 36', 'age: 38', 'age: 60', 'age: 50', 'age: 49', 'age: 55', 'age: 57'], 2: ['group: Patient', 'group: 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": "165a6ec5",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "26d1b061",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:15:09.109599Z",
     "iopub.status.busy": "2025-03-25T08:15:09.109491Z",
     "iopub.status.idle": "2025-03-25T08:15:09.122483Z",
     "shell.execute_reply": "2025-03-25T08:15:09.122222Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical features preview: {'GSM7988184': [1.0, 61.0, 0.0], 'GSM7988185': [0.0, 37.0, 1.0], 'GSM7988186': [0.0, 56.0, 0.0], 'GSM7988187': [0.0, 56.0, 0.0], 'GSM7988188': [1.0, 24.0, 0.0], 'GSM7988189': [1.0, 58.0, 1.0], 'GSM7988190': [1.0, 43.0, 1.0], 'GSM7988191': [1.0, 26.0, 0.0], 'GSM7988192': [0.0, 40.0, 1.0], 'GSM7988193': [1.0, 47.0, 1.0], 'GSM7988194': [0.0, 22.0, 0.0], 'GSM7988195': [1.0, 54.0, 0.0], 'GSM7988196': [0.0, 58.0, 1.0], 'GSM7988197': [1.0, 44.0, 0.0], 'GSM7988198': [1.0, 20.0, 0.0], 'GSM7988199': [0.0, 26.0, 1.0], 'GSM7988200': [1.0, 23.0, 0.0], 'GSM7988201': [1.0, 33.0, 1.0], 'GSM7988202': [0.0, 54.0, 0.0], 'GSM7988203': [1.0, 25.0, 0.0], 'GSM7988204': [0.0, 58.0, 1.0], 'GSM7988205': [1.0, 37.0, 1.0], 'GSM7988206': [0.0, 23.0, 1.0], 'GSM7988207': [1.0, 22.0, 1.0], 'GSM7988208': [1.0, 51.0, 0.0], 'GSM7988209': [1.0, 48.0, 1.0], 'GSM7988210': [0.0, 36.0, 1.0], 'GSM7988211': [0.0, 56.0, 0.0], 'GSM7988212': [1.0, 38.0, 0.0], 'GSM7988213': [1.0, 60.0, 1.0], 'GSM7988214': [0.0, 37.0, 0.0], 'GSM7988215': [0.0, 25.0, 0.0], 'GSM7988216': [0.0, 44.0, 1.0], 'GSM7988217': [1.0, 61.0, 0.0], 'GSM7988218': [1.0, 50.0, 1.0], 'GSM7988219': [0.0, 60.0, 0.0], 'GSM7988220': [0.0, 47.0, 1.0], 'GSM7988221': [0.0, 49.0, 0.0], 'GSM7988222': [1.0, 50.0, 0.0], 'GSM7988223': [0.0, 55.0, 0.0], 'GSM7988224': [0.0, 60.0, 1.0], 'GSM7988225': [0.0, 57.0, 0.0], 'GSM8032049': [0.0, 44.0, 1.0], 'GSM8032050': [0.0, 60.0, 0.0], 'GSM8032051': [0.0, 37.0, 0.0], 'GSM8032052': [0.0, 58.0, 1.0], 'GSM8032053': [0.0, 60.0, 1.0], 'GSM8032054': [0.0, 56.0, 0.0], 'GSM8032055': [1.0, 24.0, 0.0], 'GSM8032056': [1.0, 50.0, 1.0], 'GSM8032057': [1.0, 51.0, 0.0], 'GSM8032058': [0.0, 55.0, 0.0], 'GSM8032059': [1.0, 48.0, 1.0], 'GSM8032060': [0.0, 26.0, 1.0], 'GSM8032061': [0.0, 22.0, 0.0], 'GSM8032062': [1.0, 38.0, 0.0], 'GSM8032063': [1.0, 50.0, 0.0], 'GSM8032064': [0.0, 56.0, 0.0], 'GSM8032065': [1.0, 33.0, 1.0], 'GSM8032066': [1.0, 47.0, 1.0], 'GSM8032067': [1.0, 22.0, 1.0], 'GSM8032068': [1.0, 23.0, 0.0], 'GSM8032069': [0.0, 23.0, 1.0], 'GSM8032070': [0.0, 58.0, 1.0], 'GSM8032071': [1.0, 54.0, 0.0], 'GSM8032072': [0.0, 37.0, 1.0], 'GSM8032073': [0.0, 36.0, 1.0], 'GSM8032074': [1.0, 61.0, 0.0], 'GSM8032075': [0.0, 49.0, 0.0], 'GSM8032076': [0.0, 57.0, 0.0], 'GSM8032077': [1.0, 60.0, 1.0], 'GSM8032078': [1.0, 25.0, 0.0], 'GSM8032079': [0.0, 47.0, 1.0], 'GSM8032080': [1.0, 44.0, 0.0], 'GSM8032081': [0.0, 56.0, 0.0], 'GSM8032082': [0.0, 54.0, 0.0], 'GSM8032083': [1.0, 58.0, 1.0], 'GSM8032084': [1.0, 20.0, 0.0], 'GSM8032085': [1.0, 37.0, 1.0], 'GSM8032086': [1.0, 26.0, 0.0], 'GSM8032087': [0.0, 25.0, 0.0], 'GSM8032088': [1.0, 43.0, 1.0], 'GSM8032089': [0.0, 40.0, 1.0], 'GSM8032090': [1.0, 61.0, 0.0]}\n",
      "Clinical features saved to ../../output/preprocess/Chronic_Fatigue_Syndrome/clinical_data/GSE251792.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Determine gene expression data availability\n",
    "# Based on the series title and summary, this appears to be a SuperSeries on ME/CFS\n",
    "# SuperSeries typically combine multiple datasets, but we need more information to determine\n",
    "# if gene expression data is included. Since we don't have explicit confirmation,\n",
    "# let's conservatively assume gene expression data is available\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Determine variable availability and create conversion functions\n",
    "\n",
    "# 2.1 Identify rows containing trait, age, and gender data\n",
    "trait_row = 2  # 'group: Patient', 'group: Control' indicates trait information\n",
    "age_row = 1    # Contains age information\n",
    "gender_row = 0  # Contains sex information\n",
    "\n",
    "# 2.2 Create conversion functions for each variable\n",
    "\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait values to binary format (1 for Patient, 0 for Control)\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if present\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary\n",
    "    if value.lower() == \"patient\":\n",
    "        return 1\n",
    "    elif value.lower() == \"control\":\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age values to continuous numeric format\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if present\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Convert to integer\n",
    "    try:\n",
    "        return int(value)\n",
    "    except (ValueError, TypeError):\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender values to binary format (0 for Female, 1 for Male)\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if present\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary\n",
    "    if value.lower() == \"female\":\n",
    "        return 0\n",
    "    elif value.lower() == \"male\":\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save metadata for initial filtering\n",
    "# Trait data is available since trait_row is not None\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Conduct initial filtering and save cohort 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. Extract clinical features if trait data is available\n",
    "if trait_row is not None:\n",
    "    # Create directory for clinical data if it doesn't exist\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    \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 extracted features\n",
    "    preview = preview_df(clinical_features)\n",
    "    print(\"Clinical features preview:\", preview)\n",
    "    \n",
    "    # Save clinical features to CSV\n",
    "    clinical_features.to_csv(out_clinical_data_file)\n",
    "    print(f\"Clinical features saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "75695614",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "2fcd79ca",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:15:09.123543Z",
     "iopub.status.busy": "2025-03-25T08:15:09.123440Z",
     "iopub.status.idle": "2025-03-25T08:15:09.142653Z",
     "shell.execute_reply": "2025-03-25T08:15:09.142369Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found data marker at line 68\n",
      "Header line: \"ID_REF\"\t\"GSM7988184\"\t\"GSM7988185\"\t\"GSM7988186\"\t\"GSM7988187\"\t\"GSM7988188\"\t\"GSM7988189\"\t\"GSM7988190\"\t\"GSM7988191\"\t\"GSM7988192\"\t\"GSM7988193\"\t\"GSM7988194\"\t\"GSM7988195\"\t\"GSM7988196\"\t\"GSM7988197\"\t\"GSM7988198\"\t\"GSM7988199\"\t\"GSM7988200\"\t\"GSM7988201\"\t\"GSM7988202\"\t\"GSM7988203\"\t\"GSM7988204\"\t\"GSM7988205\"\t\"GSM7988206\"\t\"GSM7988207\"\t\"GSM7988208\"\t\"GSM7988209\"\t\"GSM7988210\"\t\"GSM7988211\"\t\"GSM7988212\"\t\"GSM7988213\"\t\"GSM7988214\"\t\"GSM7988215\"\t\"GSM7988216\"\t\"GSM7988217\"\t\"GSM7988218\"\t\"GSM7988219\"\t\"GSM7988220\"\t\"GSM7988221\"\t\"GSM7988222\"\t\"GSM7988223\"\t\"GSM7988224\"\t\"GSM7988225\"\t\"GSM8032049\"\t\"GSM8032050\"\t\"GSM8032051\"\t\"GSM8032052\"\t\"GSM8032053\"\t\"GSM8032054\"\t\"GSM8032055\"\t\"GSM8032056\"\t\"GSM8032057\"\t\"GSM8032058\"\t\"GSM8032059\"\t\"GSM8032060\"\t\"GSM8032061\"\t\"GSM8032062\"\t\"GSM8032063\"\t\"GSM8032064\"\t\"GSM8032065\"\t\"GSM8032066\"\t\"GSM8032067\"\t\"GSM8032068\"\t\"GSM8032069\"\t\"GSM8032070\"\t\"GSM8032071\"\t\"GSM8032072\"\t\"GSM8032073\"\t\"GSM8032074\"\t\"GSM8032075\"\t\"GSM8032076\"\t\"GSM8032077\"\t\"GSM8032078\"\t\"GSM8032079\"\t\"GSM8032080\"\t\"GSM8032081\"\t\"GSM8032082\"\t\"GSM8032083\"\t\"GSM8032084\"\t\"GSM8032085\"\t\"GSM8032086\"\t\"GSM8032087\"\t\"GSM8032088\"\t\"GSM8032089\"\t\"GSM8032090\"\n",
      "First data line: \"HCE000104\"\t6204.5\t6348.3\t6352.6\t6650.1\t6049.4\t6542.7\t6282.7\t6324.4\t6523.2\t6390.9\t6396.4\t6394.2\t6321.7\t6340.9\t6392.3\t6458.5\t6379\t6455.9\t6496\t6193.5\t6263.6\t6107\t6226.6\t6341\t6144.5\t6045.2\t6145.2\t6200.9\t6332.6\t6306.7\t6102.2\t6271.9\t6211.1\t6399.8\t6337.4\t6278.7\t6348.7\t6244.7\t6289.2\t6221.3\t6328.5\t6214.3\t4641.3\t4462.3\t4639.6\t4495.9\t4615.2\t4550.7\t4454.7\t4583.3\t4811.3\t4630.6\t4479.8\t4629.2\t4602.5\t4594.4\t4521.6\t4553.9\t4725.2\t4622.7\t4717.2\t4612.9\t4555.6\t4580.9\t4626.8\t4729.9\t4686.6\t4628.4\t4625\t4542.9\t4620.7\t4518.2\t4545.3\t4588\t4548.8\t4594.1\t4651.6\t4686.7\t4585.1\t4637.7\t4637.8\t4809.7\t4706.2\t4617.6\n",
      "Index(['HCE000104', 'HCE000342', 'HCE000414', 'HCE000483', 'HCE001796',\n",
      "       'HCE003167', 'HCE003183', 'HCE003300', 'HCE004152', 'HCE004331',\n",
      "       'HCE004333', 'HCE004359', 'SL000001', 'SL000002', 'SL000003',\n",
      "       'SL000004', 'SL000006', 'SL000007', 'SL000009', 'SL000011'],\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": "bddd32cd",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "96d631fa",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:15:09.143701Z",
     "iopub.status.busy": "2025-03-25T08:15:09.143597Z",
     "iopub.status.idle": "2025-03-25T08:15:09.145268Z",
     "shell.execute_reply": "2025-03-25T08:15:09.144995Z"
    }
   },
   "outputs": [],
   "source": [
    "# Reviewing the gene identifiers in the expression data\n",
    "# The identifiers with prefixes 'HCE' and 'SL' appear to be probe IDs \n",
    "# rather than standard human gene symbols (like BRCA1, TP53, etc.)\n",
    "# These will need to be mapped to standard gene symbols for analysis\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f5d721d9",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "2954d3b3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:15:09.146279Z",
     "iopub.status.busy": "2025-03-25T08:15:09.146177Z",
     "iopub.status.idle": "2025-03-25T08:15:09.255801Z",
     "shell.execute_reply": "2025-03-25T08:15:09.255427Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['SL019100', 'SL007136', 'SL001731', 'SL019096', 'SL005173'], 'TargetFullName': ['E3 ubiquitin-protein ligase CHIP', 'CCAAT/enhancer-binding protein beta', 'Gamma-enolase', 'E3 SUMO-protein ligase PIAS4', 'Interleukin-10 receptor subunit alpha'], 'Target': ['CHIP', 'CEBPB', 'NSE', 'PIAS4', 'IL-10 Ra'], 'PT_LIST': ['Q9UNE7', 'P17676', 'P09104', 'Q8N2W9', 'Q13651'], 'Entrez_GENE_ID_LIST': ['10273', '1051', '2026', '51588', '3587'], 'EntrezGeneSymbol': ['STUB1', 'CEBPB', 'ENO2', 'PIAS4', 'IL10RA'], 'SPOT_ID': [nan, nan, nan, nan, nan]}\n"
     ]
    }
   ],
   "source": [
    "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "\n",
    "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
    "print(\"Gene annotation preview:\")\n",
    "print(preview_df(gene_annotation))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e7445d25",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "20cc6151",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:15:09.257194Z",
     "iopub.status.busy": "2025-03-25T08:15:09.256956Z",
     "iopub.status.idle": "2025-03-25T08:15:09.339298Z",
     "shell.execute_reply": "2025-03-25T08:15:09.338862Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data after mapping:\n",
      "Number of genes: 1315\n",
      "Number of samples: 84\n",
      "First few genes:\n",
      "      GSM7988184  GSM7988185  GSM7988186  GSM7988187  GSM7988188  GSM7988189  \\\n",
      "Gene                                                                           \n",
      "A2M       2645.2      1851.6      2049.7      3365.0      1905.3      2880.7   \n",
      "ABL1        26.8        29.9        33.8        65.0        23.7        37.2   \n",
      "ABL2        56.7        85.5        73.2        55.0        89.3        57.4   \n",
      "ACAN       528.8       443.1       268.1       357.7       213.8       446.2   \n",
      "ACE2        21.3        17.2        25.9        14.2        19.7        18.7   \n",
      "\n",
      "      GSM7988190  GSM7988191  GSM7988192  GSM7988193  ...  GSM8032081  \\\n",
      "Gene                                                  ...               \n",
      "A2M       2093.6      2079.1      2820.9      2171.8  ...     25789.1   \n",
      "ABL1        33.3        31.1        21.1        26.7  ...       416.3   \n",
      "ABL2        62.0        72.6        60.8        59.3  ...       808.3   \n",
      "ACAN       350.1       299.2       464.3       666.0  ...      1162.4   \n",
      "ACE2        27.3        14.2        17.2        16.0  ...       579.3   \n",
      "\n",
      "      GSM8032082  GSM8032083  GSM8032084  GSM8032085  GSM8032086  GSM8032087  \\\n",
      "Gene                                                                           \n",
      "A2M      25975.6     27122.5     31820.3     38772.8     25573.6     31443.3   \n",
      "ABL1       427.7       462.9       403.5       394.9       417.0       416.4   \n",
      "ABL2       852.8       770.6      1067.4       944.6       819.9       749.9   \n",
      "ACAN      1199.8      1517.0      1597.4      1118.9      1349.4      1096.8   \n",
      "ACE2       673.4       587.8       552.5       550.8       583.5       625.1   \n",
      "\n",
      "      GSM8032088  GSM8032089  GSM8032090  \n",
      "Gene                                      \n",
      "A2M      21939.5     25984.0     56532.3  \n",
      "ABL1       398.3       419.9       394.3  \n",
      "ABL2       852.5       754.7       513.2  \n",
      "ACAN      1325.4      1192.3      1313.5  \n",
      "ACE2       545.1       556.1       648.6  \n",
      "\n",
      "[5 rows x 84 columns]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to ../../output/preprocess/Chronic_Fatigue_Syndrome/gene_data/GSE251792.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Determine which columns in the annotation contain probe IDs and gene symbols\n",
    "id_column = 'ID'  # The column in gene_annotation that corresponds to the probe IDs in gene_data\n",
    "gene_symbol_column = 'EntrezGeneSymbol'  # The column containing gene symbols\n",
    "\n",
    "# 2. Create a mapping dataframe between probe IDs and gene symbols\n",
    "gene_mapping = get_gene_mapping(gene_annotation, id_column, gene_symbol_column)\n",
    "\n",
    "# 3. Apply the mapping to convert probe-level measurements to gene-level expression\n",
    "# This handles many-to-many mappings by dividing expression values equally among genes\n",
    "# for each probe, then summing all contributions for each gene\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "\n",
    "# Preview the gene expression data after mapping\n",
    "print(\"Gene expression data after mapping:\")\n",
    "print(f\"Number of genes: {len(gene_data)}\")\n",
    "print(f\"Number of samples: {len(gene_data.columns)}\")\n",
    "print(\"First few genes:\")\n",
    "print(gene_data.head())\n",
    "\n",
    "# Save the processed 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\"Gene expression data saved to {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "98faf153",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "ee4b8c65",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:15:09.340629Z",
     "iopub.status.busy": "2025-03-25T08:15:09.340512Z",
     "iopub.status.idle": "2025-03-25T08:15:09.798316Z",
     "shell.execute_reply": "2025-03-25T08:15:09.797685Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Chronic_Fatigue_Syndrome/gene_data/GSE251792.csv\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical data saved to ../../output/preprocess/Chronic_Fatigue_Syndrome/clinical_data/GSE251792.csv\n",
      "Linked data shape: (84, 1305)\n",
      "For the feature 'Chronic_Fatigue_Syndrome', the least common label is '1.0' with 42 occurrences. This represents 50.00% of the dataset.\n",
      "The distribution of the feature 'Chronic_Fatigue_Syndrome' in this dataset is fine.\n",
      "\n",
      "Quartiles for 'Age':\n",
      "  25%: 33.0\n",
      "  50% (Median): 47.0\n",
      "  75%: 56.0\n",
      "Min: 20.0\n",
      "Max: 61.0\n",
      "The distribution of the feature 'Age' in this dataset is fine.\n",
      "\n",
      "For the feature 'Gender', the least common label is '1.0' with 38 occurrences. This represents 45.24% of the dataset.\n",
      "The distribution of the feature 'Gender' in this dataset is fine.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "A new JSON file was created at: ../../output/preprocess/Chronic_Fatigue_Syndrome/cohort_info.json\n",
      "Linked data saved to ../../output/preprocess/Chronic_Fatigue_Syndrome/GSE251792.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
}