File size: 48,401 Bytes
92d2f89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "3af99f62",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:50:57.705127Z",
     "iopub.status.busy": "2025-03-25T06:50:57.704928Z",
     "iopub.status.idle": "2025-03-25T06:50:57.867243Z",
     "shell.execute_reply": "2025-03-25T06:50:57.866864Z"
    }
   },
   "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 = \"Autism_spectrum_disorder_(ASD)\"\n",
    "cohort = \"GSE111175\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Autism_spectrum_disorder_(ASD)\"\n",
    "in_cohort_dir = \"../../input/GEO/Autism_spectrum_disorder_(ASD)/GSE111175\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Autism_spectrum_disorder_(ASD)/GSE111175.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Autism_spectrum_disorder_(ASD)/gene_data/GSE111175.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Autism_spectrum_disorder_(ASD)/clinical_data/GSE111175.csv\"\n",
    "json_path = \"../../output/preprocess/Autism_spectrum_disorder_(ASD)/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ba25fb99",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "edc0e834",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:50:57.868690Z",
     "iopub.status.busy": "2025-03-25T06:50:57.868542Z",
     "iopub.status.idle": "2025-03-25T06:50:58.247453Z",
     "shell.execute_reply": "2025-03-25T06:50:58.247094Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Perturbations of PI3K/AKT, RAS/ERK, WNT/B-catenin networks in leukocytes are linked to ASD genetics and fetal origins of autism\"\n",
      "!Series_summary\t\"Hundreds of genes are implicated in autism spectrum disorder (ASD) but the mechanisms through which they contribute to ASD pathophysiology remain elusive. Here, we analyzed leukocyte transcriptomics from 1-4 year-old male toddlers with ASD or typical development from the general population. We discovered a perturbed gene network that includes genes highly expressed during fetal brain development and which is dysregulated in hiPSC-derived neuron models of ASD. High-confidence ASD risk genes emerge as upstream regulators of the network, and many risk genes may impact the network by modulating RAS/ERK, PI3K/AKT, and WNT/-catenin signaling pathways. We found that the degree of dysregulation in this network correlated with the severity of ASD symptoms in the toddlers. These results demonstrate how the heterogeneous genetics of ASD may dysregulate a core network to influence brain development at prenatal and very early postnatal ages and, thereby, the severity of later ASD symptoms.\"\n",
      "!Series_overall_design\t\"Leukocyte gene expression levels were analysed in autistic and typically developing infants and toddlers\"\n",
      "!Series_overall_design\t\"\"\n",
      "!Series_overall_design\t\"Diagnosis key:\"\n",
      "!Series_overall_design\t\"ASD: autism spectrum disorder\"\n",
      "!Series_overall_design\t\"TD: typically developing (control)\"\n",
      "!Series_overall_design\t\"PDDNOS: pervasive developmental disorder not otherwise specified\"\n",
      "!Series_overall_design\t\"PreemieNoDelay: Preemie No Delay (the individual was a preemie but didn't show any mental delay)\"\n",
      "!Series_overall_design\t\"LD: language delay\"\n",
      "!Series_overall_design\t\"AutFeat: Autism features (individual shows some signs of autism, but doesn't meet full criteria)\"\n",
      "!Series_overall_design\t\"\"\n",
      "!Series_overall_design\t\"ADOS_CoSo: the score of each individual for ADOS communication and social deficit, a metric used for the diagnosis of individuals with autism.  The higher the score, the more severe the case.\"\n",
      "!Series_overall_design\t\"\"\n",
      "!Series_overall_design\t\"These data have been included in a SuperSeries with GSE42133 because the data were normalized together and are linked to that data set.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['cell type: leukocyte'], 1: ['gender: M'], 2: ['age (months): 15.277', 'age (months): 18.957', 'age (months): 25.692', 'age (months): 13.142', 'age (months): 24.575', 'age (months): 34.694', 'age (months): 19.22', 'age (months): 13.536', 'age (months): 15.08', 'age (months): 15.146', 'age (months): 23.294', 'age (months): 23.655', 'age (months): 32.526', 'age (months): 17.643', 'age (months): 13.569', 'age (months): 19.055', 'age (months): 12.977', 'age (months): 13.109', 'age (months): 15.113', 'age (months): 16.361', 'age (months): 29.273', 'age (months): 44.879', 'age (months): 17.248', 'age (months): 22.078', 'age (months): 14.423', 'age (months): 28.452', 'age (months): 12.517', 'age (months): 23.129', 'age (months): 28.287', 'age (months): 13.273'], 3: ['diagnosis: TD', 'diagnosis: LD', 'diagnosis: ASD', 'diagnosis: PreemieNoDelay', 'diagnosis: PDDNOS', 'diagnosis: AutFeat'], 4: ['ados_coso: 5', 'ados_coso: 3', 'ados_coso: 1', 'ados_coso: 2', 'ados_coso: 20', 'ados_coso: 0', 'ados_coso: 17', 'ados_coso: 4', 'ados_coso: 12', 'ados_coso: 10', 'ados_coso: 7', 'ados_coso: 13', 'ados_coso: 9', 'ados_coso: 21', 'ados_coso: 11', 'ados_coso: 6', 'ados_coso: 15', 'ados_coso: 8', 'ados_coso: 14', 'ados_coso: 18', 'ados_coso: 19']}\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": "8c11ae21",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "87237f04",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:50:58.248864Z",
     "iopub.status.busy": "2025-03-25T06:50:58.248654Z",
     "iopub.status.idle": "2025-03-25T06:50:58.292524Z",
     "shell.execute_reply": "2025-03-25T06:50:58.292215Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of selected clinical features:\n",
      "{'GSM3024679': [0.0, 15.277], 'GSM3024680': [0.0, 18.957], 'GSM3024681': [0.0, 25.692], 'GSM3024682': [0.0, 13.142], 'GSM3024683': [0.0, 24.575], 'GSM3024684': [1.0, 34.694], 'GSM3024685': [0.0, 19.22], 'GSM3024686': [0.0, 13.536], 'GSM3024687': [1.0, 15.08], 'GSM3024688': [0.0, 15.146], 'GSM3024689': [0.0, 23.294], 'GSM3024690': [0.0, 23.655], 'GSM3024691': [1.0, 32.526], 'GSM3024692': [0.0, 17.643], 'GSM3024693': [0.0, 17.643], 'GSM3024694': [0.0, 13.569], 'GSM3024695': [0.0, 13.569], 'GSM3024696': [0.0, 19.055], 'GSM3024697': [0.0, 12.977], 'GSM3024698': [0.0, 13.109], 'GSM3024699': [0.0, 15.113], 'GSM3024700': [0.0, 16.361], 'GSM3024701': [1.0, 29.273], 'GSM3024702': [1.0, 29.273], 'GSM3024703': [0.0, 24.575], 'GSM3024704': [0.0, 44.879], 'GSM3024705': [0.0, 17.248], 'GSM3024706': [0.0, 22.078], 'GSM3024707': [0.0, 14.423], 'GSM3024708': [1.0, 28.452], 'GSM3024709': [0.0, 12.517], 'GSM3024710': [0.0, 23.129], 'GSM3024711': [1.0, 28.287], 'GSM3024712': [0.0, 13.273], 'GSM3024713': [1.0, 40.608], 'GSM3024714': [1.0, 40.608], 'GSM3024715': [0.0, 21.257], 'GSM3024716': [1.0, 33.38], 'GSM3024717': [0.0, 12.912], 'GSM3024718': [0.0, 19.351], 'GSM3024719': [0.0, 31.639], 'GSM3024720': [1.0, 33.906], 'GSM3024721': [1.0, 19.68], 'GSM3024722': [1.0, 15.671], 'GSM3024723': [1.0, 41.068], 'GSM3024724': [1.0, 41.068], 'GSM3024725': [1.0, 36.172], 'GSM3024726': [1.0, 29.766], 'GSM3024727': [0.0, 13.339], 'GSM3024728': [0.0, 17.084], 'GSM3024729': [0.0, 17.084], 'GSM3024730': [0.0, 24.674], 'GSM3024731': [1.0, 38.538], 'GSM3024732': [0.0, 15.737], 'GSM3024733': [0.0, 15.737], 'GSM3024734': [1.0, 39.951], 'GSM3024735': [0.0, 13.733], 'GSM3024736': [1.0, 30.916], 'GSM3024737': [1.0, 28.715], 'GSM3024738': [1.0, 25.199], 'GSM3024739': [0.0, 11.236], 'GSM3024740': [0.0, 28.912], 'GSM3024741': [1.0, 14.324], 'GSM3024742': [1.0, 18.661], 'GSM3024743': [0.0, 13.306], 'GSM3024744': [1.0, 29.043], 'GSM3024745': [0.0, 14.456], 'GSM3024746': [1.0, 33.873], 'GSM3024747': [1.0, 31.606], 'GSM3024748': [0.0, 12.32], 'GSM3024749': [0.0, 11.532], 'GSM3024750': [1.0, 41.035], 'GSM3024751': [1.0, 31.934], 'GSM3024752': [0.0, 19.187], 'GSM3024753': [1.0, 18.07], 'GSM3024754': [0.0, 28.846], 'GSM3024755': [1.0, 16.526], 'GSM3024756': [0.0, 18.497], 'GSM3024757': [0.0, 33.511], 'GSM3024758': [0.0, 14.62], 'GSM3024759': [0.0, 18.267], 'GSM3024760': [1.0, 40.312], 'GSM3024761': [1.0, 15.507], 'GSM3024762': [0.0, 15.376], 'GSM3024763': [0.0, 18.136], 'GSM3024764': [0.0, 16.394], 'GSM3024765': [0.0, 19.713], 'GSM3024766': [1.0, 12.616], 'GSM3024767': [1.0, 40.476], 'GSM3024768': [1.0, 40.476], 'GSM3024769': [1.0, 12.156], 'GSM3024770': [1.0, 31.08], 'GSM3024771': [0.0, 13.897], 'GSM3024772': [0.0, 14.259], 'GSM3024773': [0.0, 15.244], 'GSM3024774': [0.0, 15.244], 'GSM3024775': [0.0, 13.996], 'GSM3024776': [0.0, 30.949], 'GSM3024777': [0.0, 12.715], 'GSM3024778': [0.0, 12.485], 'GSM3024779': [0.0, 37.027], 'GSM3024780': [0.0, 12.649], 'GSM3024781': [0.0, 13.01], 'GSM3024782': [0.0, 16.0], 'GSM3024783': [0.0, 13.864], 'GSM3024784': [0.0, 14.554], 'GSM3024785': [0.0, 20.008], 'GSM3024786': [0.0, 18.957], 'GSM3024787': [0.0, 16.821], 'GSM3024788': [0.0, 27.598], 'GSM3024789': [0.0, 27.598], 'GSM3024790': [0.0, 12.386], 'GSM3024791': [0.0, 14.292], 'GSM3024792': [0.0, 13.733], 'GSM3024793': [0.0, 13.733], 'GSM3024794': [0.0, 13.634], 'GSM3024795': [0.0, 17.676], 'GSM3024796': [0.0, 15.901], 'GSM3024797': [0.0, 23.786], 'GSM3024798': [0.0, 15.803], 'GSM3024799': [0.0, 16.657], 'GSM3024800': [0.0, 26.152], 'GSM3024801': [0.0, 22.111], 'GSM3024802': [0.0, 23.228], 'GSM3024803': [0.0, 12.156], 'GSM3024804': [0.0, 23.622], 'GSM3024805': [0.0, 13.405], 'GSM3024806': [0.0, 18.727], 'GSM3024807': [0.0, 18.694], 'GSM3024808': [0.0, 25.298], 'GSM3024809': [0.0, 25.298], 'GSM3024810': [0.0, 16.821], 'GSM3024811': [0.0, 32.394], 'GSM3024812': [0.0, 12.025], 'GSM3024813': [0.0, 13.832], 'GSM3024814': [0.0, 13.832], 'GSM3024815': [0.0, 19.778], 'GSM3024816': [0.0, 30.193], 'GSM3024817': [0.0, 17.051], 'GSM3024818': [0.0, 13.01], 'GSM3024819': [0.0, 16.427]}\n",
      "Clinical features saved to ../../output/preprocess/Autism_spectrum_disorder_(ASD)/clinical_data/GSE111175.csv\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "import json\n",
    "from typing import Optional, Dict, Any, Callable\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on the series title and summary, this appears to be gene expression data from leukocytes\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# For Trait: Looking at diagnosis in row 3\n",
    "trait_row = 3\n",
    "\n",
    "# For Age: Found in row 2\n",
    "age_row = 2\n",
    "\n",
    "# For Gender: Found in row 1, but it's constant (all males)\n",
    "# Since it's constant, we'll set it to None as it won't be useful for associative studies\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "def convert_trait(value: str) -> int:\n",
    "    \"\"\"\n",
    "    Convert diagnosis value to binary: 1 for ASD or related conditions, 0 for typically developing\n",
    "    \"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after the colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary based on diagnosis\n",
    "    if value == 'ASD' or value == 'PDDNOS' or value == 'AutFeat':\n",
    "        return 1  # Has autism or autism-related features\n",
    "    elif value == 'TD' or value == 'PreemieNoDelay' or value == 'LD':\n",
    "        return 0  # Typically developing or non-autism condition\n",
    "    else:\n",
    "        return None  # Unknown or invalid value\n",
    "\n",
    "def convert_age(value: str) -> float:\n",
    "    \"\"\"\n",
    "    Convert age value to continuous (months)\n",
    "    \"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after the colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    try:\n",
    "        # Extract numeric value\n",
    "        return float(value)\n",
    "    except (ValueError, TypeError):\n",
    "        return None\n",
    "\n",
    "def convert_gender(value: str) -> int:\n",
    "    \"\"\"\n",
    "    Convert gender value to binary: 0 for female, 1 for male\n",
    "    Not used in this dataset since all subjects are male\n",
    "    \"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after the colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    if value.lower() in ['m', 'male']:\n",
    "        return 1\n",
    "    elif value.lower() in ['f', 'female']:\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine if trait data is available\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Save cohort metadata\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 data is available)\n",
    "if trait_row is not None:\n",
    "    try:\n",
    "        # The clinical_data variable should already be defined from a previous step\n",
    "        # If not, we'll check for it in the global variables\n",
    "        if 'clinical_data' not in globals():\n",
    "            # If clinical_data isn't already loaded, we'll need to use the sample characteristics\n",
    "            # that were shown in the output of the previous step\n",
    "            # Create a dictionary representation of the sample characteristics\n",
    "            sample_chars = {\n",
    "                0: ['cell type: leukocyte'], \n",
    "                1: ['gender: M'], \n",
    "                2: ['age (months): 15.277', 'age (months): 18.957', 'age (months): 25.692', 'age (months): 13.142', 'age (months): 24.575', 'age (months): 34.694', 'age (months): 19.22', 'age (months): 13.536', 'age (months): 15.08', 'age (months): 15.146', 'age (months): 23.294', 'age (months): 23.655', 'age (months): 32.526', 'age (months): 17.643', 'age (months): 13.569', 'age (months): 19.055', 'age (months): 12.977', 'age (months): 13.109', 'age (months): 15.113', 'age (months): 16.361', 'age (months): 29.273', 'age (months): 44.879', 'age (months): 17.248', 'age (months): 22.078', 'age (months): 14.423', 'age (months): 28.452', 'age (months): 12.517', 'age (months): 23.129', 'age (months): 28.287', 'age (months): 13.273'], \n",
    "                3: ['diagnosis: TD', 'diagnosis: LD', 'diagnosis: ASD', 'diagnosis: PreemieNoDelay', 'diagnosis: PDDNOS', 'diagnosis: AutFeat'], \n",
    "                4: ['ados_coso: 5', 'ados_coso: 3', 'ados_coso: 1', 'ados_coso: 2', 'ados_coso: 20', 'ados_coso: 0', 'ados_coso: 17', 'ados_coso: 4', 'ados_coso: 12', 'ados_coso: 10', 'ados_coso: 7', 'ados_coso: 13', 'ados_coso: 9', 'ados_coso: 21', 'ados_coso: 11', 'ados_coso: 6', 'ados_coso: 15', 'ados_coso: 8', 'ados_coso: 14', 'ados_coso: 18', 'ados_coso: 19']\n",
    "            }\n",
    "            # Convert it to a DataFrame\n",
    "            clinical_data = pd.DataFrame.from_dict(sample_chars, orient='index')\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 extracted clinical features\n",
    "        preview = preview_df(selected_clinical_df)\n",
    "        print(\"Preview of selected clinical features:\")\n",
    "        print(preview)\n",
    "        \n",
    "        # Create directory if it doesn't exist\n",
    "        os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "        \n",
    "        # Save the clinical features to a CSV file\n",
    "        selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
    "        print(f\"Clinical features saved to {out_clinical_data_file}\")\n",
    "    except Exception as e:\n",
    "        print(f\"Error in clinical feature extraction: {str(e)}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8ad2e272",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "58818eaa",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:50:58.293722Z",
     "iopub.status.busy": "2025-03-25T06:50:58.293610Z",
     "iopub.status.idle": "2025-03-25T06:50:58.948927Z",
     "shell.execute_reply": "2025-03-25T06:50:58.948549Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209',\n",
      "       'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229',\n",
      "       'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236',\n",
      "       'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253',\n",
      "       'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262'],\n",
      "      dtype='object', name='ID')\n"
     ]
    }
   ],
   "source": [
    "# 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.\n",
    "gene_data = get_genetic_data(matrix_file)\n",
    "\n",
    "# 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.\n",
    "print(gene_data.index[:20])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "99f424c5",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "955e304e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:50:58.950270Z",
     "iopub.status.busy": "2025-03-25T06:50:58.950142Z",
     "iopub.status.idle": "2025-03-25T06:50:58.952117Z",
     "shell.execute_reply": "2025-03-25T06:50:58.951793Z"
    }
   },
   "outputs": [],
   "source": [
    "# Reviewing the gene identifiers\n",
    "# The identifiers shown are Illumina probe IDs (ILMN_XXXXXXX format)\n",
    "# These are not standard human gene symbols like BRCA1, TP53, etc.\n",
    "# Illumina IDs need to be mapped to gene symbols for biological interpretation\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "819a6a53",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "e14aa482",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:50:58.953236Z",
     "iopub.status.busy": "2025-03-25T06:50:58.953125Z",
     "iopub.status.idle": "2025-03-25T06:51:10.759015Z",
     "shell.execute_reply": "2025-03-25T06:51:10.758628Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Species': [nan, nan, nan, nan, nan], 'Source': [nan, nan, nan, nan, nan], 'Search_Key': [nan, nan, nan, nan, nan], 'Transcript': [nan, nan, nan, nan, nan], 'ILMN_Gene': [nan, nan, nan, nan, nan], 'Source_Reference_ID': [nan, nan, nan, nan, nan], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Unigene_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': [nan, nan, nan, nan, nan], 'Symbol': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB'], 'Protein_Product': [nan, nan, nan, nan, 'thrB'], 'Probe_Id': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5090180.0, 6510136.0, 7560739.0, 1450438.0, 1240647.0], 'Probe_Type': [nan, nan, nan, nan, nan], 'Probe_Start': [nan, nan, nan, nan, nan], 'SEQUENCE': ['GAATAAAGAACAATCTGCTGATGATCCCTCCGTGGATCTGATTCGTGTAA', 'CCATGTGATACGAGGGCGCGTAGTTTGCATTATCGTTTTTATCGTTTCAA', 'CCGACAGATGTATGTAAGGCCAACGTGCTCAAATCTTCATACAGAAAGAT', 'TCTGTCACTGTCAGGAAAGTGGTAAAACTGCAACTCAATTACTGCAATGC', 'CTTGTGCCTGAGCTGTCAAAAGTAGAGCACGTCGCCGAGATGAAGGGCGC'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': [nan, nan, nan, nan, nan], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': [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": "9306d4e5",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "a0da5317",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:51:10.760410Z",
     "iopub.status.busy": "2025-03-25T06:51:10.760275Z",
     "iopub.status.idle": "2025-03-25T06:51:13.063289Z",
     "shell.execute_reply": "2025-03-25T06:51:13.062920Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "First 10 mapped gene symbols:\n",
      "Index(['A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1', 'A3GALT2',\n",
      "       'A4GALT', 'A4GNT'],\n",
      "      dtype='object', name='Gene')\n",
      "\n",
      "Preview of gene expression data:\n",
      "{'GSM3024679': [12.14829504, 17.699203898, 17.230453527999998, 23.403461292, 6.554122355], 'GSM3024680': [11.969531379, 17.527891581, 17.219302601, 22.918376916, 6.391279755], 'GSM3024681': [11.727884569, 17.387517878, 17.65973662, 23.093720998, 6.500198372], 'GSM3024682': [11.816503156, 17.572131345, 17.174511298, 23.327156476, 6.613017923], 'GSM3024683': [11.719622797, 18.240017216, 17.772976413000002, 23.249077607, 6.506893687], 'GSM3024684': [12.286030665, 17.873893835, 17.620441581, 23.201478258999998, 6.962539937], 'GSM3024685': [12.048422686, 17.355880630999998, 17.638495722000002, 23.174944167, 6.199299892], 'GSM3024686': [11.924370501999999, 17.754780502, 17.569035263, 23.021282288, 6.355609546], 'GSM3024687': [12.001591653999998, 17.844821955, 17.606445103, 23.076822311, 6.594722618], 'GSM3024688': [12.311364401999999, 17.228406662, 17.794923965, 22.776799546, 6.759964068], 'GSM3024689': [11.935815924, 17.470965681, 17.578313018, 22.874851672, 6.444160827], 'GSM3024690': [12.436110176, 17.67965371, 17.938196194, 23.022721108, 5.874136805], 'GSM3024691': [11.894314798, 18.044227451, 17.453671941, 23.174959463, 6.586291159], 'GSM3024692': [11.971704959, 17.544529813, 17.508546055, 23.08887756, 6.998182568], 'GSM3024693': [12.180822328, 17.628938356, 17.281315994, 22.907317312, 6.999953293], 'GSM3024694': [12.060684981000001, 17.867582012, 17.457109648, 23.101099171999998, 6.530406321], 'GSM3024695': [12.139271094, 17.973033992, 17.42826023, 22.925884761, 6.576595802], 'GSM3024696': [11.896378838, 17.646054093, 17.321054325, 23.29679502, 6.520284253], 'GSM3024697': [11.883716043, 17.746804088, 17.820674568, 23.338652142, 6.526629701], 'GSM3024698': [12.480998412, 17.947627428, 17.355774218, 23.085625319000002, 6.675471592], 'GSM3024699': [11.867819649000001, 17.524844502, 17.36009403, 23.286532665000003, 6.694614881], 'GSM3024700': [12.1055691, 17.596039603, 18.342650933999998, 23.391746279, 6.537733132], 'GSM3024701': [12.272881042, 18.150840151, 17.807688355, 23.228966413000002, 6.143268903], 'GSM3024702': [11.939531546, 17.523102865, 17.490859005, 23.231358833, 6.485310047], 'GSM3024703': [11.751055917, 17.850367634999998, 17.525698017, 23.236043882, 6.354228378], 'GSM3024704': [12.207938814999999, 17.73965046, 17.664480220999998, 23.241258728, 6.140386974], 'GSM3024705': [11.871884130000002, 17.97870907, 17.814301828, 24.10035744, 6.728461191], 'GSM3024706': [12.695606706, 17.308622046, 17.999152243, 22.927649349, 6.507663708], 'GSM3024707': [12.190363963, 17.918360283, 17.430457125, 23.357719472, 6.453224836], 'GSM3024708': [12.358380873000002, 17.701844345, 17.238405806, 23.160853771, 6.631547378], 'GSM3024709': [11.842979324, 18.070519056000002, 17.237460779, 23.261164064, 6.684769344], 'GSM3024710': [11.570915359, 17.624002891, 17.708232141, 23.065285642, 6.775636421], 'GSM3024711': [11.92516573, 17.557640341, 17.578662784, 23.307635703, 6.231651171], 'GSM3024712': [11.957949707000001, 17.776787091, 17.233471473999998, 23.384179933, 6.592178507], 'GSM3024713': [11.935296978, 17.437546284, 17.39480941, 23.098194606, 6.362346687], 'GSM3024714': [11.836711166, 17.782645039000002, 17.470763722, 23.112017649, 6.446273412], 'GSM3024715': [11.816344931, 17.805377613, 17.583367855, 23.362363006, 6.408822153], 'GSM3024716': [12.26523718, 17.326007853, 17.66554885, 23.214361947, 6.551567891], 'GSM3024717': [11.965086894999999, 17.83189388, 17.929628342, 23.757285979000002, 6.189994728], 'GSM3024718': [11.871610617, 17.621547419000002, 17.672495390999998, 22.990316604, 6.407329024], 'GSM3024719': [12.064922067, 17.679264523, 17.401322593, 23.147796213, 6.645820245], 'GSM3024720': [11.956123627, 17.626637792, 17.661966309, 23.511223778999998, 7.389751911], 'GSM3024721': [11.711696063, 17.737371437, 17.477009554, 23.005041417, 6.463671767], 'GSM3024722': [12.025094850999999, 17.72192921, 17.695114745, 23.043315349, 6.521063147], 'GSM3024723': [11.826356059999998, 17.635471987000003, 17.457819026000003, 22.932235121, 6.755566788], 'GSM3024724': [11.976445091, 17.700466019, 18.099020913, 23.179847992, 6.663111103], 'GSM3024725': [11.575562799, 17.582610146, 17.402698657000002, 23.237559498, 6.610994202], 'GSM3024726': [12.259168665, 17.505718010000002, 17.724975811, 23.235863755, 6.61175874], 'GSM3024727': [12.365564905, 17.826673815, 17.704456679, 23.129381248, 6.526287603], 'GSM3024728': [12.023533572000002, 17.805981361, 17.465898085, 23.367549292, 6.605595016], 'GSM3024729': [12.018544592, 17.340689335, 17.704120934, 23.424688023, 6.398008948], 'GSM3024730': [11.860838831, 17.371423926, 17.856703087, 23.138913435, 6.486311742], 'GSM3024731': [12.110223186999999, 17.254132612, 17.83377432, 22.917499598, 6.294110042], 'GSM3024732': [11.990632696999999, 17.90192403, 17.529131018, 23.253893919, 6.369369376], 'GSM3024733': [11.819628512000001, 17.764159856, 17.712981438, 23.427460378, 6.646218329], 'GSM3024734': [11.896854145999999, 17.932485882, 17.584731223, 22.645635418, 6.680303163], 'GSM3024735': [11.83390781, 17.649750152, 17.574178852, 23.002533834, 6.595205978], 'GSM3024736': [11.569020787, 17.645076782, 17.694437316, 23.563557676, 6.212096208], 'GSM3024737': [11.957070329, 17.711415027999998, 17.454819511, 23.116779583, 6.349858619], 'GSM3024738': [12.150181597, 18.025074805, 17.590567412, 23.287613973, 7.363684183], 'GSM3024739': [11.68211303, 17.998029654, 17.439440696, 23.08339286, 6.153456426], 'GSM3024740': [12.082824733999999, 17.525174404, 17.713553128, 23.319464699, 6.087617356], 'GSM3024741': [11.713824749, 17.777253714, 17.350112738, 23.351000416, 6.109498509], 'GSM3024742': [12.342666955999999, 18.053176289, 17.839001228, 22.737755914, 6.368672438], 'GSM3024743': [12.028123124, 17.581790521000002, 17.5501272, 23.649765117, 6.122950643], 'GSM3024744': [12.002765632, 17.801769093, 17.471506455, 23.100406209, 6.453549979], 'GSM3024745': [12.269979242, 17.426052755, 17.769204018, 22.599868961, 6.732054898], 'GSM3024746': [11.982378746, 17.895462128, 17.391416552, 23.47099016, 6.477538161], 'GSM3024747': [11.736938585, 17.810762237, 17.21809665, 23.218049091, 6.330656462], 'GSM3024748': [12.433842707, 18.071018347, 17.483980847, 23.830256151999997, 6.513887528], 'GSM3024749': [12.187955458000001, 17.204521646, 17.166438465, 23.70291769, 6.18237761], 'GSM3024750': [12.734539140999999, 17.909728829, 17.463105058, 23.253824817, 6.179015608], 'GSM3024751': [11.787108703000001, 17.559234526, 17.210473044, 22.959029942, 6.177801514], 'GSM3024752': [12.155071227, 17.71100567, 17.936402462, 23.091192849, 6.655557593], 'GSM3024753': [12.01398554, 17.789996721999998, 17.477377691, 23.374555868, 6.693498984], 'GSM3024754': [11.734981072, 17.663516797, 17.613345317, 22.947281606, 6.478471988], 'GSM3024755': [12.239431535, 17.664293044, 17.452157462000002, 23.396123906, 6.411715146], 'GSM3024756': [12.227549370999999, 17.846412912, 17.577523059, 23.644639929, 6.339790223], 'GSM3024757': [12.090944883, 16.866217206, 17.494437161, 23.224058175, 6.048543058], 'GSM3024758': [12.461979718, 17.525919526, 17.950085069, 23.286456221, 6.032320007], 'GSM3024759': [12.126251572000001, 17.777619754, 17.567104027, 22.813582142, 6.111670103], 'GSM3024760': [11.810178735000001, 17.674408391, 17.761393184, 23.443596712999998, 6.534603931], 'GSM3024761': [11.807557837000001, 17.611303381, 17.473876488, 23.184373602, 6.308111958], 'GSM3024762': [12.005798344999999, 17.61768562, 17.238004395, 23.008250576000002, 6.752817983], 'GSM3024763': [11.941254262000001, 17.847341601, 18.064372292, 23.085620228, 6.634114418], 'GSM3024764': [11.878438982, 17.7165369, 18.037922626, 23.119507605000003, 6.479712408], 'GSM3024765': [11.778239026000001, 17.797760705, 17.069650401, 23.133505383, 6.50414404], 'GSM3024766': [11.987824521, 17.397939239, 17.596497179, 23.263529638999998, 7.426931295], 'GSM3024767': [11.702061164, 17.587371799, 17.456773663, 23.552133695, 6.30074462], 'GSM3024768': [12.25314636, 17.639805246, 17.618752653, 23.41364676, 6.475720431], 'GSM3024769': [11.895869529, 18.05282505, 17.592705664, 23.197921478, 5.951584024], 'GSM3024770': [11.840212172000001, 17.630583955, 17.602747700000002, 22.908305198, 7.274174405], 'GSM3024771': [11.800306314, 17.95136852, 17.926810008, 23.548445064, 6.496645339], 'GSM3024772': [11.884421334999999, 17.840550245, 17.507642287, 23.617515443, 6.531566281], 'GSM3024773': [12.203483934000001, 17.85471896, 17.728281457, 23.136315477, 6.406962597], 'GSM3024774': [11.894359796, 18.00651432, 17.737295023999998, 23.078081425, 6.755852468], 'GSM3024775': [11.828591073, 17.65162589, 17.532489698, 23.118352801999997, 6.533248277], 'GSM3024776': [12.228943281, 17.634047227, 17.435904981, 23.254392367999998, 6.379434874], 'GSM3024777': [11.997546719, 18.462771276, 18.259314957, 23.13575836, 6.842505934], 'GSM3024778': [11.834799017, 17.584522622, 17.545597178, 22.993266401, 6.469428937], 'GSM3024779': [11.80790209, 18.860132171, 17.640156377, 23.526316475999998, 6.12477909], 'GSM3024780': [11.920686078, 18.15872777, 17.454839233999998, 23.005243643, 6.667719385], 'GSM3024781': [12.033715587, 17.661465982, 17.655558226, 23.435810908, 6.438531626], 'GSM3024782': [12.456833074, 18.145134053, 17.179142417, 23.010716271, 6.565902755], 'GSM3024783': [12.071711796, 17.808273895, 17.874682751, 23.479990966000003, 6.844256742], 'GSM3024784': [11.925122261999999, 17.951333465, 17.592376852, 23.199191997, 6.264964684], 'GSM3024785': [11.66792218, 17.687952955, 17.714138359, 23.269072714, 6.22739386], 'GSM3024786': [11.930788386, 17.16210981, 17.836658179, 23.547361266, 6.705984443], 'GSM3024787': [12.080001617, 17.556548202, 17.469551006, 23.294915764000002, 6.556116099], 'GSM3024788': [11.807601888, 17.729907426, 17.283754656, 22.941999249, 6.432972235], 'GSM3024789': [11.882233132, 17.774689229, 17.343552341, 23.437636272, 6.094453205], 'GSM3024790': [12.125679304, 17.412946446, 17.548301235, 23.355586959, 6.720466387], 'GSM3024791': [11.805290224, 17.722267117, 17.556688591, 23.360874599, 6.593007285], 'GSM3024792': [11.688122444000001, 17.699239692, 17.595111105, 23.00402767, 6.742372983], 'GSM3024793': [11.919195533, 18.207317694, 17.818738552, 23.419835958, 6.585794389], 'GSM3024794': [12.092132346, 17.837403111, 17.785567839000002, 23.377775882999998, 6.708207267], 'GSM3024795': [11.864090996, 17.471463697, 17.619110798, 23.570250094, 6.653087835], 'GSM3024796': [11.873289404, 17.793796358999998, 17.628287645, 23.13140403, 5.982530673], 'GSM3024797': [11.840929569, 17.639059063, 17.713457157, 23.288482666, 6.461493526], 'GSM3024798': [11.819594712, 17.895527235, 17.895198596, 23.264609285, 6.284425318], 'GSM3024799': [11.956347013, 17.902391978, 17.345770292, 23.214501077, 6.620962866], 'GSM3024800': [11.95388487, 17.373384091, 17.856150028, 23.163693475000002, 6.250811476], 'GSM3024801': [12.103487487999999, 18.040320180000002, 17.782500341000002, 23.762479283, 6.697582353], 'GSM3024802': [12.068210286, 17.825516308, 17.951255663, 23.320456888, 6.510336119], 'GSM3024803': [11.778654115, 17.865694748, 17.390966017, 23.063713299, 6.620587511], 'GSM3024804': [12.194067718, 17.545804417, 17.631879855, 23.381652014, 6.076221116], 'GSM3024805': [11.78805159, 17.792496918, 17.489723326, 23.190423478, 6.635685728], 'GSM3024806': [11.845316913000001, 17.917776847, 17.661189387, 23.330569844, 6.470696049], 'GSM3024807': [12.100077176, 17.420491248, 17.484593852, 22.936298908, 6.474975954], 'GSM3024808': [11.991461064, 17.54762838, 17.547359384, 23.279417198, 6.667719385], 'GSM3024809': [12.298344704, 17.820199936, 17.604536804, 23.138750881, 6.941477574], 'GSM3024810': [11.996499888999999, 17.892576165999998, 17.322534716, 22.963249152, 6.20856573], 'GSM3024811': [11.724132137000002, 17.381806937, 17.783545964, 23.237206786, 6.257983255], 'GSM3024812': [11.735416483, 18.053376608999997, 17.642520384, 23.189606094, 6.684495795], 'GSM3024813': [12.068068483000001, 17.756658177, 17.974945881, 23.517455187, 6.678554132], 'GSM3024814': [12.11516884, 17.962488337, 17.808250659000002, 22.850014441, 6.623127249], 'GSM3024815': [11.825303263999999, 17.455332457, 17.550148321, 23.364604472, 6.181048729], 'GSM3024816': [11.821744769999999, 17.254191, 17.508777891999998, 23.135277723999998, 6.583838824], 'GSM3024817': [11.929267229, 17.971582134000002, 17.643833835, 22.968637193, 6.254894541], 'GSM3024818': [11.631113892, 17.410927604, 18.01394457, 23.598198509, 6.672887258], 'GSM3024819': [12.396639759, 17.748723579, 17.2416284, 23.226073112, 6.783958141]}\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to ../../output/preprocess/Autism_spectrum_disorder_(ASD)/gene_data/GSE111175.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the columns in gene annotation for mapping\n",
    "# From the preview, we can see that 'ID' contains the probe identifiers (ILMN_*) \n",
    "# and 'Symbol' contains the gene symbols\n",
    "\n",
    "# 2. Get gene mapping dataframe by extracting the two columns\n",
    "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n",
    "\n",
    "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
    "\n",
    "# Print the first few gene symbols to confirm the mapping worked\n",
    "print(\"First 10 mapped gene symbols:\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# Preview a small subset of the gene expression data\n",
    "print(\"\\nPreview of gene expression data:\")\n",
    "print(preview_df(gene_data))\n",
    "\n",
    "# Save the gene expression data\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Gene expression data saved to {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "380d3069",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "34fcc5f2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:51:13.064701Z",
     "iopub.status.busy": "2025-03-25T06:51:13.064576Z",
     "iopub.status.idle": "2025-03-25T06:51:32.237265Z",
     "shell.execute_reply": "2025-03-25T06:51:32.236602Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape: (21464, 141)\n",
      "Gene data columns (sample IDs): ['GSM3024679', 'GSM3024680', 'GSM3024681', 'GSM3024682', 'GSM3024683'] ...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data shape: (20259, 141)\n",
      "First few normalized gene symbols: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1']\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Autism_spectrum_disorder_(ASD)/gene_data/GSE111175.csv\n",
      "Clinical data shape: (2, 140)\n",
      "Clinical data rows (traits): [0.0, 15.277]\n",
      "Clinical data columns (samples): ['GSM3024680', 'GSM3024681', 'GSM3024682', 'GSM3024683', 'GSM3024684'] ...\n",
      "Number of common samples: 140\n",
      "Linked data shape: (140, 20261)\n",
      "Renamed first column to Autism_spectrum_disorder_(ASD)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data shape after handling missing values: (140, 20261)\n",
      "For the feature 'Autism_spectrum_disorder_(ASD)', the least common label is '1.0' with 38 occurrences. This represents 27.14% of the dataset.\n",
      "The distribution of the feature 'Autism_spectrum_disorder_(ASD)' in this dataset is fine.\n",
      "\n",
      "A new JSON file was created at: ../../output/preprocess/Autism_spectrum_disorder_(ASD)/cohort_info.json\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Autism_spectrum_disorder_(ASD)/GSE111175.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Load gene data and normalize gene symbols\n",
    "gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n",
    "print(f\"Gene data shape: {gene_data.shape}\")\n",
    "print(f\"Gene data columns (sample IDs): {gene_data.columns[:5].tolist()} ...\")\n",
    "\n",
    "# Normalize gene symbols\n",
    "try:\n",
    "    normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "    print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n",
    "    print(f\"First few normalized gene symbols: {normalized_gene_data.index[:5].tolist()}\")\n",
    "    \n",
    "    # Save the normalized gene data\n",
    "    os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "    normalized_gene_data.to_csv(out_gene_data_file)\n",
    "    print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
    "    \n",
    "    # Use the normalized gene data for linking\n",
    "    gene_data = normalized_gene_data\n",
    "except Exception as e:\n",
    "    print(f\"Warning: Gene symbol normalization failed: {e}\")\n",
    "    print(\"Continuing with unnormalized gene data\")\n",
    "\n",
    "# Reload or recreate the clinical data with proper orientation\n",
    "try:\n",
    "    # When loading clinical data, ensure index is maintained\n",
    "    selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)\n",
    "    print(f\"Clinical data shape: {selected_clinical_df.shape}\")\n",
    "    print(f\"Clinical data rows (traits): {selected_clinical_df.index.tolist()}\")\n",
    "    print(f\"Clinical data columns (samples): {selected_clinical_df.columns[:5].tolist()} ...\")\n",
    "except Exception as e:\n",
    "    print(f\"Error loading clinical data: {e}\")\n",
    "    # If loading fails, recreate the 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",
    "    print(f\"Recreated clinical data shape: {selected_clinical_df.shape}\")\n",
    "    print(f\"Recreated clinical data rows (traits): {selected_clinical_df.index.tolist()}\")\n",
    "    print(f\"Recreated clinical data columns (samples): {selected_clinical_df.columns[:5].tolist()} ...\")\n",
    "    \n",
    "    # Save the clinical data with index\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    selected_clinical_df.to_csv(out_clinical_data_file)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "\n",
    "# Verify common samples between datasets\n",
    "common_samples = list(set(gene_data.columns).intersection(set(selected_clinical_df.columns)))\n",
    "print(f\"Number of common samples: {len(common_samples)}\")\n",
    "\n",
    "if len(common_samples) == 0:\n",
    "    print(\"Error: No common samples found between gene data and clinical data\")\n",
    "    print(\"Gene data column names format:\", gene_data.columns[0])\n",
    "    print(\"Clinical data column names format:\", selected_clinical_df.columns[0])\n",
    "    \n",
    "    # In case of emergency, create a placeholder dataset so we can validate and save info\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=True,\n",
    "        df=pd.DataFrame({trait: [], 'Age': []}), \n",
    "        note=\"Data linking failed - no common samples between gene expression and clinical data.\"\n",
    "    )\n",
    "    print(\"The dataset was determined to be not usable for analysis.\")\n",
    "else:\n",
    "    # Subset both datasets to include only common samples\n",
    "    gene_data_subset = gene_data[common_samples]\n",
    "    clinical_data_subset = selected_clinical_df[common_samples]\n",
    "    \n",
    "    # 2. Link the clinical and genetic data\n",
    "    linked_data = geo_link_clinical_genetic_data(clinical_data_subset, gene_data_subset)\n",
    "    print(f\"Linked data shape: {linked_data.shape}\")\n",
    "    \n",
    "    # Check if trait column exists in linked data\n",
    "    if trait not in linked_data.columns:\n",
    "        # Try to fix the trait column name if it was transformed during linkage\n",
    "        if len(linked_data.columns) > 0 and pd.api.types.is_numeric_dtype(linked_data.iloc[:, 0]):\n",
    "            # If first column is numeric and likely the trait\n",
    "            linked_data = linked_data.rename(columns={linked_data.columns[0]: trait})\n",
    "            print(f\"Renamed first column to {trait}\")\n",
    "    \n",
    "    # Verify trait column exists after potential renaming\n",
    "    if trait not in linked_data.columns:\n",
    "        print(f\"Error: '{trait}' column missing in linked data\")\n",
    "        print(f\"Available columns: {linked_data.columns[:10].tolist()} ...\")\n",
    "        \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=True,\n",
    "            df=pd.DataFrame({trait: [], 'Age': []}), \n",
    "            note=\"Data linking failed - trait column missing in linked data.\"\n",
    "        )\n",
    "        print(\"The dataset was determined to be not usable for analysis.\")\n",
    "    else:\n",
    "        # 3. Handle missing values in the linked data\n",
    "        linked_data = handle_missing_values(linked_data, trait)\n",
    "        print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
    "        \n",
    "        # 4. Determine whether the trait and demographic features are severely biased\n",
    "        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=trait_biased, \n",
    "            df=unbiased_linked_data, \n",
    "            note=\"Dataset contains gene expression data from leukocytes related to Autism Spectrum Disorder (ASD).\"\n",
    "        )\n",
    "        \n",
    "        # 6. If the linked data is usable, save it as a CSV 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(\"The dataset was determined to be not usable for analysis due to bias in the trait distribution.\")"
   ]
  }
 ],
 "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
}