File size: 34,432 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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "a50fb9be",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:51:42.332108Z",
     "iopub.status.busy": "2025-03-25T06:51:42.331866Z",
     "iopub.status.idle": "2025-03-25T06:51:42.496787Z",
     "shell.execute_reply": "2025-03-25T06:51:42.496478Z"
    }
   },
   "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 = \"GSE123302\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Autism_spectrum_disorder_(ASD)\"\n",
    "in_cohort_dir = \"../../input/GEO/Autism_spectrum_disorder_(ASD)/GSE123302\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Autism_spectrum_disorder_(ASD)/GSE123302.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Autism_spectrum_disorder_(ASD)/gene_data/GSE123302.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Autism_spectrum_disorder_(ASD)/clinical_data/GSE123302.csv\"\n",
    "json_path = \"../../output/preprocess/Autism_spectrum_disorder_(ASD)/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fd59624c",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "e610b7b8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:51:42.498172Z",
     "iopub.status.busy": "2025-03-25T06:51:42.498038Z",
     "iopub.status.idle": "2025-03-25T06:51:42.814203Z",
     "shell.execute_reply": "2025-03-25T06:51:42.813791Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"A meta-analysis of two high-risk prospective studies reveals autism-specific transcriptional changes to chromatin, autoimmune, and environmental response genes in umbilical cord blood\"\n",
      "!Series_summary\t\"Autism spectrum disorder (ASD) is a neurodevelopmental disorder that affects more than 1% of children in the USA. ASD risk is thought to arise from both genetic and environmental factors, with the perinatal period as a critical window. Understanding early transcriptional changes in ASD would assist in clarifying disease pathogenesis and identifying biomarkers. However, little is known about umbilical cord blood gene expression profiles in babies later diagnosed with ASD compared to non-typically developing and non-ASD (Non-TD) or typically developing (TD) children. Genome-wide transcript levels were measured by Affymetrix Human Gene 2.0 array in RNA from cord blood samples from both the Markers of Autism Risk in Babies-Learning Early Signs (MARBLES) and the Early Autism Risk Longitudinal Investigation (EARLI) high-risk pregnancy cohorts that enroll younger siblings of a child previously diagnosed with ASD. Younger siblings were diagnosed based on assessments at 36 months, and 59 ASD, 92 Non-TD, and 120 TD subjects were included. Using both differential expression analysis and weighted gene correlation network analysis, gene expression between ASD and TD, and between Non-TD and TD, was compared within each study and via meta-analysis. While cord blood gene expression differences comparing either ASD or Non-TD to TD did not reach genome- wide significance, 172 genes were nominally differentially expressed between ASD and TD cord blood (log2(fold change) > 0.1, p < 0.01). These genes were significantly enriched for functions in xenobiotic metabolism, chromatin regulation, and systemic lupus erythematosus (FDR q < 0.05). In contrast, 66 genes were nominally differentially expressed between Non-TD and TD, including 8 genes that were also differentially expressed in ASD. Gene coexpression modules were significantly correlated with demographic factors and cell type proportions. ASD-associated gene expression differences identified in this study are subtle, as cord blood is not the main affected tissue, it is composed of many cell types, and ASD is a heterogeneous disorder. This is the first study to identify gene expression differences in cord blood specific to ASD through a meta- analysis across two prospective pregnancy cohorts. The enriched gene pathways support involvement of environmental, immune, and epigenetic mechanisms in ASD etiology.\"\n",
      "!Series_overall_design\t\"Genome-wide transcript levels were measured by Affymetrix Human Gene 2.0 array in umbilical cord blood samples from both the Early Autism Risk Longitudinal Investigation (EARLI) and the Markers of Autism Risk in Babies--Learning Early Signs (MARBLES) studies, which are high-risk pregnancy cohorts of mothers with a child previously diagnosed with ASD. An algorithm-based child diagnosis was based on 36 month assessments, categorized as either ASD, typical development (TD), or not ASD but non-typical (Non-TD). RNA from a total of 59 ASD, 92 Non-TD, and 120 TD subjects were included and differences were analyzed by comparing ASD versus TD subjects, with Non-TD versus TD as a specificity control.\"\n",
      "!Series_overall_design\t\"Note: only files from those who consented to share data were uploaded.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['diagnosis: ASD', 'diagnosis: Non-TD', 'diagnosis: TD'], 1: ['Sex: female', 'Sex: male'], 2: ['study: MARBLES', 'study: EARLI'], 3: ['array batch: MARBLES_2', 'array batch: MARBLES_3', 'array batch: EARLI_1', 'array batch: EARLI_7', 'array batch: EARLI_10', 'array batch: MARBLES_1', 'array batch: EARLI_2', 'array batch: EARLI_3', 'array batch: EARLI_5', 'array batch: EARLI_6', 'array batch: EARLI_8', 'array batch: EARLI_9', 'array batch: EARLI_4']}\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": "de02c1ac",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "e3df645f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:51:42.815418Z",
     "iopub.status.busy": "2025-03-25T06:51:42.815310Z",
     "iopub.status.idle": "2025-03-25T06:51:42.833185Z",
     "shell.execute_reply": "2025-03-25T06:51:42.832891Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical features preview:\n",
      "{'GSM3499537': [1.0, 0.0], 'GSM3499538': [1.0, 0.0], 'GSM3499539': [1.0, 0.0], 'GSM3499540': [1.0, 0.0], 'GSM3499541': [1.0, 0.0], 'GSM3499542': [1.0, 0.0], 'GSM3499543': [1.0, 0.0], 'GSM3499544': [1.0, 0.0], 'GSM3499545': [1.0, 0.0], 'GSM3499546': [1.0, 0.0], 'GSM3499547': [1.0, 0.0], 'GSM3499548': [1.0, 0.0], 'GSM3499549': [1.0, 0.0], 'GSM3499550': [1.0, 0.0], 'GSM3499551': [1.0, 0.0], 'GSM3499552': [1.0, 0.0], 'GSM3499553': [1.0, 1.0], 'GSM3499554': [1.0, 1.0], 'GSM3499555': [1.0, 1.0], 'GSM3499556': [1.0, 1.0], 'GSM3499557': [1.0, 1.0], 'GSM3499558': [1.0, 1.0], 'GSM3499559': [1.0, 1.0], 'GSM3499560': [1.0, 1.0], 'GSM3499561': [1.0, 1.0], 'GSM3499562': [1.0, 1.0], 'GSM3499563': [1.0, 1.0], 'GSM3499564': [1.0, 1.0], 'GSM3499565': [1.0, 1.0], 'GSM3499566': [1.0, 1.0], 'GSM3499567': [1.0, 1.0], 'GSM3499568': [1.0, 1.0], 'GSM3499569': [1.0, 1.0], 'GSM3499570': [1.0, 1.0], 'GSM3499571': [1.0, 1.0], 'GSM3499572': [1.0, 1.0], 'GSM3499573': [1.0, 1.0], 'GSM3499574': [1.0, 1.0], 'GSM3499575': [1.0, 1.0], 'GSM3499576': [1.0, 1.0], 'GSM3499577': [1.0, 1.0], 'GSM3499578': [1.0, 1.0], 'GSM3499579': [1.0, 1.0], 'GSM3499580': [1.0, 1.0], 'GSM3499581': [1.0, 1.0], 'GSM3499582': [1.0, 1.0], 'GSM3499583': [1.0, 1.0], 'GSM3499584': [1.0, 1.0], 'GSM3499585': [1.0, 1.0], 'GSM3499586': [1.0, 1.0], 'GSM3499587': [1.0, 1.0], 'GSM3499588': [1.0, 1.0], 'GSM3499589': [1.0, 1.0], 'GSM3499590': [0.0, 0.0], 'GSM3499591': [0.0, 0.0], 'GSM3499592': [0.0, 0.0], 'GSM3499593': [0.0, 0.0], 'GSM3499594': [0.0, 0.0], 'GSM3499595': [0.0, 0.0], 'GSM3499596': [0.0, 0.0], 'GSM3499597': [0.0, 0.0], 'GSM3499598': [0.0, 0.0], 'GSM3499599': [0.0, 0.0], 'GSM3499600': [0.0, 0.0], 'GSM3499601': [0.0, 0.0], 'GSM3499602': [0.0, 0.0], 'GSM3499603': [0.0, 0.0], 'GSM3499604': [0.0, 0.0], 'GSM3499605': [0.0, 0.0], 'GSM3499606': [0.0, 0.0], 'GSM3499607': [0.0, 0.0], 'GSM3499608': [0.0, 0.0], 'GSM3499609': [0.0, 0.0], 'GSM3499610': [0.0, 0.0], 'GSM3499611': [0.0, 0.0], 'GSM3499612': [0.0, 0.0], 'GSM3499613': [0.0, 0.0], 'GSM3499614': [0.0, 0.0], 'GSM3499615': [0.0, 0.0], 'GSM3499616': [0.0, 0.0], 'GSM3499617': [0.0, 0.0], 'GSM3499618': [0.0, 0.0], 'GSM3499619': [0.0, 0.0], 'GSM3499620': [0.0, 0.0], 'GSM3499621': [0.0, 0.0], 'GSM3499622': [0.0, 0.0], 'GSM3499623': [0.0, 0.0], 'GSM3499624': [0.0, 0.0], 'GSM3499625': [0.0, 0.0], 'GSM3499626': [0.0, 0.0], 'GSM3499627': [0.0, 1.0], 'GSM3499628': [0.0, 1.0], 'GSM3499629': [0.0, 1.0], 'GSM3499630': [0.0, 1.0], 'GSM3499631': [0.0, 1.0], 'GSM3499632': [0.0, 1.0], 'GSM3499633': [0.0, 1.0], 'GSM3499634': [0.0, 1.0], 'GSM3499635': [0.0, 1.0], 'GSM3499636': [0.0, 1.0], 'GSM3499637': [0.0, 1.0], 'GSM3499638': [0.0, 1.0], 'GSM3499639': [0.0, 1.0], 'GSM3499640': [0.0, 1.0], 'GSM3499641': [0.0, 1.0], 'GSM3499642': [0.0, 1.0], 'GSM3499643': [0.0, 1.0], 'GSM3499644': [0.0, 1.0], 'GSM3499645': [0.0, 1.0], 'GSM3499646': [0.0, 1.0], 'GSM3499647': [0.0, 1.0], 'GSM3499648': [0.0, 1.0], 'GSM3499649': [0.0, 1.0], 'GSM3499650': [0.0, 1.0], 'GSM3499651': [0.0, 1.0], 'GSM3499652': [0.0, 1.0], 'GSM3499653': [0.0, 1.0], 'GSM3499654': [0.0, 1.0], 'GSM3499655': [0.0, 1.0], 'GSM3499656': [0.0, 1.0], 'GSM3499657': [0.0, 1.0], 'GSM3499658': [0.0, 1.0], 'GSM3499659': [0.0, 1.0], 'GSM3499660': [0.0, 1.0], 'GSM3499661': [0.0, 1.0], 'GSM3499662': [0.0, 1.0], 'GSM3499663': [0.0, 1.0], 'GSM3499664': [0.0, 1.0], 'GSM3499665': [0.0, 1.0], 'GSM3499666': [0.0, 1.0], 'GSM3499667': [0.0, 1.0], 'GSM3499668': [0.0, 1.0], 'GSM3499669': [0.0, 1.0], 'GSM3499670': [0.0, 0.0], 'GSM3499671': [0.0, 0.0], 'GSM3499672': [0.0, 0.0], 'GSM3499673': [0.0, 0.0], 'GSM3499674': [0.0, 0.0], 'GSM3499675': [0.0, 0.0], 'GSM3499676': [0.0, 0.0], 'GSM3499677': [0.0, 0.0], 'GSM3499678': [0.0, 0.0], 'GSM3499679': [0.0, 0.0], 'GSM3499680': [0.0, 0.0], 'GSM3499681': [0.0, 0.0], 'GSM3499682': [0.0, 0.0], 'GSM3499683': [0.0, 0.0], 'GSM3499684': [0.0, 0.0], 'GSM3499685': [0.0, 0.0], 'GSM3499686': [0.0, 0.0], 'GSM3499687': [0.0, 0.0], 'GSM3499688': [0.0, 0.0], 'GSM3499689': [0.0, 0.0], 'GSM3499690': [0.0, 0.0], 'GSM3499691': [0.0, 0.0], 'GSM3499692': [0.0, 0.0], 'GSM3499693': [0.0, 0.0], 'GSM3499694': [0.0, 0.0], 'GSM3499695': [0.0, 0.0], 'GSM3499696': [0.0, 0.0], 'GSM3499697': [0.0, 0.0], 'GSM3499698': [0.0, 0.0], 'GSM3499699': [0.0, 0.0], 'GSM3499700': [0.0, 0.0], 'GSM3499701': [0.0, 0.0], 'GSM3499702': [0.0, 0.0], 'GSM3499703': [0.0, 0.0], 'GSM3499704': [0.0, 0.0], 'GSM3499705': [0.0, 0.0], 'GSM3499706': [0.0, 0.0], 'GSM3499707': [0.0, 0.0], 'GSM3499708': [0.0, 0.0], 'GSM3499709': [0.0, 0.0], 'GSM3499710': [0.0, 0.0], 'GSM3499711': [0.0, 0.0], 'GSM3499712': [0.0, 0.0], 'GSM3499713': [0.0, 0.0], 'GSM3499714': [0.0, 0.0], 'GSM3499715': [0.0, 1.0], 'GSM3499716': [0.0, 1.0], 'GSM3499717': [0.0, 1.0], 'GSM3499718': [0.0, 1.0], 'GSM3499719': [0.0, 1.0], 'GSM3499720': [0.0, 1.0], 'GSM3499721': [0.0, 1.0], 'GSM3499722': [0.0, 1.0], 'GSM3499723': [0.0, 1.0], 'GSM3499724': [0.0, 1.0], 'GSM3499725': [0.0, 1.0], 'GSM3499726': [0.0, 1.0], 'GSM3499727': [0.0, 1.0], 'GSM3499728': [0.0, 1.0], 'GSM3499729': [0.0, 1.0], 'GSM3499730': [0.0, 1.0], 'GSM3499731': [0.0, 1.0], 'GSM3499732': [0.0, 1.0], 'GSM3499733': [0.0, 1.0], 'GSM3499734': [0.0, 1.0], 'GSM3499735': [0.0, 1.0], 'GSM3499736': [0.0, 1.0]}\n",
      "Clinical data saved to ../../output/preprocess/Autism_spectrum_disorder_(ASD)/clinical_data/GSE123302.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Based on background information, this dataset contains gene expression data measured by Affymetrix Human Gene 2.0 array\n",
    "# This is suitable gene expression data, not miRNA or methylation data\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "\n",
    "# For trait (ASD status), we can see it's available in row 0 as \"diagnosis\"\n",
    "trait_row = 0  \n",
    "\n",
    "# For gender, we see it in row 1 as \"Sex\"\n",
    "gender_row = 1  \n",
    "\n",
    "# For age, there's no information available in the sample characteristics\n",
    "age_row = None  \n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert the trait value to binary (0 for non-ASD, 1 for ASD)\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    if value.upper() == 'ASD':\n",
    "        return 1\n",
    "    elif value.upper() in ['NON-TD', 'TD']:\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender value to binary (0 for female, 1 for male)\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    if value.lower() == 'female':\n",
    "        return 0\n",
    "    elif value.lower() == 'male':\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# Age conversion function is not needed since age data is not available\n",
    "convert_age = None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Check if trait data is available (trait_row is not None)\n",
    "is_trait_available = trait_row is not None\n",
    "validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path, \n",
    "                             is_gene_available=is_gene_available, \n",
    "                             is_trait_available=is_trait_available)\n",
    "\n",
    "# 4. Clinical Feature Extraction\n",
    "# This should only be executed if trait_row is not None, which it is in this case\n",
    "if trait_row is not None:\n",
    "    # Extract clinical features using the provided function\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",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender,\n",
    "        age_row=age_row,\n",
    "        convert_age=convert_age\n",
    "    )\n",
    "    \n",
    "    # Preview the data\n",
    "    print(\"Clinical features preview:\")\n",
    "    print(preview_df(clinical_features))\n",
    "    \n",
    "    # Save the clinical data to CSV\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    clinical_features.to_csv(out_clinical_data_file, index=False)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1661f40b",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "518df04d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:51:42.834228Z",
     "iopub.status.busy": "2025-03-25T06:51:42.834129Z",
     "iopub.status.idle": "2025-03-25T06:51:43.396619Z",
     "shell.execute_reply": "2025-03-25T06:51:43.396244Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['16657436', '16657440', '16657445', '16657447', '16657450', '16657469',\n",
      "       '16657473', '16657476', '16657489', '16657492', '16657502', '16657506',\n",
      "       '16657514', '16657529', '16657534', '16657554', '16657572', '16657594',\n",
      "       '16657598', '16657647'],\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": "5f7eb08f",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "e704977a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:51:43.397894Z",
     "iopub.status.busy": "2025-03-25T06:51:43.397780Z",
     "iopub.status.idle": "2025-03-25T06:51:43.399672Z",
     "shell.execute_reply": "2025-03-25T06:51:43.399399Z"
    }
   },
   "outputs": [],
   "source": [
    "# These identifiers appear to be probe IDs from a microarray platform, not human gene symbols.\n",
    "# The numeric identifiers (like '16657436') are not in the format of standard gene symbols \n",
    "# which would typically be alphanumeric (like 'BRCA1', 'TP53', etc.)\n",
    "# Therefore, these would need to be mapped to gene symbols for proper analysis.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9dcf7ce8",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "57998130",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:51:43.400780Z",
     "iopub.status.busy": "2025-03-25T06:51:43.400677Z",
     "iopub.status.idle": "2025-03-25T06:51:51.812450Z",
     "shell.execute_reply": "2025-03-25T06:51:51.812013Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['16657436', '16657440', '16657445', '16657447', '16657450'], 'RANGE_STRAND': ['+', '+', '+', '+', '+'], 'RANGE_START': [12190.0, 29554.0, 69091.0, 160446.0, 317811.0], 'RANGE_END': [13639.0, 31109.0, 70008.0, 161525.0, 328581.0], 'total_probes': [25.0, 28.0, 8.0, 13.0, 36.0], 'GB_ACC': ['NR_046018', nan, nan, nan, 'NR_024368'], 'SPOT_ID': ['chr1:12190-13639', 'chr1:29554-31109', 'chr1:69091-70008', 'chr1:160446-161525', 'chr1:317811-328581'], 'RANGE_GB': ['NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10']}\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": "85ce5d52",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "1b0e1532",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:51:51.814043Z",
     "iopub.status.busy": "2025-03-25T06:51:51.813908Z",
     "iopub.status.idle": "2025-03-25T06:52:04.010112Z",
     "shell.execute_reply": "2025-03-25T06:52:04.009773Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation column names:\n",
      "['ID', 'RANGE_STRAND', 'RANGE_START', 'RANGE_END', 'total_probes', 'GB_ACC', 'SPOT_ID', 'RANGE_GB']\n",
      "\n",
      "Examining more rows for potential gene information:\n",
      "\n",
      "Sample of GB_ACC values:\n",
      "0     NR_046018\n",
      "4     NR_024368\n",
      "7     NR_029406\n",
      "9     XR_132471\n",
      "15    NR_047526\n",
      "18    NM_152486\n",
      "19    NM_198317\n",
      "21    NM_005101\n",
      "22    NM_198576\n",
      "23    NR_038869\n",
      "Name: GB_ACC, dtype: object\n",
      "\n",
      "Creating mapping from RefSeq accessions:\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sample of the mapping data:\n",
      "         ID         Gene\n",
      "0  16657436  [NR_046018]\n",
      "1  16657440           []\n",
      "2  16657445           []\n",
      "3  16657447           []\n",
      "4  16657450  [NR_024368]\n",
      "5  16657469           []\n",
      "6  16657473           []\n",
      "7  16657476  [NR_029406]\n",
      "8  16657480           []\n",
      "9  16657485  [XR_132471]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "No genes were mapped successfully using accession numbers.\n",
      "\n",
      "Falling back to using probe IDs as identifiers...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene data saved with original probe IDs: (36459, 224)\n",
      "Sample probe IDs: Index(['16657436', '16657440', '16657445', '16657447', '16657450'], dtype='object', name='ID')\n",
      "Gene data saved to ../../output/preprocess/Autism_spectrum_disorder_(ASD)/gene_data/GSE123302.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Let's first check if we have any annotation columns that might contain gene symbols\n",
    "print(\"Gene annotation column names:\")\n",
    "print(gene_annotation.columns.tolist())\n",
    "\n",
    "# Let's check more rows to get a better understanding of the data\n",
    "print(\"\\nExamining more rows for potential gene information:\")\n",
    "# Look at GB_ACC column which contains accession numbers\n",
    "print(\"\\nSample of GB_ACC values:\")\n",
    "print(gene_annotation['GB_ACC'].dropna().head(10))\n",
    "\n",
    "# Try to get any additional columns that might have gene annotations\n",
    "additional_cols = [col for col in gene_annotation.columns if 'gene' in col.lower()]\n",
    "if additional_cols:\n",
    "    print(\"\\nAdditional gene-related columns found:\")\n",
    "    print(additional_cols)\n",
    "    for col in additional_cols:\n",
    "        print(f\"\\nSample of {col} values:\")\n",
    "        print(gene_annotation[col].dropna().head(5))\n",
    "\n",
    "# For Affymetrix Gene 2.0 arrays, we often need to use a specialized annotation package\n",
    "# Let's try a different approach - use the GB_ACC column which contains RefSeq IDs that can be mapped to genes\n",
    "print(\"\\nCreating mapping from RefSeq accessions:\")\n",
    "\n",
    "# Create a mapping dataframe with RefSeq IDs\n",
    "mapping_data = gene_annotation[['ID', 'GB_ACC']].copy()\n",
    "mapping_data = mapping_data.rename(columns={'GB_ACC': 'Gene'})\n",
    "\n",
    "# As a special case for this dataset: many RefSeq accessions start with NM_, NR_, XM_, XR_\n",
    "# which include gene information we can try to extract\n",
    "def extract_gene_info_from_accession(accession):\n",
    "    \"\"\"Try to extract gene information from RefSeq accession IDs\"\"\"\n",
    "    if not isinstance(accession, str):\n",
    "        return []\n",
    "    \n",
    "    # For NM_ and NR_ accessions, let's extract potential gene information\n",
    "    # This is an imperfect approach but might help with this dataset\n",
    "    parts = accession.split('_')\n",
    "    if len(parts) >= 2 and parts[0] in ['NM', 'NR', 'XM', 'XR']:\n",
    "        # Return the accession itself as a placeholder for the gene\n",
    "        return [accession]\n",
    "    return []\n",
    "\n",
    "# Update the mapping function in apply_gene_mapping\n",
    "mapping_data['Gene'] = mapping_data['Gene'].apply(extract_gene_info_from_accession)\n",
    "\n",
    "# Print a sample of the mapping\n",
    "print(\"Sample of the mapping data:\")\n",
    "print(mapping_data.head(10))\n",
    "\n",
    "# Apply the mapping\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_data)\n",
    "\n",
    "# Check if we have any genes mapped\n",
    "if gene_data.shape[0] == 0:\n",
    "    print(\"\\nNo genes were mapped successfully using accession numbers.\")\n",
    "    \n",
    "    # Since we couldn't map genes using the available annotations, we'll create\n",
    "    # a simpler dataset where probe IDs are treated as gene identifiers\n",
    "    print(\"\\nFalling back to using probe IDs as identifiers...\")\n",
    "    \n",
    "    # Create a CSV with the original probe data\n",
    "    gene_data_original = get_genetic_data(matrix_file)\n",
    "    \n",
    "    # Save the probe-level data\n",
    "    os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "    gene_data_original.to_csv(out_gene_data_file)\n",
    "    \n",
    "    print(f\"\\nGene data saved with original probe IDs: {gene_data_original.shape}\")\n",
    "    print(f\"Sample probe IDs: {gene_data_original.index[:5]}\")\n",
    "    print(f\"Gene data saved to {out_gene_data_file}\")\n",
    "else:\n",
    "    # Normalize gene symbols\n",
    "    gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "    \n",
    "    # Print summary and save\n",
    "    print(f\"\\nGene data shape after mapping: {gene_data.shape}\")\n",
    "    print(f\"First 10 gene symbols after mapping: {gene_data.index[:10]}\")\n",
    "    \n",
    "    # Save the gene expression data\n",
    "    os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "    gene_data.to_csv(out_gene_data_file)\n",
    "    print(f\"Gene data saved to {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "82610280",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "894e1df3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:52:04.011493Z",
     "iopub.status.busy": "2025-03-25T06:52:04.011369Z",
     "iopub.status.idle": "2025-03-25T06:52:04.376165Z",
     "shell.execute_reply": "2025-03-25T06:52:04.375793Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape: (36459, 224)\n",
      "First few gene/probe identifiers: [16657436, 16657440, 16657445, 16657447, 16657450]\n",
      "Linking clinical and genetic data failed - no valid rows or trait column missing\n",
      "Abnormality detected in the cohort: GSE123302. Preprocessing failed.\n",
      "The dataset was determined to be not usable for analysis.\n"
     ]
    }
   ],
   "source": [
    "# 1. We need to first load the selected_clinical_df from the saved file, or recreate it\n",
    "try:\n",
    "    # Try to load the previously saved clinical data\n",
    "    selected_clinical_df = pd.read_csv(out_clinical_data_file)\n",
    "except:\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",
    "\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",
    "    # Save the clinical data\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",
    "# Try to load the gene data from Step 6\n",
    "gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n",
    "\n",
    "# Check if we have proper gene symbols or just probe IDs\n",
    "# In this case, Step 6 indicated that we have probe IDs, not gene symbols\n",
    "# So we'll skip normalization and use the probe IDs directly\n",
    "print(f\"Gene data shape: {gene_data.shape}\")\n",
    "print(f\"First few gene/probe identifiers: {gene_data.index[:5].tolist()}\")\n",
    "\n",
    "# 2. Link the clinical and genetic data\n",
    "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data)\n",
    "\n",
    "# Check if linking was successful\n",
    "if len(linked_data) == 0 or trait not in linked_data.columns:\n",
    "    print(\"Linking clinical and genetic data failed - no valid rows or trait column missing\")\n",
    "    # Set is_usable to False and save cohort 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,  # Consider it biased if linking fails\n",
    "        df=pd.DataFrame({trait: [], 'Gender': []}), \n",
    "        note=\"Data linking failed - unable to process gene expression data appropriately.\"\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",
    "    \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_type = 'binary' if len(linked_data[trait].unique()) <= 2 else 'continuous'\n",
    "    if trait_type == 'binary':\n",
    "        if len(linked_data[trait].value_counts()) >= 2:\n",
    "            is_trait_biased = judge_binary_variable_biased(linked_data, trait)\n",
    "        else:\n",
    "            print(f\"Trait '{trait}' has only one unique value, considering it biased.\")\n",
    "            is_trait_biased = True\n",
    "    else:\n",
    "        is_trait_biased = judge_continuous_variable_biased(linked_data, trait)\n",
    "    \n",
    "    # Remove biased demographic features\n",
    "    unbiased_linked_data = linked_data.copy()\n",
    "    if 'Age' in unbiased_linked_data.columns:\n",
    "        age_biased = judge_continuous_variable_biased(unbiased_linked_data, 'Age')\n",
    "        if age_biased:\n",
    "            print(f\"The distribution of the feature \\'Age\\' in this dataset is severely biased.\")\n",
    "            unbiased_linked_data = unbiased_linked_data.drop(columns=['Age'])\n",
    "    \n",
    "    if 'Gender' in unbiased_linked_data.columns:\n",
    "        if len(unbiased_linked_data['Gender'].value_counts()) >= 2:\n",
    "            gender_biased = judge_binary_variable_biased(unbiased_linked_data, 'Gender')\n",
    "            if gender_biased:\n",
    "                print(f\"The distribution of the feature \\'Gender\\' in this dataset is severely biased.\")\n",
    "                unbiased_linked_data = unbiased_linked_data.drop(columns=['Gender'])\n",
    "        else:\n",
    "            print(f\"Gender has only one unique value, considering it biased and removing.\")\n",
    "            unbiased_linked_data = unbiased_linked_data.drop(columns=['Gender'])\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 data from umbilical cord blood samples 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
}