File size: 30,203 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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "156b8f30",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:19:00.766010Z",
     "iopub.status.busy": "2025-03-25T08:19:00.765586Z",
     "iopub.status.idle": "2025-03-25T08:19:00.930281Z",
     "shell.execute_reply": "2025-03-25T08:19:00.929947Z"
    }
   },
   "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 = \"GSE45980\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Chronic_kidney_disease\"\n",
    "in_cohort_dir = \"../../input/GEO/Chronic_kidney_disease/GSE45980\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Chronic_kidney_disease/GSE45980.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Chronic_kidney_disease/gene_data/GSE45980.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Chronic_kidney_disease/clinical_data/GSE45980.csv\"\n",
    "json_path = \"../../output/preprocess/Chronic_kidney_disease/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4788314a",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "7b9710f4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:19:00.931664Z",
     "iopub.status.busy": "2025-03-25T08:19:00.931531Z",
     "iopub.status.idle": "2025-03-25T08:19:00.972631Z",
     "shell.execute_reply": "2025-03-25T08:19:00.972346Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"An integrative analysis of renal miRNA- and mRNA-expression signatures in progressive chronic kidney disease [discovery cohort]\"\n",
      "!Series_summary\t\"MicroRNAs (miRNAs) significantly contribute to chronic kidney disease (CKD) progression via regulating mRNA expression and abundance. However, their association with clinical outcome remains poorly understood. We performed large scale miRNA and mRNA expression profiling on cryo-cut renal biopsy sections from n=43 subjects. miRNAs differentiating stable and progressive cases were determined, and putative target mRNAs showing inversely correlated expression profiles were identified and further characterized. We found a downregulation of 7 miRNAs in the progressive phenotype, and an upregulation of 29 target mRNAs which are involved in inflammatory response, cell-cell-interaction, apoptosis, and intracellular signaling. Particularly a diminished expression of miR-206 in progressive disease correlated significantly with the upregulation of the target mRNAs CCL19, CXCL1, IFNAR2, NCK2, PTK2B, PTPRC, RASGRP1, and TNFRSF25, all participating in inflammatory pathways. Progressive cases also showed a decreased expression of miR-532-3p, and an increased expression of target transcripts MAP3K14, TNFRSF10B/TRAIL-R2, TRADD, and TRAF2, all being involved in apoptosis pathways. miR-206, miR-532-3p and all 12 mRNA targets correlated with the degree of histological damage. \"\n",
      "!Series_summary\t\"The identified renal miRNA- and mRNA-profiles, and biological pathways may represent regulatory mechanisms, which are commonly present in various kinds of progressive chronic kidney disease.\"\n",
      "!Series_overall_design\t\"mRNA- and miRNA-profiling was performed on renal biopsy samples from human subjects with various proteinuric nephropathies, miRNA-mRNA correlations were identified for those subjects who showed a progressive decline of renal function during follow up.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['gender: male', 'gender: female'], 1: ['age (yrs): 72', 'age (yrs): 20', 'age (yrs): 64', 'age (yrs): 17', 'age (yrs): 46', 'age (yrs): 55', 'age (yrs): 74', 'age (yrs): 49', 'age (yrs): 42', 'age (yrs): 73', 'age (yrs): 63', 'age (yrs): 33', 'age (yrs): 24', 'age (yrs): 45', 'age (yrs): 70', 'age (yrs): 60', 'age (yrs): 67', 'age (yrs): 31', 'age (yrs): 53', 'age (yrs): 22', 'age (yrs): 54', 'age (yrs): 40', 'age (yrs): 38', 'age (yrs): 19', 'age (yrs): 28', 'age (yrs): 65', 'age (yrs): 58', 'age (yrs): 56', 'age (yrs): 34', 'age (yrs): 59'], 2: ['diagnosis: Diabetic Nephropathy', 'diagnosis: Focal-Segmental Glomerulosclerosis', 'diagnosis: Hypertensive Nephropathy', 'diagnosis: IgA-Nephropathy', 'diagnosis: Membranous Nephropathy', 'diagnosis: Minimal-Change Disease', 'diagnosis: Other/Unknown'], 3: ['clinical course: stable', 'clinical course: progressive']}\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": "c36c0824",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "373844ab",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:19:00.973648Z",
     "iopub.status.busy": "2025-03-25T08:19:00.973546Z",
     "iopub.status.idle": "2025-03-25T08:19:00.984064Z",
     "shell.execute_reply": "2025-03-25T08:19:00.983792Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of extracted clinical features:\n",
      "{'GSM1121040': [0.0, 72.0, 1.0], 'GSM1121041': [0.0, 20.0, 0.0], 'GSM1121042': [0.0, 64.0, 0.0], 'GSM1121043': [0.0, 17.0, 1.0], 'GSM1121044': [0.0, 46.0, 1.0], 'GSM1121045': [0.0, 55.0, 1.0], 'GSM1121046': [0.0, 74.0, 1.0], 'GSM1121047': [0.0, 49.0, 1.0], 'GSM1121048': [0.0, 20.0, 1.0], 'GSM1121049': [0.0, 42.0, 1.0], 'GSM1121050': [0.0, 73.0, 0.0], 'GSM1121051': [0.0, 63.0, 0.0], 'GSM1121052': [0.0, 33.0, 0.0], 'GSM1121053': [0.0, 74.0, 1.0], 'GSM1121054': [0.0, 24.0, 1.0], 'GSM1121055': [0.0, 45.0, 1.0], 'GSM1121056': [0.0, 70.0, 1.0], 'GSM1121057': [0.0, 60.0, 1.0], 'GSM1121058': [0.0, 67.0, 0.0], 'GSM1121059': [0.0, 31.0, 0.0], 'GSM1121060': [0.0, 53.0, 0.0], 'GSM1121061': [0.0, 67.0, 0.0], 'GSM1121062': [0.0, 22.0, 0.0], 'GSM1121063': [0.0, 54.0, 0.0], 'GSM1121064': [0.0, 40.0, 1.0], 'GSM1121065': [0.0, 38.0, 0.0], 'GSM1121066': [0.0, 19.0, 1.0], 'GSM1121067': [0.0, 28.0, 0.0], 'GSM1121068': [0.0, 65.0, 1.0], 'GSM1121069': [0.0, 74.0, 1.0], 'GSM1121070': [0.0, 65.0, 1.0], 'GSM1121071': [1.0, 54.0, 1.0], 'GSM1121072': [1.0, 58.0, 1.0], 'GSM1121073': [1.0, 56.0, 1.0], 'GSM1121074': [1.0, 34.0, 1.0], 'GSM1121075': [1.0, 31.0, 1.0], 'GSM1121076': [1.0, 64.0, 0.0], 'GSM1121077': [1.0, 59.0, 1.0], 'GSM1121078': [1.0, 70.0, 1.0], 'GSM1121079': [1.0, 58.0, 1.0], 'GSM1121080': [1.0, 67.0, 0.0], 'GSM1121081': [1.0, 54.0, 1.0], 'GSM1121082': [1.0, 61.0, 1.0]}\n",
      "Clinical features saved to ../../output/preprocess/Chronic_kidney_disease/clinical_data/GSE45980.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information, this dataset contains mRNA expression profiling\n",
    "# which is suitable for our study\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "\n",
    "# 2.1 Data Availability\n",
    "# For trait: The key is 3, which refers to \"clinical course: stable/progressive\"\n",
    "# For age: The key is 1, which contains \"age (yrs): X\"\n",
    "# For gender: The key is 0, which contains \"gender: male/female\"\n",
    "trait_row = 3\n",
    "age_row = 1\n",
    "gender_row = 0\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait (clinical course) to binary.\"\"\"\n",
    "    if pd.isna(value) or value is None:\n",
    "        return None\n",
    "    value = value.lower()\n",
    "    if \"clinical course:\" in value:\n",
    "        value = value.split(\"clinical course:\")[1].strip()\n",
    "    \n",
    "    if \"progressive\" in value:\n",
    "        return 1  # Progressive CKD\n",
    "    elif \"stable\" in value:\n",
    "        return 0  # Stable CKD\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age to continuous numeric value.\"\"\"\n",
    "    if pd.isna(value) or value is None:\n",
    "        return None\n",
    "    try:\n",
    "        if \"age (yrs):\" in value:\n",
    "            age_str = value.split(\"age (yrs):\")[1].strip()\n",
    "            return float(age_str)\n",
    "        return None\n",
    "    except:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender to binary (0 for female, 1 for male).\"\"\"\n",
    "    if pd.isna(value) or value is None:\n",
    "        return None\n",
    "    value = value.lower()\n",
    "    if \"gender:\" in value:\n",
    "        value = value.split(\"gender:\")[1].strip()\n",
    "    \n",
    "    if \"female\" in value:\n",
    "        return 0\n",
    "    elif \"male\" in value:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait data availability\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",
    "    # Extract clinical features\n",
    "    clinical_features = geo_select_clinical_features(\n",
    "        clinical_df=clinical_data,\n",
    "        trait=trait,\n",
    "        trait_row=trait_row,\n",
    "        convert_trait=convert_trait,\n",
    "        age_row=age_row,\n",
    "        convert_age=convert_age,\n",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender\n",
    "    )\n",
    "    \n",
    "    # Preview the extracted clinical features\n",
    "    print(\"Preview of extracted clinical features:\")\n",
    "    print(preview_df(clinical_features))\n",
    "    \n",
    "    # Save the clinical features to a CSV file\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 features saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5ae47aa3",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "f251d609",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:19:00.984988Z",
     "iopub.status.busy": "2025-03-25T08:19:00.984889Z",
     "iopub.status.idle": "2025-03-25T08:19:01.020778Z",
     "shell.execute_reply": "2025-03-25T08:19:01.020481Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SOFT file: ../../input/GEO/Chronic_kidney_disease/GSE45980/GSE45980_family.soft.gz\n",
      "Matrix file: ../../input/GEO/Chronic_kidney_disease/GSE45980/GSE45980_series_matrix.txt.gz\n",
      "Gene data shape: (9665, 43)\n",
      "First 20 gene/probe identifiers:\n",
      "['A_23_P100001', 'A_23_P100240', 'A_23_P100315', 'A_23_P100326', 'A_23_P100355', 'A_23_P100392', 'A_23_P100486', 'A_23_P100501', 'A_23_P100660', 'A_23_P100704', 'A_23_P100764', 'A_23_P100963', 'A_23_P101111', 'A_23_P101332', 'A_23_P10135', 'A_23_P101407', 'A_23_P101480', 'A_23_P101516', 'A_23_P101532', 'A_23_P101551']\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  # Assume gene data is available\n",
    "\n",
    "# Extract gene data\n",
    "try:\n",
    "    # Extract gene data from the matrix file\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    print(f\"Gene data shape: {gene_data.shape}\")\n",
    "    \n",
    "    # Print the first 20 gene/probe identifiers\n",
    "    print(\"First 20 gene/probe identifiers:\")\n",
    "    print(gene_data.index[:20].tolist())\n",
    "except Exception as e:\n",
    "    print(f\"Error extracting gene data: {e}\")\n",
    "    print(f\"File path: {matrix_file}\")\n",
    "    print(\"Please check if the file exists and contains the expected markers.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0a0cd049",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "17781454",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:19:01.021786Z",
     "iopub.status.busy": "2025-03-25T08:19:01.021682Z",
     "iopub.status.idle": "2025-03-25T08:19:01.023401Z",
     "shell.execute_reply": "2025-03-25T08:19:01.023141Z"
    }
   },
   "outputs": [],
   "source": [
    "# The identifiers like 'A_23_P100001' are probe IDs from Agilent microarrays\n",
    "# They are not human gene symbols and require mapping to gene symbols\n",
    "# These are specific probe identifiers used in Agilent microarray platforms\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d25dca25",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "e0dc13a8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:19:01.024372Z",
     "iopub.status.busy": "2025-03-25T08:19:01.024274Z",
     "iopub.status.idle": "2025-03-25T08:19:01.933183Z",
     "shell.execute_reply": "2025-03-25T08:19:01.932800Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "Columns in gene annotation: ['ID', 'SPOT_ID', 'CONTROL_TYPE', 'REFSEQ', 'GB_ACC', 'GENE', 'GENE_SYMBOL', 'GENE_NAME', 'UNIGENE_ID', 'ENSEMBL_ID', 'TIGR_ID', 'ACCESSION_STRING', 'CHROMOSOMAL_LOCATION', 'CYTOBAND', 'DESCRIPTION', 'GO_ID', 'SEQUENCE']\n",
      "{'ID': ['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107', '(+)E1A_r60_a135'], 'SPOT_ID': ['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107', '(+)E1A_r60_a135'], 'CONTROL_TYPE': ['pos', 'pos', 'pos', 'pos', 'pos'], 'REFSEQ': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan], 'GENE': [nan, nan, nan, nan, nan], 'GENE_SYMBOL': [nan, nan, nan, nan, nan], 'GENE_NAME': [nan, nan, nan, nan, nan], 'UNIGENE_ID': [nan, nan, nan, nan, nan], 'ENSEMBL_ID': [nan, nan, nan, nan, nan], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': [nan, nan, nan, nan, nan], 'CHROMOSOMAL_LOCATION': [nan, nan, nan, nan, nan], 'CYTOBAND': [nan, nan, nan, nan, nan], 'DESCRIPTION': [nan, nan, nan, nan, nan], 'GO_ID': [nan, nan, nan, nan, nan], 'SEQUENCE': [nan, nan, nan, nan, nan]}\n",
      "\n",
      "Examining potential gene mapping columns:\n",
      "\n",
      "Sample mappings from 'ID' to 'GENE_SYMBOL':\n",
      "                ID GENE_SYMBOL\n",
      "0     (+)E1A_r60_1         NaN\n",
      "1     (+)E1A_r60_3         NaN\n",
      "2  (+)E1A_r60_a104         NaN\n",
      "3  (+)E1A_r60_a107         NaN\n",
      "4  (+)E1A_r60_a135         NaN\n",
      "5   (+)E1A_r60_a20         NaN\n",
      "6   (+)E1A_r60_a22         NaN\n",
      "7   (+)E1A_r60_a97         NaN\n",
      "8   (+)E1A_r60_n11         NaN\n",
      "9    (+)E1A_r60_n9         NaN\n",
      "\n",
      "Number of probes with gene symbol mappings: 29833\n",
      "Sample of valid mappings:\n",
      "              ID GENE_SYMBOL\n",
      "11  A_23_P100001     FAM174B\n",
      "12  A_23_P100022        SV2B\n",
      "13  A_23_P100056      RBPMS2\n",
      "14  A_23_P100074        AVEN\n",
      "15  A_23_P100127       CASC5\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",
    "# Look more closely at columns that might contain gene information\n",
    "print(\"\\nExamining potential gene mapping columns:\")\n",
    "# Based on the output, 'ID' and 'GENE_SYMBOL' are likely the mapping columns we need\n",
    "gene_id_col = 'ID'\n",
    "gene_symbol_col = 'GENE_SYMBOL'\n",
    "\n",
    "if gene_id_col in gene_annotation.columns and gene_symbol_col in gene_annotation.columns:\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 symbol 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.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9eacf94f",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "00a36a8b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:19:01.934523Z",
     "iopub.status.busy": "2025-03-25T08:19:01.934412Z",
     "iopub.status.idle": "2025-03-25T08:19:01.991972Z",
     "shell.execute_reply": "2025-03-25T08:19:01.991616Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Using mapping from 'ID' to 'GENE_SYMBOL'\n",
      "Gene mapping dataframe shape: (29833, 2)\n",
      "Sample of gene mapping:\n",
      "              ID     Gene\n",
      "11  A_23_P100001  FAM174B\n",
      "12  A_23_P100022     SV2B\n",
      "13  A_23_P100056   RBPMS2\n",
      "14  A_23_P100074     AVEN\n",
      "15  A_23_P100127    CASC5\n",
      "Gene expression data shape after mapping: (8182, 43)\n",
      "First 5 gene symbols after mapping:\n",
      "['A1BG', 'A4GALT', 'AAAS', 'AACS', 'AADACL3']\n",
      "\n",
      "Preview of gene expression data after mapping:\n",
      "         GSM1121040  GSM1121041  GSM1121042  GSM1121043  GSM1121044\n",
      "Gene                                                               \n",
      "A1BG          5.819       6.883       5.939       5.627       5.884\n",
      "A4GALT       10.260       9.439       9.304       9.026       8.972\n",
      "AAAS          6.096       6.338       6.158       5.887       5.926\n",
      "AACS          6.395       6.298       6.431       6.227       5.974\n",
      "AADACL3       6.082       6.453       5.749       5.782       6.057\n"
     ]
    }
   ],
   "source": [
    "# 1. Determine the columns for gene identifier and gene symbol mapping\n",
    "probe_id_col = 'ID'  # This contains identifiers like 'A_23_P100001' matching the gene expression data\n",
    "gene_symbol_col = 'GENE_SYMBOL'  # This contains the gene symbols we need\n",
    "\n",
    "print(f\"Using mapping from '{probe_id_col}' to '{gene_symbol_col}'\")\n",
    "\n",
    "# 2. Extract the gene mapping dataframe with the two relevant columns\n",
    "gene_mapping = get_gene_mapping(gene_annotation, probe_id_col, gene_symbol_col)\n",
    "print(f\"Gene mapping dataframe shape: {gene_mapping.shape}\")\n",
    "print(\"Sample of gene mapping:\")\n",
    "print(gene_mapping.head())\n",
    "\n",
    "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n",
    "print(\"First 5 gene symbols after mapping:\")\n",
    "print(gene_data.index[:5].tolist())\n",
    "\n",
    "# Show the first few values for a few genes to verify the data\n",
    "print(\"\\nPreview of gene expression data after mapping:\")\n",
    "print(gene_data.iloc[:5, :5])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "154dd42c",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "5b5252e1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:19:01.993362Z",
     "iopub.status.busy": "2025-03-25T08:19:01.993243Z",
     "iopub.status.idle": "2025-03-25T08:19:04.343051Z",
     "shell.execute_reply": "2025-03-25T08:19:04.342664Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Normalizing gene symbols...\n",
      "Gene data shape after normalization: (8116, 43)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Chronic_kidney_disease/gene_data/GSE45980.csv\n",
      "Loaded clinical data from ../../output/preprocess/Chronic_kidney_disease/clinical_data/GSE45980.csv\n",
      "Clinical data shape: (3, 43)\n",
      "\n",
      "Linking clinical and genetic data...\n",
      "Linked data shape: (43, 8119)\n",
      "Linked data preview (first 5 rows, first 5 columns):\n",
      "              0     1    2   A1BG  A4GALT\n",
      "GSM1121040  0.0  72.0  1.0  5.819  10.260\n",
      "GSM1121041  0.0  20.0  0.0  6.883   9.439\n",
      "GSM1121042  0.0  64.0  0.0  5.939   9.304\n",
      "GSM1121043  0.0  17.0  1.0  5.627   9.026\n",
      "GSM1121044  0.0  46.0  1.0  5.884   8.972\n",
      "Linked data after renaming columns:\n",
      "            Chronic_kidney_disease   Age  Gender   A1BG  A4GALT\n",
      "GSM1121040                     0.0  72.0     1.0  5.819  10.260\n",
      "GSM1121041                     0.0  20.0     0.0  6.883   9.439\n",
      "GSM1121042                     0.0  64.0     0.0  5.939   9.304\n",
      "GSM1121043                     0.0  17.0     1.0  5.627   9.026\n",
      "GSM1121044                     0.0  46.0     1.0  5.884   8.972\n",
      "\n",
      "Handling missing values...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data shape after handling missing values: (43, 8119)\n",
      "\n",
      "Checking for bias in trait and demographic features...\n",
      "For the feature 'Chronic_kidney_disease', the least common label is '1.0' with 12 occurrences. This represents 27.91% of the dataset.\n",
      "The distribution of the feature 'Chronic_kidney_disease' in this dataset is fine.\n",
      "\n",
      "Quartiles for 'Age':\n",
      "  25%: 36.0\n",
      "  50% (Median): 55.0\n",
      "  75%: 65.0\n",
      "Min: 17.0\n",
      "Max: 74.0\n",
      "The distribution of the feature 'Age' in this dataset is fine.\n",
      "\n",
      "For the feature 'Gender', the least common label is '0.0' with 15 occurrences. This represents 34.88% of the dataset.\n",
      "The distribution of the feature 'Gender' in this dataset is fine.\n",
      "\n",
      "\n",
      "Conducting final quality validation...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Chronic_kidney_disease/GSE45980.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "print(\"\\nNormalizing gene symbols...\")\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\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 data saved to {out_gene_data_file}\")\n",
    "\n",
    "# 2. Load clinical data from previously saved file\n",
    "try:\n",
    "    # Try to load the clinical data from the file saved in Step 2\n",
    "    selected_clinical_df = pd.read_csv(out_clinical_data_file)\n",
    "    print(f\"Loaded clinical data from {out_clinical_data_file}\")\n",
    "except FileNotFoundError:\n",
    "    # If not available, re-extract it using the correct row indices from Step 2\n",
    "    background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n",
    "    trait_row = 3  # Correct row index from Step 2\n",
    "    age_row = 1\n",
    "    gender_row = 0\n",
    "    \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",
    "    # 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 extracted and saved to {out_clinical_data_file}\")\n",
    "\n",
    "print(f\"Clinical data shape: {selected_clinical_df.shape}\")\n",
    "\n",
    "# 3. Link the clinical and genetic data\n",
    "print(\"\\nLinking clinical and genetic data...\")\n",
    "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data)\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "print(\"Linked data preview (first 5 rows, first 5 columns):\")\n",
    "print(linked_data.iloc[:5, :5])\n",
    "\n",
    "# Rename the clinical columns to match expected names\n",
    "linked_data = linked_data.rename(columns={0: trait, 1: \"Age\", 2: \"Gender\"})\n",
    "print(\"Linked data after renaming columns:\")\n",
    "print(linked_data.iloc[:5, :5])\n",
    "\n",
    "# 4. Handle missing values in the linked data\n",
    "print(\"\\nHandling 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",
    "# 5. Determine if the trait and demographic features are biased\n",
    "print(\"\\nChecking for bias in trait and demographic features...\")\n",
    "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "\n",
    "# 6. Conduct final quality validation and save relevant information\n",
    "print(\"\\nConducting final quality validation...\")\n",
    "is_gene_available = True  # We've confirmed gene data is available in previous steps\n",
    "is_trait_available = True  # We've confirmed trait data is available in previous steps\n",
    "\n",
    "note = \"This dataset contains gene expression data from kidney biopsies. It classifies samples based on clinical course (stable or progressive chronic kidney disease).\"\n",
    "\n",
    "is_usable = validate_and_save_cohort_info(\n",
    "    is_final=True,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=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",
    "# 7. 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(\"Linked data not saved as dataset is not usable for the current trait study.\")"
   ]
  }
 ],
 "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
}