File size: 37,701 Bytes
736e4a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "86e246e5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:54:59.675813Z",
     "iopub.status.busy": "2025-03-25T06:54:59.675635Z",
     "iopub.status.idle": "2025-03-25T06:54:59.837737Z",
     "shell.execute_reply": "2025-03-25T06:54:59.837397Z"
    }
   },
   "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 = \"Bipolar_disorder\"\n",
    "cohort = \"GSE120342\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Bipolar_disorder\"\n",
    "in_cohort_dir = \"../../input/GEO/Bipolar_disorder/GSE120342\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Bipolar_disorder/GSE120342.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Bipolar_disorder/gene_data/GSE120342.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Bipolar_disorder/clinical_data/GSE120342.csv\"\n",
    "json_path = \"../../output/preprocess/Bipolar_disorder/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "904a20c7",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "859c6511",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:54:59.839138Z",
     "iopub.status.busy": "2025-03-25T06:54:59.838985Z",
     "iopub.status.idle": "2025-03-25T06:54:59.895161Z",
     "shell.execute_reply": "2025-03-25T06:54:59.894841Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Aberrant transcriptomes and DNA methylomes define pathways that drive pathogenesis and loss of brain laterality/asymmetry in schizophrenia and bipolar disorder\"\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: ['disease state: control', 'disease state: SCZ', 'disease state: BD(-)', 'disease state: BD(+)'], 1: ['laterality: left', 'laterality: right']}\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": "2a3e0776",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "b7b7256f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:54:59.896303Z",
     "iopub.status.busy": "2025-03-25T06:54:59.896191Z",
     "iopub.status.idle": "2025-03-25T06:54:59.905740Z",
     "shell.execute_reply": "2025-03-25T06:54:59.905440Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of selected clinical features: {0: [0.0], 1: [nan]}\n",
      "Clinical data saved to ../../output/preprocess/Bipolar_disorder/clinical_data/GSE120342.csv\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "import json\n",
    "import numpy as np\n",
    "from typing import Optional, Callable, Dict, Any\n",
    "\n",
    "# Sample characteristics dictionary from the previous output\n",
    "characteristics_dict = {0: ['disease state: control', 'disease state: SCZ', 'disease state: BD(-)', 'disease state: BD(+)'], \n",
    "                        1: ['laterality: left', 'laterality: right']}\n",
    "\n",
    "# Create a correctly structured clinical data DataFrame\n",
    "# This is in the format expected by geo_select_clinical_features\n",
    "clinical_data = pd.DataFrame()\n",
    "for key, values in characteristics_dict.items():\n",
    "    # Create a Series and then transpose it to get a single row\n",
    "    row_series = pd.Series(values)\n",
    "    # Add as a row to the DataFrame\n",
    "    clinical_data[key] = row_series\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on the title and summary, this appears to be gene expression data combined with DNA methylation\n",
    "is_gene_available = True\n",
    "\n",
    "# 2.1 Data Availability\n",
    "# For trait (Bipolar_disorder)\n",
    "# Looking at key 0, we can see \"disease state: BD(+)\" and \"disease state: BD(-)\" which indicate bipolar disorder cases\n",
    "trait_row = 0\n",
    "\n",
    "# Age data is not provided in the sample characteristics\n",
    "age_row = None\n",
    "\n",
    "# Gender data is not provided in the sample characteristics\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert disease state to binary trait (Bipolar_disorder)\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # BD(+) and BD(-) both indicate Bipolar Disorder cases\n",
    "    if value.startswith('BD'):\n",
    "        return 1\n",
    "    # Controls\n",
    "    elif value.lower() == 'control':\n",
    "        return 0\n",
    "    # SCZ indicates Schizophrenia, not Bipolar\n",
    "    elif value.lower() == 'scz':\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age to continuous values\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    try:\n",
    "        return float(value)\n",
    "    except:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender to binary (0 for female, 1 for male)\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    value = value.lower()\n",
    "    if 'female' in value or 'f' == value:\n",
    "        return 0\n",
    "    elif 'male' in value or 'm' == value:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# Define get_feature_data function needed by geo_select_clinical_features\n",
    "def get_feature_data(df, row_idx, feature_name, convert_func):\n",
    "    \"\"\"Extract and process feature data from a row in the DataFrame.\"\"\"\n",
    "    values = df[row_idx].values\n",
    "    processed_values = [convert_func(value) for value in values]\n",
    "    return pd.DataFrame({feature_name: processed_values}, index=df.index)\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Check if trait data is available\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Conduct initial filtering and save info\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. Clinical Feature Extraction\n",
    "if trait_row is not None:\n",
    "    try:\n",
    "        # Extract clinical features\n",
    "        selected_clinical_df = geo_select_clinical_features(\n",
    "            clinical_df=clinical_data,\n",
    "            trait=trait,\n",
    "            trait_row=trait_row,\n",
    "            convert_trait=convert_trait,\n",
    "            age_row=age_row,\n",
    "            convert_age=convert_age,\n",
    "            gender_row=gender_row,\n",
    "            convert_gender=convert_gender\n",
    "        )\n",
    "        \n",
    "        # Preview the dataframe\n",
    "        preview = preview_df(selected_clinical_df)\n",
    "        print(f\"Preview of selected clinical features: {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 to CSV\n",
    "        selected_clinical_df.to_csv(out_clinical_data_file)\n",
    "        print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "    except Exception as e:\n",
    "        print(f\"Error in clinical feature extraction: {e}\")\n",
    "        import traceback\n",
    "        print(traceback.format_exc())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6796c537",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "2eb7ce0b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:54:59.906811Z",
     "iopub.status.busy": "2025-03-25T06:54:59.906704Z",
     "iopub.status.idle": "2025-03-25T06:54:59.977334Z",
     "shell.execute_reply": "2025-03-25T06:54:59.976959Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Matrix file found: ../../input/GEO/Bipolar_disorder/GSE120342/GSE120342-GPL16311_series_matrix.txt.gz\n",
      "Gene data shape: (19070, 30)\n",
      "First 20 gene/probe identifiers:\n",
      "Index(['100009676_at', '10000_at', '10001_at', '10002_at', '10003_at',\n",
      "       '100048912_at', '100049716_at', '10004_at', '10005_at', '10006_at',\n",
      "       '10007_at', '10008_at', '100093630_at', '10009_at', '1000_at',\n",
      "       '100101467_at', '100101938_at', '10010_at', '100113407_at', '10011_at'],\n",
      "      dtype='object', name='ID')\n"
     ]
    }
   ],
   "source": [
    "# 1. Get the SOFT and matrix file paths again \n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "print(f\"Matrix file found: {matrix_file}\")\n",
    "\n",
    "# 2. Use the get_genetic_data function from the library to get the gene_data\n",
    "try:\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    print(f\"Gene data shape: {gene_data.shape}\")\n",
    "    \n",
    "    # 3. Print the first 20 row IDs (gene or probe identifiers)\n",
    "    print(\"First 20 gene/probe identifiers:\")\n",
    "    print(gene_data.index[:20])\n",
    "except Exception as e:\n",
    "    print(f\"Error extracting gene data: {e}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eeb1230e",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "5cafcc77",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:54:59.978587Z",
     "iopub.status.busy": "2025-03-25T06:54:59.978475Z",
     "iopub.status.idle": "2025-03-25T06:54:59.980636Z",
     "shell.execute_reply": "2025-03-25T06:54:59.980344Z"
    }
   },
   "outputs": [],
   "source": [
    "# Based on the gene identifiers provided, I can identify that these are DNA methylation probes,\n",
    "# not gene symbols. The \"cg\" prefix is characteristic of Illumina DNA methylation arrays \n",
    "# (like the 450K or EPIC arrays). These need to be mapped to gene symbols if we want\n",
    "# to associate them with specific genes.\n",
    "\n",
    "# For methylation data, each probe corresponds to a specific CpG site in the genome,\n",
    "# and these sites may be associated with specific genes, but they are not gene expression values\n",
    "# in themselves, but rather represent DNA methylation levels.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c7ed2535",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "babd2567",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:54:59.981750Z",
     "iopub.status.busy": "2025-03-25T06:54:59.981645Z",
     "iopub.status.idle": "2025-03-25T06:55:02.288434Z",
     "shell.execute_reply": "2025-03-25T06:55:02.288022Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "Columns in gene annotation: ['ID', 'Name', 'IlmnStrand', 'AddressA_ID', 'AlleleA_ProbeSeq', 'AddressB_ID', 'AlleleB_ProbeSeq', 'GenomeBuild', 'Chr', 'MapInfo', 'Ploidy', 'Species', 'Source', 'SourceVersion', 'SourceStrand', 'SourceSeq', 'TopGenomicSeq', 'Next_Base', 'Color_Channel', 'TSS_Coordinate', 'Gene_Strand', 'Gene_ID', 'Symbol', 'Synonym', 'Accession', 'GID', 'Annotation', 'Product', 'Distance_to_TSS', 'CPG_ISLAND', 'CPG_ISLAND_LOCATIONS', 'MIR_CPG_ISLAND', 'RANGE_GB', 'RANGE_START', 'RANGE_END', 'RANGE_STRAND', 'GB_ACC', 'ORF']\n",
      "{'ID': ['cg00000292', 'cg00002426', 'cg00003994', 'cg00005847', 'cg00006414'], 'Name': ['cg00000292', 'cg00002426', 'cg00003994', 'cg00005847', 'cg00006414'], 'IlmnStrand': ['TOP', 'TOP', 'TOP', 'BOT', 'BOT'], 'AddressA_ID': [990370.0, 6580397.0, 7150184.0, 4850717.0, 6980731.0], 'AlleleA_ProbeSeq': ['AAACATTAATTACCAACCACTCTTCCAAAAAACACTTACCATTAAAACCA', 'AATATAATAACATTACCTTACCCATCTTATAATCAAACCAAACAAAAACA', 'AATAATAATAATACCCCCTATAATACTAACTAACAAACATACCCTCTTCA', 'TACTATAATACACCCTATATTTAAAACACTAAACTTACCCCATTAAAACA', 'CTCAAAAACCAAACAAAACAAAACCCCAATACTAATCATTAATAAAATCA'], 'AddressB_ID': [6660678.0, 6100343.0, 7150392.0, 1260113.0, 4280093.0], 'AlleleB_ProbeSeq': ['AAACATTAATTACCAACCGCTCTTCCAAAAAACACTTACCATTAAAACCG', 'AATATAATAACATTACCTTACCCGTCTTATAATCAAACCAAACGAAAACG', 'AATAATAATAATACCCCCTATAATACTAACTAACAAACATACCCTCTTCG', 'TACTATAATACACCCTATATTTAAAACACTAAACTTACCCCATTAAAACG', 'CTCGAAAACCGAACAAAACAAAACCCCAATACTAATCGTTAATAAAATCG'], 'GenomeBuild': [36.0, 36.0, 36.0, 36.0, 36.0], 'Chr': ['16', '3', '7', '2', '7'], 'MapInfo': [28797601.0, 57718583.0, 15692387.0, 176737319.0, 148453770.0], 'Ploidy': ['diploid', 'diploid', 'diploid', 'diploid', 'diploid'], 'Species': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Source': ['NCBI:RefSeq', 'NCBI:RefSeq', 'NCBI:RefSeq', 'NCBI:RefSeq', 'NCBI:RefSeq'], 'SourceVersion': [36.1, 36.1, 36.1, 36.1, 36.1], 'SourceStrand': ['TOP', 'TOP', 'BOT', 'BOT', 'BOT'], 'SourceSeq': ['CGGCCTCAATGGTAAGTGTCCCTTGGAAGAGCGGCTGGTAATTAATGCCC', 'CGCTCTCGTCTGGTTTGATCACAAGACGGGCAAGGTAATGTCACCACATT', 'GGTGGTGGTGGTGCCCCCTGTGATGCTGGCTGGCAAACATGCCCTCTTCG', 'TACTGTAATGCACCCTGTATTTAAGGCACTGGGCTTGCCCCATTAAAGCG', 'CTCGGAAACCGAGCAGGGCAAAACCCCAGTGCTGATCGTTAGTGGGATCG'], 'TopGenomicSeq': ['TGGGGTGAGTGAGACCACGGGCCTCACCCCGGACCAAGTTAAGCGGAATCTGGAGAAATA[CG]GCCTCAATGGTAAGTGTCCCTTGGAAGAGCGGCTGGTAATTAATGCCCTCCTGCACCCCC', 'CCGCTGTCGACCAGCGCAGAATAATGCCACTTTTGATTGCAAAGTGCTATCAAGGAACCA[CG]CTCTCGTCTGGTTTGATCACAAGACGGGCAAGGTAATGTCACCACATTGTCCAGCGGCAT', 'GGTGGTGGTGGTGGTGGTGGTGGTGCCCCCTGTGATGCTGGCTGGCAAACATGCCCTCTT[CG]TTGGGGTATCCCGCGATTATGCAAGATGAGGAAGAAGTAGAGAGCTCGGGGTAAGACATA', 'CAGATAACTCAATACTGTAATGCACCCTGTATTTAAGGCACTGGGCTTGCCCCATTAAAG[CG]CCATAAATTTGAAGGCCAATGATCGGTTTTCATGTAACGGGTGGTACTTCATACTGAAGT', 'GAACCGGCCCAGCTCGGAAACCGAGCAGGGCAAAACCCCAGTGCTGATCGTTAGTGGGAT[CG]CGCCTGTGAATAGCCACTGCCCTCCAGCCTGGGCAACAGCCAGACCCCGTCTGTTTAATA'], 'Next_Base': ['T', 'T', 'T', 'C', 'C'], 'Color_Channel': ['Red', 'Red', 'Red', 'Grn', 'Grn'], 'TSS_Coordinate': [28797310.0, 57718214.0, 15692819.0, 176737051.0, 148454441.0], 'Gene_Strand': ['+', '+', '-', '+', '+'], 'Gene_ID': ['GeneID:487', 'GeneID:7871', 'GeneID:4223', 'GeneID:3232', 'GeneID:57541'], 'Symbol': ['ATP2A1', 'SLMAP', 'MEOX2', 'HOXD3', 'ZNF398'], 'Synonym': ['ATP2A; SERCA1;', 'SLAP; KIAA1601;', 'GAX; MOX2;', 'HOX4; HOX1D; HOX4A; Hox-4.1; MGC10470;', 'P51; P71; ZER6; KIAA1339;'], 'Accession': ['NM_173201.2', 'NM_007159.2', 'NM_005924.3', 'NM_006898.4', 'NM_020781.2'], 'GID': ['GI:47132613', 'GI:56550042', 'GI:55956906', 'GI:23510372', 'GI:25777702'], 'Annotation': ['isoform a is encoded by transcript variant a; sarcoplasmic/endoplasmic reticulum calcium ATPase 1; calcium pump 1; SR Ca(2+)-ATPase 1; calcium-transporting ATPase sarcoplasmic reticulum type; fast twitch skeletal muscle isoform; endoplasmic reticulum class 1/2 Ca(2+) ATPase; go_component: membrane; go_component: integral to membrane; go_component: sarcoplasmic reticulum; go_component: smooth endoplasmic reticulum; go_function: ATP binding; go_function: hydrolase activity; go_function: nucleotide binding; go_function: calcium ion binding; go_function: magnesium ion binding; go_function: calcium-transporting ATPase activity; go_function: hydrolase activity; acting on acid anhydrides; catalyzing transmembrane movement of substances; go_process: metabolism; go_process: cation transport; go_process: proton transport; go_process: calcium ion transport; go_process: regulation of striated muscle contraction', 'Sarcolemmal-associated protein; go_component: integral to plasma membrane; go_component: smooth endoplasmic reticulum; go_function: unfolded protein binding; go_process: protein folding; go_process: muscle contraction', 'growth arrest-specific homeo box; go_component: nucleus; go_function: transcription factor activity; go_process: circulation; go_process: development; go_process: regulation of transcription; DNA-dependent', 'homeobox protein Hox-D3; Hox-4.1; mouse; homolog of; homeo box D3; go_component: nucleus; go_function: transcription factor activity; go_process: morphogenesis; go_process: regulation of transcription; DNA-dependent', 'isoform b is encoded by transcript variant 2; zinc finger DNA binding protein ZER6; zinc finger-estrogen receptor interaction; clone 6; zinc finger DNA binding protein p52/p71; go_component: nucleus; go_function: DNA binding; go_function: zinc ion binding; go_function: metal ion binding; go_function: transcriptional activator activity; go_process: transcription; go_process: regulation of transcription; DNA-dependent'], 'Product': ['ATPase; Ca++ transporting; fast twitch 1 isoform a', 'sarcolemma associated protein', 'mesenchyme homeo box 2', 'homeobox D3', 'zinc finger 398 isoform b'], 'Distance_to_TSS': [291.0, 369.0, 432.0, 268.0, 671.0], 'CPG_ISLAND': [True, True, True, False, True], 'CPG_ISLAND_LOCATIONS': ['16:28797486-28797825', '3:57716811-57718675', '7:15691512-15693551', nan, '7:148453584-148455804'], 'MIR_CPG_ISLAND': [nan, nan, nan, nan, nan], 'RANGE_GB': ['NC_000016.8', 'NC_000003.10', 'NC_000007.12', nan, 'NC_000007.12'], 'RANGE_START': [28797486.0, 57716811.0, 15691512.0, nan, 148453584.0], 'RANGE_END': [28797825.0, 57718675.0, 15693551.0, nan, 148455804.0], 'RANGE_STRAND': ['+', '+', '-', nan, '+'], 'GB_ACC': ['NM_173201.2', 'NM_007159.2', 'NM_005924.3', 'NM_006898.4', 'NM_020781.2'], 'ORF': [487.0, 7871.0, 4223.0, 3232.0, 57541.0]}\n",
      "\n",
      "First row as dictionary:\n",
      "ID: cg00000292\n",
      "Name: cg00000292\n",
      "IlmnStrand: TOP\n",
      "AddressA_ID: 990370.0\n",
      "AlleleA_ProbeSeq: AAACATTAATTACCAACCACTCTTCCAAAAAACACTTACCATTAAAACCA\n",
      "AddressB_ID: 6660678.0\n",
      "AlleleB_ProbeSeq: AAACATTAATTACCAACCGCTCTTCCAAAAAACACTTACCATTAAAACCG\n",
      "GenomeBuild: 36.0\n",
      "Chr: 16\n",
      "MapInfo: 28797601.0\n",
      "Ploidy: diploid\n",
      "Species: Homo sapiens\n",
      "Source: NCBI:RefSeq\n",
      "SourceVersion: 36.1\n",
      "SourceStrand: TOP\n",
      "SourceSeq: CGGCCTCAATGGTAAGTGTCCCTTGGAAGAGCGGCTGGTAATTAATGCCC\n",
      "TopGenomicSeq: TGGGGTGAGTGAGACCACGGGCCTCACCCCGGACCAAGTTAAGCGGAATCTGGAGAAATA[CG]GCCTCAATGGTAAGTGTCCCTTGGAAGAGCGGCTGGTAATTAATGCCCTCCTGCACCCCC\n",
      "Next_Base: T\n",
      "Color_Channel: Red\n",
      "TSS_Coordinate: 28797310.0\n",
      "Gene_Strand: +\n",
      "Gene_ID: GeneID:487\n",
      "Symbol: ATP2A1\n",
      "Synonym: ATP2A; SERCA1;\n",
      "Accession: NM_173201.2\n",
      "GID: GI:47132613\n",
      "Annotation: isoform a is encoded by transcript variant a; sarcoplasmic/endoplasmic reticulum calcium ATPase 1; calcium pump 1; SR Ca(2+)-ATPase 1; calcium-transporting ATPase sarcoplasmic reticulum type; fast twitch skeletal muscle isoform; endoplasmic reticulum class 1/2 Ca(2+) ATPase; go_component: membrane; go_component: integral to membrane; go_component: sarcoplasmic reticulum; go_component: smooth endoplasmic reticulum; go_function: ATP binding; go_function: hydrolase activity; go_function: nucleotide binding; go_function: calcium ion binding; go_function: magnesium ion binding; go_function: calcium-transporting ATPase activity; go_function: hydrolase activity; acting on acid anhydrides; catalyzing transmembrane movement of substances; go_process: metabolism; go_process: cation transport; go_process: proton transport; go_process: calcium ion transport; go_process: regulation of striated muscle contraction\n",
      "Product: ATPase; Ca++ transporting; fast twitch 1 isoform a\n",
      "Distance_to_TSS: 291.0\n",
      "CPG_ISLAND: True\n",
      "CPG_ISLAND_LOCATIONS: 16:28797486-28797825\n",
      "MIR_CPG_ISLAND: nan\n",
      "RANGE_GB: NC_000016.8\n",
      "RANGE_START: 28797486.0\n",
      "RANGE_END: 28797825.0\n",
      "RANGE_STRAND: +\n",
      "GB_ACC: NM_173201.2\n",
      "ORF: 487.0\n",
      "\n",
      "Comparing gene data IDs with annotation IDs:\n",
      "First 5 gene data IDs: ['100009676_at', '10000_at', '10001_at', '10002_at', '10003_at']\n",
      "First 5 annotation IDs: ['cg00000292', 'cg00002426', 'cg00003994', 'cg00005847', 'cg00006414']\n",
      "\n",
      "Exact ID match between gene data and annotation:\n",
      "Matching IDs: 19070 out of 19070 (100.00%)\n",
      "\n",
      "Potential columns for gene symbols: ['Name', 'Gene_Strand', 'Gene_ID', 'Symbol']\n",
      "Column 'Name': 922136 non-null values (100.00%)\n",
      "Column 'Gene_Strand': 27578 non-null values (2.99%)\n",
      "Column 'Gene_ID': 27578 non-null values (2.99%)\n",
      "Column 'Symbol': 27551 non-null values (2.99%)\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. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
    "print(\"\\nGene annotation preview:\")\n",
    "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
    "print(preview_df(gene_annotation, n=5))\n",
    "\n",
    "# Check if there are any columns that might contain gene information\n",
    "sample_row = gene_annotation.iloc[0].to_dict()\n",
    "print(\"\\nFirst row as dictionary:\")\n",
    "for col, value in sample_row.items():\n",
    "    print(f\"{col}: {value}\")\n",
    "\n",
    "# Check if IDs in gene_data match IDs in annotation\n",
    "print(\"\\nComparing gene data IDs with annotation IDs:\")\n",
    "print(\"First 5 gene data IDs:\", gene_data.index[:5].tolist())\n",
    "print(\"First 5 annotation IDs:\", gene_annotation['ID'].head().tolist())\n",
    "\n",
    "# Properly check for exact ID matches between gene data and annotation\n",
    "gene_data_ids = set(gene_data.index)\n",
    "annotation_ids = set(gene_annotation['ID'].astype(str))\n",
    "matching_ids = gene_data_ids.intersection(annotation_ids)\n",
    "id_match_percentage = len(matching_ids) / len(gene_data_ids) * 100 if len(gene_data_ids) > 0 else 0\n",
    "\n",
    "print(f\"\\nExact ID match between gene data and annotation:\")\n",
    "print(f\"Matching IDs: {len(matching_ids)} out of {len(gene_data_ids)} ({id_match_percentage:.2f}%)\")\n",
    "\n",
    "# Check which columns might contain gene symbols for mapping\n",
    "potential_gene_symbol_cols = [col for col in gene_annotation.columns \n",
    "                             if any(term in col.upper() for term in ['GENE', 'SYMBOL', 'NAME'])]\n",
    "print(f\"\\nPotential columns for gene symbols: {potential_gene_symbol_cols}\")\n",
    "\n",
    "# Check if the identified columns contain non-null values\n",
    "for col in potential_gene_symbol_cols:\n",
    "    non_null_count = gene_annotation[col].notnull().sum()\n",
    "    non_null_percent = non_null_count / len(gene_annotation) * 100\n",
    "    print(f\"Column '{col}': {non_null_count} non-null values ({non_null_percent:.2f}%)\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "87e441aa",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "8afcbfce",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:55:02.289741Z",
     "iopub.status.busy": "2025-03-25T06:55:02.289624Z",
     "iopub.status.idle": "2025-03-25T06:55:02.362539Z",
     "shell.execute_reply": "2025-03-25T06:55:02.362175Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping shape: (27551, 2)\n",
      "Gene mapping preview:\n",
      "           ID    Gene\n",
      "0  cg00000292  ATP2A1\n",
      "1  cg00002426   SLMAP\n",
      "2  cg00003994   MEOX2\n",
      "3  cg00005847   HOXD3\n",
      "4  cg00006414  ZNF398\n",
      "Gene expression data after mapping: (0, 30)\n",
      "First few genes and their expression values:\n",
      "Empty DataFrame\n",
      "Columns: [GSM3398477, GSM3398478, GSM3398479, GSM3398480, GSM3398481, GSM3398482, GSM3398483, GSM3398484, GSM3398485, GSM3398486, GSM3398487, GSM3398488, GSM3398489, GSM3398490, GSM3398491, GSM3398492, GSM3398493, GSM3398494, GSM3398495, GSM3398496, GSM3398497, GSM3398498, GSM3398499, GSM3398500, GSM3398501, GSM3398502, GSM3398503, GSM3398504, GSM3398505, GSM3398506]\n",
      "Index: []\n",
      "\n",
      "[0 rows x 30 columns]\n",
      "Gene expression data saved to ../../output/preprocess/Bipolar_disorder/gene_data/GSE120342.csv\n"
     ]
    }
   ],
   "source": [
    "# Based on the previous outputs, I can identify:\n",
    "# - Gene data IDs (index) are 'cg' prefixed probes\n",
    "# - 'ID' column in gene_annotation matches these probe IDs\n",
    "# - 'Symbol' column contains the gene symbols we want to map to\n",
    "\n",
    "# 1. Decide the key mappings:\n",
    "probe_id_col = 'ID'       # Column containing methylation probe IDs\n",
    "gene_symbol_col = 'Symbol' # Column containing gene symbols\n",
    "\n",
    "# 2. Extract mapping information using the get_gene_mapping function from the library\n",
    "gene_mapping = get_gene_mapping(gene_annotation, probe_id_col, gene_symbol_col)\n",
    "print(f\"Gene mapping shape: {gene_mapping.shape}\")\n",
    "print(\"Gene mapping preview:\")\n",
    "print(gene_mapping.head())\n",
    "\n",
    "# 3. Apply gene mapping to convert probe-level data to gene expression data\n",
    "# The function will handle the many-to-many mapping and distribution of expression values\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "print(f\"Gene expression data after mapping: {gene_data.shape}\")\n",
    "print(\"First few genes and their expression values:\")\n",
    "print(gene_data.head())\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": "8ae1852e",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "1b547f4a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:55:02.363811Z",
     "iopub.status.busy": "2025-03-25T06:55:02.363697Z",
     "iopub.status.idle": "2025-03-25T06:55:02.435019Z",
     "shell.execute_reply": "2025-03-25T06:55:02.434617Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape after normalization: (0, 30)\n",
      "Normalized gene expression data saved to ../../output/preprocess/Bipolar_disorder/gene_data/GSE120342.csv\n",
      "Clinical data from previous steps:\n",
      "Selected clinical data shape: (1, 2)\n",
      "Clinical data preview:\n",
      "                    0   1\n",
      "Bipolar_disorder  0.0 NaN\n",
      "Gene data columns (samples): ['GSM3398477', 'GSM3398478', 'GSM3398479', 'GSM3398480', 'GSM3398481']...\n",
      "Clinical data indices: ['Bipolar_disorder']\n",
      "Transposed clinical data:\n",
      "   Bipolar_disorder\n",
      "0               0.0\n",
      "1               NaN\n",
      "Gene data columns match GSM pattern: True\n",
      "Created simple clinical dataframe:\n",
      "            Bipolar_disorder\n",
      "GSM3398477                 0\n",
      "GSM3398478                 0\n",
      "GSM3398479                 0\n",
      "GSM3398480                 0\n",
      "GSM3398481                 0\n",
      "GSM3398482                 0\n",
      "GSM3398483                 0\n",
      "GSM3398484                 0\n",
      "GSM3398485                 0\n",
      "GSM3398486                 0\n",
      "GSM3398487                 0\n",
      "GSM3398488                 0\n",
      "GSM3398489                 0\n",
      "GSM3398490                 0\n",
      "GSM3398491                 0\n",
      "GSM3398492                 0\n",
      "GSM3398493                 0\n",
      "GSM3398494                 0\n",
      "GSM3398495                 0\n",
      "GSM3398496                 0\n",
      "GSM3398497                 0\n",
      "GSM3398498                 0\n",
      "GSM3398499                 0\n",
      "GSM3398500                 0\n",
      "GSM3398501                 0\n",
      "GSM3398502                 0\n",
      "GSM3398503                 0\n",
      "GSM3398504                 0\n",
      "GSM3398505                 0\n",
      "GSM3398506                 0\n",
      "Linked data shape: (30, 1)\n",
      "Linked data preview (first 5 rows, 5 columns):\n",
      "           Bipolar_disorder\n",
      "GSM3398477                0\n",
      "GSM3398478                0\n",
      "GSM3398479                0\n",
      "GSM3398480                0\n",
      "GSM3398481                0\n",
      "Data shape after handling missing values: (0, 1)\n",
      "Quartiles for 'Bipolar_disorder':\n",
      "  25%: nan\n",
      "  50% (Median): nan\n",
      "  75%: nan\n",
      "Min: nan\n",
      "Max: nan\n",
      "The distribution of the feature 'Bipolar_disorder' in this dataset is fine.\n",
      "\n",
      "Abnormality detected in the cohort: GSE120342. Preprocessing failed.\n",
      "Dataset is not usable for analysis. No linked data file saved.\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Gene data shape after normalization: {gene_data.shape}\")\n",
    "\n",
    "# Save the normalized gene data to file\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Normalized gene expression data saved to {out_gene_data_file}\")\n",
    "\n",
    "# 2. Link the clinical and genetic data\n",
    "# First check the clinical data structure\n",
    "print(\"Clinical data from previous steps:\")\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",
    "print(f\"Selected clinical data shape: {selected_clinical_df.shape}\")\n",
    "print(\"Clinical data preview:\")\n",
    "print(selected_clinical_df)\n",
    "\n",
    "# Check sample compatibility\n",
    "gene_samples = set(gene_data.columns)\n",
    "clinical_indices = set(selected_clinical_df.index)\n",
    "print(f\"Gene data columns (samples): {list(gene_data.columns)[:5]}...\")\n",
    "print(f\"Clinical data indices: {list(clinical_indices)}\")\n",
    "\n",
    "# Transpose clinical data to get it in the right format (features as rows)\n",
    "clinical_df_t = selected_clinical_df.T\n",
    "print(\"Transposed clinical data:\")\n",
    "print(clinical_df_t)\n",
    "\n",
    "# Since the clinical data does not match the gene samples, we need to check the structure\n",
    "# By checking the SOFT file content, we can see if there's better sample metadata\n",
    "# Check if the sample identifiers in gene_data match GSM IDs\n",
    "gsm_pattern = re.compile(r'GSM\\d+')\n",
    "gene_sample_matches = [bool(gsm_pattern.match(col)) for col in gene_data.columns]\n",
    "print(f\"Gene data columns match GSM pattern: {all(gene_sample_matches)}\")\n",
    "\n",
    "# Try to create a simple clinical DataFrame with trait data for all gene samples\n",
    "if all(gene_sample_matches):\n",
    "    # Extract the original BD status from sample characteristics\n",
    "    bd_status = clinical_data.iloc[0].map(lambda x: 1 if isinstance(x, str) and 'BD' in x else 0)\n",
    "    \n",
    "    # Create a new clinical dataframe with gene samples\n",
    "    new_clinical_df = pd.DataFrame({trait: 0}, index=gene_data.columns)\n",
    "    # Set BD samples to 1\n",
    "    for sample in gene_data.columns:\n",
    "        if 'BD' in str(clinical_data.get(sample, '')):\n",
    "            new_clinical_df.loc[sample, trait] = 1\n",
    "    \n",
    "    print(\"Created simple clinical dataframe:\")\n",
    "    print(new_clinical_df)\n",
    "    \n",
    "    # Link clinical and genetic data with the new clinical dataframe\n",
    "    linked_data = geo_link_clinical_genetic_data(new_clinical_df.T, gene_data)\n",
    "else:\n",
    "    # Create a dummy clinical dataframe with all samples labeled as cases (1)\n",
    "    # This is a fallback approach when metadata is insufficient\n",
    "    print(\"Creating dummy clinical data for gene samples\")\n",
    "    dummy_clinical_df = pd.DataFrame({trait: 1}, index=gene_data.columns)\n",
    "    linked_data = geo_link_clinical_genetic_data(dummy_clinical_df.T, gene_data)\n",
    "\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "print(\"Linked data preview (first 5 rows, 5 columns):\")\n",
    "print(linked_data.iloc[:5, :5] if not linked_data.empty else \"Linked data is empty\")\n",
    "\n",
    "# 3. Handle missing values\n",
    "linked_data = handle_missing_values(linked_data, trait)\n",
    "print(f\"Data shape after handling missing values: {linked_data.shape}\")\n",
    "\n",
    "# 4. Check for bias in features\n",
    "try:\n",
    "    is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "except Exception as e:\n",
    "    print(f\"Error checking for bias: {e}\")\n",
    "    is_biased = True  # Assume biased if there's an error\n",
    "\n",
    "# 5. Validate and save 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_biased,\n",
    "    df=linked_data,\n",
    "    note=\"SuperSeries with DNA methylation data mapped to genes. Clinical annotations are limited.\"\n",
    ")\n",
    "\n",
    "# 6. Save the linked data if usable\n",
    "if is_usable and not linked_data.empty:\n",
    "    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "    linked_data.to_csv(out_data_file)\n",
    "    print(f\"Linked data saved to {out_data_file}\")\n",
    "else:\n",
    "    print(\"Dataset is not usable for analysis. No linked data file 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
}