File size: 38,438 Bytes
f88156f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
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
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "025177ce",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:17:46.232619Z",
     "iopub.status.busy": "2025-03-25T08:17:46.232170Z",
     "iopub.status.idle": "2025-03-25T08:17:46.399395Z",
     "shell.execute_reply": "2025-03-25T08:17:46.399034Z"
    }
   },
   "outputs": [],
   "source": [
    "import sys\n",
    "import os\n",
    "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
    "\n",
    "# Path Configuration\n",
    "from tools.preprocess import *\n",
    "\n",
    "# Processing context\n",
    "trait = \"Chronic_kidney_disease\"\n",
    "cohort = \"GSE104948\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Chronic_kidney_disease\"\n",
    "in_cohort_dir = \"../../input/GEO/Chronic_kidney_disease/GSE104948\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Chronic_kidney_disease/GSE104948.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Chronic_kidney_disease/gene_data/GSE104948.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Chronic_kidney_disease/clinical_data/GSE104948.csv\"\n",
    "json_path = \"../../output/preprocess/Chronic_kidney_disease/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "72d95a4e",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "71233c43",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:17:46.400874Z",
     "iopub.status.busy": "2025-03-25T08:17:46.400724Z",
     "iopub.status.idle": "2025-03-25T08:17:46.484068Z",
     "shell.execute_reply": "2025-03-25T08:17:46.483762Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Glomerular Transcriptome from European Renal cDNA Bank subjects and living donors\"\n",
      "!Series_summary\t\"summary : Glomerular Transcriptome from European Renal cDNA Bank subjects and living donors. Samples included in this analysis have been previously analyzed using older CDF definitions and are included under previous GEO submissions - GSE47183 (chronic kidney disease samples), and GSE32591 (IgA nephropathy samples).  \"\n",
      "!Series_overall_design\t\"RNA from the glomerular compartment of was extracted and processed for hybridization on Affymetrix microarrays, annotated using Human Entrez Gene ID custom CDF version 19.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['tissue: Glomeruli from kidney biopsy'], 1: ['diagnosis: Diabetic Nephropathy', 'diagnosis: Focal Segmental Glomerular Sclerosis/Minimal Change Disease', 'diagnosis: Focal Segmental Glomerular Sclerosis', nan, 'diagnosis: Minimal Change Disease', 'diagnosis: ANCA Associated Vasculitis', 'diagnosis: Tumor Nephrectomy']}\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": "7375cc4a",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "89ad30dc",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:17:46.485181Z",
     "iopub.status.busy": "2025-03-25T08:17:46.485073Z",
     "iopub.status.idle": "2025-03-25T08:17:46.495517Z",
     "shell.execute_reply": "2025-03-25T08:17:46.495227Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of selected clinical features:\n",
      "{'GSM1': [1.0], 'GSM2': [0.0], 'GSM3': [0.0], 'GSM4': [1.0], 'GSM5': [0.0], 'GSM6': [1.0], 'GSM7': [1.0], 'GSM8': [1.0], 'GSM9': [1.0]}\n",
      "Clinical data saved to ../../output/preprocess/Chronic_kidney_disease/clinical_data/GSE104948.csv\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import os\n",
    "import json\n",
    "from typing import Optional, Callable, Dict, Any, List\n",
    "\n",
    "# 1. Evaluate gene expression data availability\n",
    "# From the background information, we can see this is an Affymetrix microarray dataset with gene annotation\n",
    "# This suggests gene expression data is available\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Analyze sample characteristics for trait, age, and gender availability\n",
    "\n",
    "# 2.1 Data Availability\n",
    "# From the sample characteristics dictionary, we can see diagnosis information in index 1\n",
    "trait_row = 1  # The diagnosis information is available at index 1\n",
    "age_row = None  # Age information is not available\n",
    "gender_row = None  # Gender information is not available\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "\n",
    "def convert_trait(value):\n",
    "    \"\"\"\n",
    "    Convert diagnosis values to binary indicating presence of chronic kidney disease (CKD).\n",
    "    Diabetic Nephropathy, Hypertensive Nephropathy, IgA Nephropathy, FSGS, \n",
    "    Membranous Glomerulonephropathy and Lupus Nephritis are all forms of CKD.\n",
    "    \"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Categorize the different diagnoses\n",
    "    ckd_diagnoses = [\n",
    "        'Diabetic Nephropathy', \n",
    "        'Hypertensive Nephropathy', \n",
    "        'IgA Nephropathy',\n",
    "        'Focal Segmental Glomerular Sclerosis',\n",
    "        'Membranous Glomerulonephropathy',\n",
    "        'Systemic Lupus Erythematosus'  # Lupus can cause lupus nephritis, a form of CKD\n",
    "    ]\n",
    "    \n",
    "    non_ckd_diagnoses = [\n",
    "        'Minimal Change Disease',  # Typically causes nephrotic syndrome but not chronic kidney failure\n",
    "        'Thin Membrande Disease',  # Typically benign\n",
    "        'Tumor Nephrectomy'        # Control samples from tumor-adjacent normal tissue\n",
    "    ]\n",
    "    \n",
    "    if value in ckd_diagnoses:\n",
    "        return 1  # Has CKD\n",
    "    elif value in non_ckd_diagnoses:\n",
    "        return 0  # Does not have CKD\n",
    "    else:\n",
    "        return None  # Unknown or ambiguous diagnosis\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Placeholder function for age conversion.\"\"\"\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Placeholder function for gender conversion.\"\"\"\n",
    "    return None\n",
    "\n",
    "# 3. Save metadata\n",
    "is_trait_available = trait_row is not None\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. Clinical Feature Extraction\n",
    "if trait_row is not None:\n",
    "    # Since we have the sample characteristics directly from previous output, \n",
    "    # we need to create a DataFrame from this information to pass to geo_select_clinical_features\n",
    "    sample_chars = {0: ['tissue: Glomeruli from kidney biopsy'], \n",
    "                   1: ['diagnosis: Diabetic Nephropathy', \n",
    "                       'diagnosis: Minimal Change Disease', \n",
    "                       'diagnosis: Thin Membrande Disease', \n",
    "                       'diagnosis: Hypertensive Nephropathy', \n",
    "                       'diagnosis: Tumor Nephrectomy', \n",
    "                       'diagnosis: IgA Nephropathy', \n",
    "                       'diagnosis: Focal Segmental Glomerular Sclerosis', \n",
    "                       np.nan, \n",
    "                       'diagnosis: Membranous Glomerulonephropathy', \n",
    "                       'diagnosis: Systemic Lupus Erythematosus']}\n",
    "    \n",
    "    # Create a DataFrame from sample characteristics\n",
    "    # We'll create a transposed structure with columns for each sample and rows for characteristics\n",
    "    chars_df = pd.DataFrame()\n",
    "    \n",
    "    # First, determine how many unique samples we have based on the characteristic values\n",
    "    # We'll assume each unique value in the diagnosis row represents a different sample\n",
    "    unique_diagnoses = [val for val in sample_chars[1] if not pd.isna(val)]\n",
    "    \n",
    "    # Create a column for each unique diagnosis\n",
    "    for i, diagnosis in enumerate(unique_diagnoses):\n",
    "        sample_id = f\"GSM{i+1}\"\n",
    "        sample_data = {}\n",
    "        \n",
    "        # For each characteristic row, assign the corresponding value\n",
    "        for row_idx, values_list in sample_chars.items():\n",
    "            if row_idx == 1:  # Diagnosis row (trait)\n",
    "                sample_data[row_idx] = diagnosis\n",
    "            elif row_idx == 0:  # Tissue row\n",
    "                sample_data[row_idx] = values_list[0]  # Use the first value for all samples\n",
    "        \n",
    "        # Add column to dataframe\n",
    "        chars_df[sample_id] = pd.Series(sample_data)\n",
    "    \n",
    "    # Extract clinical features using the provided function\n",
    "    selected_clinical_df = geo_select_clinical_features(\n",
    "        clinical_df=chars_df,\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 output\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 to CSV\n",
    "    selected_clinical_df.to_csv(out_clinical_data_file)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1d527eed",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "850356e1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:17:46.496562Z",
     "iopub.status.busy": "2025-03-25T08:17:46.496456Z",
     "iopub.status.idle": "2025-03-25T08:17:46.605900Z",
     "shell.execute_reply": "2025-03-25T08:17:46.605506Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SOFT file: ../../input/GEO/Chronic_kidney_disease/GSE104948/GSE104948_family.soft.gz\n",
      "Matrix file: ../../input/GEO/Chronic_kidney_disease/GSE104948/GSE104948-GPL22945_series_matrix.txt.gz\n",
      "Found the matrix table marker in the file.\n",
      "Gene data shape: (12074, 71)\n",
      "First 20 gene/probe identifiers:\n",
      "['10000_at', '10001_at', '10002_at', '10003_at', '100048912_at', '10004_at', '10005_at', '10006_at', '10007_at', '100093698_at', '10009_at', '1000_at', '10010_at', '100126791_at', '100128124_at', '100128640_at', '100129128_at', '100129250_at', '100129271_at', '100129361_at']\n"
     ]
    }
   ],
   "source": [
    "# 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",
    "print(f\"SOFT file: {soft_file}\")\n",
    "print(f\"Matrix file: {matrix_file}\")\n",
    "\n",
    "# Set gene availability flag\n",
    "is_gene_available = True  # Initially assume gene data is available\n",
    "\n",
    "# First check if the matrix file contains the expected marker\n",
    "found_marker = False\n",
    "try:\n",
    "    with gzip.open(matrix_file, 'rt') as file:\n",
    "        for line in file:\n",
    "            if \"!series_matrix_table_begin\" in line:\n",
    "                found_marker = True\n",
    "                break\n",
    "    \n",
    "    if found_marker:\n",
    "        print(\"Found the matrix table marker in the file.\")\n",
    "    else:\n",
    "        print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
    "        \n",
    "    # Try to extract gene data from the matrix file\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    \n",
    "    if gene_data.shape[0] == 0:\n",
    "        print(\"Warning: Extracted gene data has 0 rows.\")\n",
    "        is_gene_available = False\n",
    "    else:\n",
    "        print(f\"Gene data shape: {gene_data.shape}\")\n",
    "        # Print the first 20 gene/probe identifiers\n",
    "        print(\"First 20 gene/probe identifiers:\")\n",
    "        print(gene_data.index[:20].tolist())\n",
    "        \n",
    "except Exception as e:\n",
    "    print(f\"Error extracting gene data: {e}\")\n",
    "    is_gene_available = False\n",
    "    \n",
    "    # Try to diagnose the file format\n",
    "    print(\"Examining file content to diagnose the issue:\")\n",
    "    try:\n",
    "        with gzip.open(matrix_file, 'rt') as file:\n",
    "            for i, line in enumerate(file):\n",
    "                if i < 10:  # Print first 10 lines to diagnose\n",
    "                    print(f\"Line {i}: {line.strip()[:100]}...\")  # Print first 100 chars of each line\n",
    "                else:\n",
    "                    break\n",
    "    except Exception as e2:\n",
    "        print(f\"Error examining file: {e2}\")\n",
    "\n",
    "if not is_gene_available:\n",
    "    print(\"Gene expression data could not be successfully extracted from this dataset.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "613dc991",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "b2081de7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:17:46.607217Z",
     "iopub.status.busy": "2025-03-25T08:17:46.607102Z",
     "iopub.status.idle": "2025-03-25T08:17:46.609051Z",
     "shell.execute_reply": "2025-03-25T08:17:46.608760Z"
    }
   },
   "outputs": [],
   "source": [
    "# Looking at the first 20 gene identifiers provided\n",
    "# These appear to be Affymetrix probe identifiers (e.g., '10000_at', '10001_at')\n",
    "# The '_at' suffix is typical for Affymetrix arrays\n",
    "# These are not standard human gene symbols (like BRCA1, TP53, etc.)\n",
    "# Therefore, mapping to official gene symbols will be required\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "494d2ff3",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "e8379dd0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:17:46.610265Z",
     "iopub.status.busy": "2025-03-25T08:17:46.610163Z",
     "iopub.status.idle": "2025-03-25T08:17:49.458922Z",
     "shell.execute_reply": "2025-03-25T08:17:49.458450Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "Columns in gene annotation: ['ID', 'Symbol', 'SPOT_ID', 'ENTREZ_GENE_ID']\n",
      "{'ID': ['1000_at', '10000_at', '100009676_at', '10001_at', '10004_at'], 'Symbol': ['CDH2', 'AKT3', 'ZBTB11-AS1', 'MED6', 'NAALADL1'], 'SPOT_ID': ['cadherin 2', 'AKT serine/threonine kinase 3', 'ZBTB11 antisense RNA 1', 'mediator complex subunit 6', 'N-acetylated alpha-linked acidic dipeptidase-like 1'], 'ENTREZ_GENE_ID': ['1000', '10000', '100009676', '10001', '10004']}\n",
      "\n",
      "Complete sample of a few rows:\n",
      "             ID      Symbol                        SPOT_ID ENTREZ_GENE_ID\n",
      "0       1000_at        CDH2                     cadherin 2           1000\n",
      "1      10000_at        AKT3  AKT serine/threonine kinase 3          10000\n",
      "2  100009676_at  ZBTB11-AS1         ZBTB11 antisense RNA 1      100009676\n",
      "\n",
      "Potential gene-related columns: ['ID', 'Symbol', 'SPOT_ID', 'ENTREZ_GENE_ID']\n",
      "\n",
      "No direct gene symbol column found. Will use Entrez Gene IDs for mapping.\n",
      "\n",
      "Sample mappings from 'ID' to 'ENTREZ_GENE_ID':\n",
      "             ID ENTREZ_GENE_ID\n",
      "0       1000_at           1000\n",
      "1      10000_at          10000\n",
      "2  100009676_at      100009676\n",
      "3      10001_at          10001\n",
      "4      10004_at          10004\n",
      "5      10005_at          10005\n",
      "6      10006_at          10006\n",
      "7      10007_at          10007\n",
      "8      10008_at          10008\n",
      "9      10009_at          10009\n",
      "\n",
      "Number of probes with gene ID mappings: 31839\n",
      "Sample of valid mappings:\n",
      "             ID ENTREZ_GENE_ID\n",
      "0       1000_at           1000\n",
      "1      10000_at          10000\n",
      "2  100009676_at      100009676\n",
      "3      10001_at          10001\n",
      "4      10004_at          10004\n"
     ]
    }
   ],
   "source": [
    "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\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",
    "# Get a more complete view to understand the annotation structure\n",
    "print(\"\\nComplete sample of a few rows:\")\n",
    "print(gene_annotation.iloc[:3].to_string())\n",
    "\n",
    "# Check if there are any columns that might contain gene information beyond what we've seen\n",
    "potential_gene_columns = [col for col in gene_annotation.columns if \n",
    "                          any(term in col.upper() for term in [\"GENE\", \"SYMBOL\", \"NAME\", \"ID\"])]\n",
    "print(f\"\\nPotential gene-related columns: {potential_gene_columns}\")\n",
    "\n",
    "# Look for additional columns that might contain gene symbols\n",
    "# Since we only have 'ID' and 'ENTREZ_GENE_ID', check if we need to use Entrez IDs for mapping\n",
    "gene_id_col = 'ID'\n",
    "gene_symbol_col = None\n",
    "\n",
    "# Check various potential column names for gene symbols\n",
    "for col_name in ['GENE_SYMBOL', 'SYMBOL', 'GENE', 'GENE_NAME', 'GB_ACC']:\n",
    "    if col_name in gene_annotation.columns:\n",
    "        gene_symbol_col = col_name\n",
    "        break\n",
    "\n",
    "# If no dedicated symbol column is found, we'll need to use ENTREZ_GENE_ID\n",
    "if gene_symbol_col is None and 'ENTREZ_GENE_ID' in gene_annotation.columns:\n",
    "    gene_symbol_col = 'ENTREZ_GENE_ID'\n",
    "    print(\"\\nNo direct gene symbol column found. Will use Entrez Gene IDs for mapping.\")\n",
    "\n",
    "if gene_id_col in gene_annotation.columns and gene_symbol_col is not None:\n",
    "    print(f\"\\nSample mappings from '{gene_id_col}' to '{gene_symbol_col}':\")\n",
    "    sample_mappings = gene_annotation[[gene_id_col, gene_symbol_col]].head(10)\n",
    "    print(sample_mappings)\n",
    "    \n",
    "    # Check for non-null mappings to confirm data quality\n",
    "    non_null_mappings = gene_annotation[[gene_id_col, gene_symbol_col]].dropna(subset=[gene_symbol_col])\n",
    "    print(f\"\\nNumber of probes with gene ID mappings: {len(non_null_mappings)}\")\n",
    "    print(f\"Sample of valid mappings:\")\n",
    "    print(non_null_mappings.head(5))\n",
    "else:\n",
    "    print(\"Required mapping columns not found in the annotation data. Will need to explore alternative mapping approaches.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0175951a",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "f4db7562",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:17:49.460435Z",
     "iopub.status.busy": "2025-03-25T08:17:49.460308Z",
     "iopub.status.idle": "2025-03-25T08:17:54.525123Z",
     "shell.execute_reply": "2025-03-25T08:17:54.524721Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping shape: (2398539, 2)\n",
      "Sample of gene mapping:\n",
      "             ID        Gene\n",
      "0       1000_at        CDH2\n",
      "1      10000_at        AKT3\n",
      "2  100009676_at  ZBTB11-AS1\n",
      "3      10001_at        MED6\n",
      "4      10004_at    NAALADL1\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape after mapping: (11996, 71)\n",
      "First few genes after mapping:\n",
      "['A1CF', 'A2M', 'A4GALT', 'A4GNT', 'AAAS', 'AACS', 'AADAC', 'AAGAB', 'AAK1', 'AAMDC']\n",
      "Gene data shape after normalization: (11965, 71)\n",
      "Number of unique genes in the processed data: 11965\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data saved to ../../output/preprocess/Chronic_kidney_disease/gene_data/GSE104948.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Determine which columns in gene annotation store the gene identifiers and symbols\n",
    "gene_id_col = 'ID'  # The probe identifiers (e.g., 10000_at)\n",
    "gene_symbol_col = 'Symbol'  # The column containing gene symbols (e.g., AKT3)\n",
    "\n",
    "# 2. Extract the mapping between probe IDs and gene symbols\n",
    "gene_mapping = get_gene_mapping(gene_annotation, gene_id_col, gene_symbol_col)\n",
    "print(f\"Gene mapping shape: {gene_mapping.shape}\")\n",
    "print(\"Sample of gene mapping:\")\n",
    "print(gene_mapping.head())\n",
    "\n",
    "# 3. Apply the gene mapping to convert from probe-level to gene-level expression\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "print(f\"Gene data shape after mapping: {gene_data.shape}\")\n",
    "print(\"First few genes after mapping:\")\n",
    "print(gene_data.index[:10].tolist())\n",
    "\n",
    "# Normalize gene symbols to handle synonyms and aggregate values for same genes\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Gene data shape after normalization: {gene_data.shape}\")\n",
    "\n",
    "# Check how many unique genes we have in the processed data\n",
    "print(f\"Number of unique genes in the processed data: {len(gene_data.index)}\")\n",
    "\n",
    "# Save the gene expression 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\"Gene data saved to {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "72ffc4e8",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "95e49c11",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:17:54.526530Z",
     "iopub.status.busy": "2025-03-25T08:17:54.526414Z",
     "iopub.status.idle": "2025-03-25T08:17:58.217697Z",
     "shell.execute_reply": "2025-03-25T08:17:58.217299Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Loaded gene data shape: (11965, 71)\n",
      "Gene data already normalized with shape: (11965, 71)\n",
      "Clinical data from source:\n",
      "         !Sample_geo_accession                            GSM2810770  \\\n",
      "0  !Sample_characteristics_ch1  tissue: Glomeruli from kidney biopsy   \n",
      "1  !Sample_characteristics_ch1       diagnosis: Diabetic Nephropathy   \n",
      "\n",
      "                             GSM2810771                            GSM2810772  \\\n",
      "0  tissue: Glomeruli from kidney biopsy  tissue: Glomeruli from kidney biopsy   \n",
      "1       diagnosis: Diabetic Nephropathy       diagnosis: Diabetic Nephropathy   \n",
      "\n",
      "                             GSM2810773                            GSM2810774  \\\n",
      "0  tissue: Glomeruli from kidney biopsy  tissue: Glomeruli from kidney biopsy   \n",
      "1       diagnosis: Diabetic Nephropathy       diagnosis: Diabetic Nephropathy   \n",
      "\n",
      "                             GSM2810775                            GSM2810776  \\\n",
      "0  tissue: Glomeruli from kidney biopsy  tissue: Glomeruli from kidney biopsy   \n",
      "1       diagnosis: Diabetic Nephropathy       diagnosis: Diabetic Nephropathy   \n",
      "\n",
      "                                          GSM2810777  \\\n",
      "0               tissue: Glomeruli from kidney biopsy   \n",
      "1  diagnosis: Focal Segmental Glomerular Sclerosi...   \n",
      "\n",
      "                                          GSM2810778  ...  \\\n",
      "0               tissue: Glomeruli from kidney biopsy  ...   \n",
      "1  diagnosis: Focal Segmental Glomerular Sclerosi...  ...   \n",
      "\n",
      "                              GSM2810831  \\\n",
      "0   tissue: Glomeruli from kidney biopsy   \n",
      "1  diagnosis: ANCA Associated Vasculitis   \n",
      "\n",
      "                              GSM2810832  \\\n",
      "0   tissue: Glomeruli from kidney biopsy   \n",
      "1  diagnosis: ANCA Associated Vasculitis   \n",
      "\n",
      "                              GSM2810833  \\\n",
      "0   tissue: Glomeruli from kidney biopsy   \n",
      "1  diagnosis: ANCA Associated Vasculitis   \n",
      "\n",
      "                              GSM2810834  \\\n",
      "0   tissue: Glomeruli from kidney biopsy   \n",
      "1  diagnosis: ANCA Associated Vasculitis   \n",
      "\n",
      "                              GSM2810835  \\\n",
      "0   tissue: Glomeruli from kidney biopsy   \n",
      "1  diagnosis: ANCA Associated Vasculitis   \n",
      "\n",
      "                              GSM2810836  \\\n",
      "0   tissue: Glomeruli from kidney biopsy   \n",
      "1  diagnosis: ANCA Associated Vasculitis   \n",
      "\n",
      "                              GSM2810837  \\\n",
      "0   tissue: Glomeruli from kidney biopsy   \n",
      "1  diagnosis: ANCA Associated Vasculitis   \n",
      "\n",
      "                             GSM2810838                            GSM2810839  \\\n",
      "0  tissue: Glomeruli from kidney biopsy  tissue: Glomeruli from kidney biopsy   \n",
      "1          diagnosis: Tumor Nephrectomy          diagnosis: Tumor Nephrectomy   \n",
      "\n",
      "                             GSM2810840  \n",
      "0  tissue: Glomeruli from kidney biopsy  \n",
      "1          diagnosis: Tumor Nephrectomy  \n",
      "\n",
      "[2 rows x 72 columns]\n",
      "Found 2 sample IDs in the matrix file\n",
      "Sample IDs (first 5): ['!Sample_characteristics_ch1', '!Sample_characteristics_ch1']\n",
      "Extracted clinical data shape: (1, 71)\n",
      "Preview of trait data:\n",
      "                        GSM2810770  GSM2810771  GSM2810772  GSM2810773  \\\n",
      "Chronic_kidney_disease         1.0         1.0         1.0         1.0   \n",
      "\n",
      "                        GSM2810774  GSM2810775  GSM2810776  GSM2810777  \\\n",
      "Chronic_kidney_disease         1.0         1.0         1.0         NaN   \n",
      "\n",
      "                        GSM2810778  GSM2810779  ...  GSM2810831  GSM2810832  \\\n",
      "Chronic_kidney_disease         NaN         NaN  ...         NaN         NaN   \n",
      "\n",
      "                        GSM2810833  GSM2810834  GSM2810835  GSM2810836  \\\n",
      "Chronic_kidney_disease         NaN         NaN         NaN         NaN   \n",
      "\n",
      "                        GSM2810837  GSM2810838  GSM2810839  GSM2810840  \n",
      "Chronic_kidney_disease         NaN         0.0         0.0         0.0  \n",
      "\n",
      "[1 rows x 71 columns]\n",
      "Updated clinical data saved to ../../output/preprocess/Chronic_kidney_disease/clinical_data/GSE104948.csv\n",
      "Found 71 common samples between gene and clinical data\n",
      "Linked data shape: (71, 11966)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data shape after handling missing values: (25, 11966)\n",
      "For the feature 'Chronic_kidney_disease', the least common label is '0.0' with 8 occurrences. This represents 32.00% of the dataset.\n",
      "The distribution of the feature 'Chronic_kidney_disease' in this dataset is fine.\n",
      "\n",
      "A new JSON file was created at: ../../output/preprocess/Chronic_kidney_disease/cohort_info.json\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Chronic_kidney_disease/GSE104948.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "try:\n",
    "    gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n",
    "    print(f\"Loaded gene data shape: {gene_data.shape}\")\n",
    "    \n",
    "    # Gene normalization was already applied in the previous step\n",
    "    print(f\"Gene data already normalized with shape: {gene_data.shape}\")\n",
    "    is_gene_available = True\n",
    "except Exception as e:\n",
    "    print(f\"Error loading gene data: {e}\")\n",
    "    is_gene_available = False\n",
    "\n",
    "# 2. Load the original data sources to properly extract sample IDs and clinical data\n",
    "try:\n",
    "    # Get file paths\n",
    "    soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "    \n",
    "    # Extract properly formatted clinical data directly from source\n",
    "    background_info, clinical_df = get_background_and_clinical_data(matrix_file)\n",
    "    \n",
    "    # Check the first few rows to understand the data structure\n",
    "    print(\"Clinical data from source:\")\n",
    "    print(clinical_df.head(3))\n",
    "    \n",
    "    # Get the sample accession IDs that will match gene data column names\n",
    "    sample_ids = clinical_df['!Sample_geo_accession'].tolist()\n",
    "    print(f\"Found {len(sample_ids)} sample IDs in the matrix file\")\n",
    "    print(f\"Sample IDs (first 5): {sample_ids[:5]}\")\n",
    "    \n",
    "    # Create proper clinical data with trait information\n",
    "    trait_data = geo_select_clinical_features(\n",
    "        clinical_df=clinical_df,\n",
    "        trait=trait,\n",
    "        trait_row=1,  # Based on previous analysis\n",
    "        convert_trait=convert_trait,\n",
    "        age_row=None,\n",
    "        convert_age=None,\n",
    "        gender_row=None,\n",
    "        convert_gender=None\n",
    "    )\n",
    "    \n",
    "    print(f\"Extracted clinical data shape: {trait_data.shape}\")\n",
    "    print(\"Preview of trait data:\")\n",
    "    print(trait_data.head())\n",
    "    \n",
    "    # Save the properly extracted clinical data\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    trait_data.to_csv(out_clinical_data_file)\n",
    "    print(f\"Updated clinical data saved to {out_clinical_data_file}\")\n",
    "    \n",
    "    is_trait_available = True\n",
    "except Exception as e:\n",
    "    print(f\"Error extracting clinical data: {e}\")\n",
    "    is_trait_available = False\n",
    "\n",
    "# 3. Link clinical and genetic data if both are available\n",
    "if is_trait_available and is_gene_available:\n",
    "    try:\n",
    "        # Check that gene_data columns match sample_ids from clinical data\n",
    "        common_samples = set(gene_data.columns).intersection(trait_data.columns)\n",
    "        print(f\"Found {len(common_samples)} common samples between gene and clinical data\")\n",
    "        \n",
    "        if len(common_samples) > 0:\n",
    "            # Filter gene data to include only common samples\n",
    "            gene_data_filtered = gene_data[list(common_samples)]\n",
    "            # Filter trait data to include only common samples\n",
    "            trait_data_filtered = trait_data[list(common_samples)]\n",
    "            \n",
    "            # Perform the linking\n",
    "            linked_data = geo_link_clinical_genetic_data(trait_data_filtered, gene_data_filtered)\n",
    "            print(f\"Linked data shape: {linked_data.shape}\")\n",
    "            \n",
    "            # Handle missing values\n",
    "            linked_data = handle_missing_values(linked_data, trait)\n",
    "            print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
    "            \n",
    "            # Check for bias in trait and demographic features\n",
    "            is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "            \n",
    "            # Validate the data quality and save cohort info\n",
    "            note = \"Dataset contains gene expression data from kidney glomeruli of patients with various kidney conditions including diabetic nephropathy, IgA nephropathy, and other kidney diseases.\"\n",
    "            is_usable = validate_and_save_cohort_info(\n",
    "                is_final=True,\n",
    "                cohort=cohort,\n",
    "                info_path=json_path,\n",
    "                is_gene_available=is_gene_available,\n",
    "                is_trait_available=is_trait_available,\n",
    "                is_biased=is_biased,\n",
    "                df=linked_data,\n",
    "                note=note\n",
    "            )\n",
    "            \n",
    "            # Save the linked data if it's usable\n",
    "            if is_usable:\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(\"Data not usable for the trait study - not saving final linked data.\")\n",
    "        else:\n",
    "            print(\"No common samples found between gene expression and clinical data.\")\n",
    "            validate_and_save_cohort_info(\n",
    "                is_final=True,\n",
    "                cohort=cohort,\n",
    "                info_path=json_path,\n",
    "                is_gene_available=is_gene_available,\n",
    "                is_trait_available=is_trait_available,\n",
    "                is_biased=True,\n",
    "                df=pd.DataFrame(),\n",
    "                note=\"No common samples between gene expression and clinical data.\"\n",
    "            )\n",
    "    except Exception as e:\n",
    "        print(f\"Error linking or processing data: {e}\")\n",
    "        validate_and_save_cohort_info(\n",
    "            is_final=True,\n",
    "            cohort=cohort,\n",
    "            info_path=json_path,\n",
    "            is_gene_available=is_gene_available,\n",
    "            is_trait_available=is_trait_available,\n",
    "            is_biased=True,  # Assume biased if there's an error\n",
    "            df=pd.DataFrame(),  # Empty dataframe for metadata\n",
    "            note=f\"Error in data processing: {str(e)}\"\n",
    "        )\n",
    "else:\n",
    "    # We can't proceed with linking if either trait or gene data is missing\n",
    "    print(\"Cannot proceed with data linking due to missing trait or gene data.\")\n",
    "    validate_and_save_cohort_info(\n",
    "        is_final=True,\n",
    "        cohort=cohort,\n",
    "        info_path=json_path,\n",
    "        is_gene_available=is_gene_available,\n",
    "        is_trait_available=is_trait_available,\n",
    "        is_biased=True,  # Data is unusable if we're missing components\n",
    "        df=pd.DataFrame(),  # Empty dataframe for metadata\n",
    "        note=\"Missing essential data components for linking (trait data or gene expression data).\"\n",
    "    )"
   ]
  }
 ],
 "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
}