File size: 27,878 Bytes
92d2f89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "2c9ee51f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:29:34.962892Z",
     "iopub.status.busy": "2025-03-25T06:29:34.962702Z",
     "iopub.status.idle": "2025-03-25T06:29:35.127107Z",
     "shell.execute_reply": "2025-03-25T06:29:35.126723Z"
    }
   },
   "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 = \"Aniridia\"\n",
    "cohort = \"GSE137996\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Aniridia\"\n",
    "in_cohort_dir = \"../../input/GEO/Aniridia/GSE137996\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Aniridia/GSE137996.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Aniridia/gene_data/GSE137996.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Aniridia/clinical_data/GSE137996.csv\"\n",
    "json_path = \"../../output/preprocess/Aniridia/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c0f9a908",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "b0a00aee",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:29:35.128310Z",
     "iopub.status.busy": "2025-03-25T06:29:35.128168Z",
     "iopub.status.idle": "2025-03-25T06:29:35.305645Z",
     "shell.execute_reply": "2025-03-25T06:29:35.305281Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Conjunctival mRNA and miRNA expression profiles in congenital aniridia are genotype and phenotype dependent (AKK mRNA)\"\n",
      "!Series_summary\t\"Purpose:\"\n",
      "!Series_summary\t\"To evaluate conjunctival cell microRNA and mRNA expression in relation to observed phenotype and genotype of aniridia-associated keratopathy (AAK) in a cohort of subjects with congenital aniridia.\"\n",
      "!Series_summary\t\"Methods:\"\n",
      "!Series_summary\t\"Using impression cytology, bulbar conjunctival cells were sampled from 20 subjects with congenital aniridia and 20 age and sex-matched healthy control subjects. RNA was extracted and microRNA and mRNA analysis was performed using microarrays. Results were related to the presence and severity of AAK determined by a standardized clinical grading scale and to the genotype (PAX6 mutation?) determined by clinical genetics.\"\n",
      "!Series_summary\t\"Results:\"\n",
      "!Series_summary\t\"Of the 2549 microRNAs analyzed, 21 were differentially expressed relative to controls. Among these miR-204-5p, an inhibitor of corneal neovascularization, was downregulated 26.8-fold, while miR-5787 and miR-224-5p were upregulated 2.8 and 2.4-fold relative to controls, respectively. At the mRNA level, 539 transcripts were differentially expressed, among these FOSB and FOS were upregulated 17.5 and 9.7-fold respectively, and JUN by 2.9-fold, all components of the AP-1 transcription factor complex. Pathway analysis revealed dysregulation of several enriched pathways including PI3K-Akt, MAPK, and Ras signaling pathways in aniridia. For several microRNAs and transcripts, expression levels aligned with AAK severity, while in very mild cases with missense or non-PAX6 coding mutations, gene expression was only minimally altered.\"\n",
      "!Series_summary\t\"Conclusion:\"\n",
      "!Series_summary\t\"In aniridia, specific factors and pathways are strongly dysregulated in conjunctival cells, suggesting that the conjunctiva in aniridia is abnormally maintained in a pro-angiogenic and proliferative state, promoting the aggressivity of AAK in a mutation-dependent manner. Transcriptional profiling of conjunctival cells at the microRNA and mRNA levels presents a powerful, minimally-invasive means to assess the regulation of cell dysfunction at the ocular surface.\"\n",
      "!Series_overall_design\t\"MiRNA and mRNA expression profiles of conjunctival cells from 20 patients with aniridia associated keratopathy compared to controls\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['age: 20', 'age: 28', 'age: 38', 'age: 57', 'age: 26', 'age: 18', 'age: 36', 'age: 42', 'age: 55', 'age: 54', 'age: 34', 'age: 51', 'age: 46', 'age: 52', 'age: 53', 'age: 40', 'age: 39', 'age: 59', 'age: 32', 'age: 37', 'age: 29', 'age: 19', 'age: 25', 'age: 22'], 1: ['gender: F', 'gender: M', 'gender: W'], 2: ['disease: AAK', 'disease: healthy control'], 3: ['Stage: Severe', 'Stage: Mild', 'Stage: NA'], 4: ['tissue: conjunctival cells']}\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": "b967c988",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "4c7e073f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:29:35.306881Z",
     "iopub.status.busy": "2025-03-25T06:29:35.306770Z",
     "iopub.status.idle": "2025-03-25T06:29:35.313900Z",
     "shell.execute_reply": "2025-03-25T06:29:35.313513Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Cannot extract clinical features: clinical data file not found.\n",
      "Empty clinical data saved to ../../output/preprocess/Aniridia/clinical_data/GSE137996.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Based on background information, this dataset contains mRNA expression data\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# For trait (Aniridia/AAK): From key 2 and 3 we can determine if person has AAK and severity\n",
    "trait_row = 2  # 'disease: AAK' or 'disease: healthy control'\n",
    "\n",
    "# For age: Available at key 0\n",
    "age_row = 0  # Age information is available\n",
    "\n",
    "# For gender: Available at key 1\n",
    "gender_row = 1  # Gender information is available\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert the trait information to binary (0: control, 1: AAK).\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    value = value.lower().strip()\n",
    "    if 'disease:' in value:\n",
    "        value = value.split('disease:')[-1].strip()\n",
    "    \n",
    "    if 'healthy control' in value or 'control' in value:\n",
    "        return 0\n",
    "    elif 'aak' in value or 'aniridia' in value:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Extract and convert age to continuous value.\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    if 'age:' in value:\n",
    "        try:\n",
    "            age = int(value.split('age:')[-1].strip())\n",
    "            return age\n",
    "        except:\n",
    "            return None\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender to binary (0: female, 1: male).\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    value = value.lower().strip()\n",
    "    if 'gender:' in value:\n",
    "        value = value.split('gender:')[-1].strip()\n",
    "    \n",
    "    if value == 'f' or value == 'w':  # Assuming 'W' means woman\n",
    "        return 0\n",
    "    elif value == 'm':\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Trait data is available if trait_row is not None\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 don't have the clinical_data.csv file, we need to create a clinical_df\n",
    "    # The expected format for geo_select_clinical_features is a DataFrame where each row\n",
    "    # represents a feature type and each column represents a sample\n",
    "    \n",
    "    # Create dummy data for demonstration purposes - the actual function will \n",
    "    # expect data in the proper format\n",
    "    sample_ids = [f\"GSM{i}\" for i in range(1, 21)]  # 20 samples based on background info\n",
    "    \n",
    "    # Create empty DataFrame with sample IDs as columns\n",
    "    clinical_df = pd.DataFrame(index=range(5), columns=sample_ids)\n",
    "    \n",
    "    # This is a placeholder to satisfy the function call\n",
    "    # In a real scenario, we would need actual clinical data arranged properly\n",
    "    \n",
    "    # Since we don't have the actual clinical data, we should skip this part\n",
    "    # and just acknowledge that clinical data extraction cannot be performed\n",
    "    print(\"Cannot extract clinical features: clinical data file not found.\")\n",
    "    \n",
    "    # Write an empty DataFrame to the output file to maintain workflow\n",
    "    empty_clinical_df = pd.DataFrame(columns=['Sample', 'Aniridia', 'Age', 'Gender'])\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    empty_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
    "    print(f\"Empty clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a7d7efe5",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "531a75ec",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:29:35.315195Z",
     "iopub.status.busy": "2025-03-25T06:29:35.315088Z",
     "iopub.status.idle": "2025-03-25T06:29:35.566604Z",
     "shell.execute_reply": "2025-03-25T06:29:35.566076Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "First 20 gene/probe identifiers:\n",
      "Index(['A_19_P00315452', 'A_19_P00315492', 'A_19_P00315493', 'A_19_P00315502',\n",
      "       'A_19_P00315506', 'A_19_P00315518', 'A_19_P00315519', 'A_19_P00315529',\n",
      "       'A_19_P00315541', 'A_19_P00315543', 'A_19_P00315551', 'A_19_P00315581',\n",
      "       'A_19_P00315584', 'A_19_P00315593', 'A_19_P00315603', 'A_19_P00315625',\n",
      "       'A_19_P00315627', 'A_19_P00315631', 'A_19_P00315641', 'A_19_P00315647'],\n",
      "      dtype='object', name='ID')\n",
      "\n",
      "Gene data dimensions: 58201 genes × 40 samples\n"
     ]
    }
   ],
   "source": [
    "# 1. Re-identify the SOFT and matrix files to ensure we have the correct paths\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. Extract the gene expression data from the matrix file\n",
    "gene_data = get_genetic_data(matrix_file)\n",
    "\n",
    "# 3. Print the first 20 row IDs (gene or probe identifiers)\n",
    "print(\"\\nFirst 20 gene/probe identifiers:\")\n",
    "print(gene_data.index[:20])\n",
    "\n",
    "# 4. Print the dimensions of the gene expression data\n",
    "print(f\"\\nGene data dimensions: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
    "\n",
    "# Note: we keep is_gene_available as True since we successfully extracted gene expression data\n",
    "is_gene_available = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "82029ca3",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "631bd0f3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:29:35.568200Z",
     "iopub.status.busy": "2025-03-25T06:29:35.568043Z",
     "iopub.status.idle": "2025-03-25T06:29:35.570489Z",
     "shell.execute_reply": "2025-03-25T06:29:35.570014Z"
    }
   },
   "outputs": [],
   "source": [
    "# The gene identifiers appear to be Agilent microarray probe IDs (starting with \"A_19_P\"),\n",
    "# not standard human gene symbols. These will need to be mapped to gene symbols.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3f814a2d",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "7c37f11e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:29:35.572065Z",
     "iopub.status.busy": "2025-03-25T06:29:35.571949Z",
     "iopub.status.idle": "2025-03-25T06:29:39.095227Z",
     "shell.execute_reply": "2025-03-25T06:29:39.094870Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['GE_BrightCorner', 'DarkCorner', 'A_21_P0014386', 'A_33_P3396872', 'A_33_P3267760'], 'CONTROL_TYPE': ['pos', 'pos', 'FALSE', 'FALSE', 'FALSE'], 'REFSEQ': [nan, nan, nan, 'NM_001105533', nan], 'GB_ACC': [nan, nan, nan, 'NM_001105533', nan], 'LOCUSLINK_ID': [nan, nan, nan, 79974.0, 54880.0], 'GENE_SYMBOL': [nan, nan, nan, 'CPED1', 'BCOR'], 'GENE_NAME': [nan, nan, nan, 'cadherin-like and PC-esterase domain containing 1', 'BCL6 corepressor'], 'UNIGENE_ID': [nan, nan, nan, 'Hs.189652', nan], 'ENSEMBL_ID': [nan, nan, nan, nan, 'ENST00000378463'], 'ACCESSION_STRING': [nan, nan, nan, 'ref|NM_001105533|gb|AK025639|gb|BC030538|tc|THC2601673', 'ens|ENST00000378463'], 'CHROMOSOMAL_LOCATION': [nan, nan, 'unmapped', 'chr7:120901888-120901947', 'chrX:39909128-39909069'], 'CYTOBAND': [nan, nan, nan, 'hs|7q31.31', 'hs|Xp11.4'], 'DESCRIPTION': [nan, nan, nan, 'Homo sapiens cadherin-like and PC-esterase domain containing 1 (CPED1), transcript variant 2, mRNA [NM_001105533]', 'BCL6 corepressor [Source:HGNC Symbol;Acc:HGNC:20893] [ENST00000378463]'], 'GO_ID': [nan, nan, nan, 'GO:0005783(endoplasmic reticulum)', 'GO:0000122(negative regulation of transcription from RNA polymerase II promoter)|GO:0000415(negative regulation of histone H3-K36 methylation)|GO:0003714(transcription corepressor activity)|GO:0004842(ubiquitin-protein ligase activity)|GO:0005515(protein binding)|GO:0005634(nucleus)|GO:0006351(transcription, DNA-dependent)|GO:0007507(heart development)|GO:0008134(transcription factor binding)|GO:0030502(negative regulation of bone mineralization)|GO:0031072(heat shock protein binding)|GO:0031519(PcG protein complex)|GO:0035518(histone H2A monoubiquitination)|GO:0042476(odontogenesis)|GO:0042826(histone deacetylase binding)|GO:0044212(transcription regulatory region DNA binding)|GO:0045892(negative regulation of transcription, DNA-dependent)|GO:0051572(negative regulation of histone H3-K4 methylation)|GO:0060021(palate development)|GO:0065001(specification of axis polarity)|GO:0070171(negative regulation of tooth mineralization)'], 'SEQUENCE': [nan, nan, 'AATACATGTTTTGGTAAACACTCGGTCAGAGCACCCTCTTTCTGTGGAATCAGACTGGCA', 'GCTTATCTCACCTAATACAGGGACTATGCAACCAAGAAACTGGAAATAAAAACAAAGATA', 'CATCAAAGCTACGAGAGATCCTACACACCCAGATTTAAAAAATAATAAAAACTTAAGGGC'], 'SPOT_ID': ['GE_BrightCorner', 'DarkCorner', 'A_21_P0014386', 'A_33_P3396872', 'A_33_P3267760']}\n"
     ]
    }
   ],
   "source": [
    "# 1. First get the file paths using geo_get_relevant_filepaths function\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. 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",
    "# 3. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
    "print(\"Gene annotation preview:\")\n",
    "print(preview_df(gene_annotation))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0e28d211",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "6047a338",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:29:39.096551Z",
     "iopub.status.busy": "2025-03-25T06:29:39.096426Z",
     "iopub.status.idle": "2025-03-25T06:29:39.356237Z",
     "shell.execute_reply": "2025-03-25T06:29:39.355886Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Original probe data dimensions: 29222 probes × 40 samples\n",
      "Gene mapping dataframe dimensions: 48862 rows × 2 columns\n",
      "Mapped gene data dimensions: 29222 genes × 40 samples\n",
      "\n",
      "First 10 gene symbols after mapping:\n",
      "['A1BG', 'A1BG-AS1', 'A1CF', 'A1CF-2', 'A1CF-3', 'A2M', 'A2M-1', 'A2M-AS1', 'A2ML1', 'A2MP1']\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the columns with probe IDs and gene symbols\n",
    "# From the output, we can see:\n",
    "# - Probe IDs in gene expression data are like 'A_19_P00315452'\n",
    "# - In gene annotation, 'ID' contains probe IDs and 'GENE_SYMBOL' contains gene symbols\n",
    "\n",
    "# 2. Get gene mapping dataframe by extracting the ID and GENE_SYMBOL columns\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')\n",
    "\n",
    "# 3. Apply gene mapping to convert probe-level expression to gene expression\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "\n",
    "# Print information about the mapping process\n",
    "print(f\"\\nOriginal probe data dimensions: {len(gene_data.index)} probes × {gene_data.shape[1]} samples\")\n",
    "print(f\"Gene mapping dataframe dimensions: {gene_mapping.shape[0]} rows × {gene_mapping.shape[1]} columns\")\n",
    "print(f\"Mapped gene data dimensions: {len(gene_data.index)} genes × {gene_data.shape[1]} samples\")\n",
    "\n",
    "# Preview the first few genes after mapping\n",
    "print(\"\\nFirst 10 gene symbols after mapping:\")\n",
    "print(list(gene_data.index[:10]))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5ba70067",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "08b65098",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:29:39.357598Z",
     "iopub.status.busy": "2025-03-25T06:29:39.357482Z",
     "iopub.status.idle": "2025-03-25T06:29:49.945972Z",
     "shell.execute_reply": "2025-03-25T06:29:49.945492Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalizing gene symbols in the gene expression data...\n",
      "Original gene data shape: 29222 genes × 40 samples\n",
      "Normalized gene data shape: 20778 genes × 40 samples\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene expression data saved to ../../output/preprocess/Aniridia/gene_data/GSE137996.csv\n",
      "Extracting clinical features from original clinical data...\n",
      "Clinical features saved to ../../output/preprocess/Aniridia/clinical_data/GSE137996.csv\n",
      "Clinical features preview:\n",
      "{'GSM4096389': [1.0, 20.0, 0.0], 'GSM4096390': [1.0, 20.0, 0.0], 'GSM4096391': [1.0, 28.0, 0.0], 'GSM4096392': [1.0, 20.0, 0.0], 'GSM4096393': [1.0, 38.0, 0.0], 'GSM4096394': [1.0, 57.0, 1.0], 'GSM4096395': [1.0, 26.0, 0.0], 'GSM4096396': [1.0, 18.0, 1.0], 'GSM4096397': [1.0, 36.0, 0.0], 'GSM4096398': [1.0, 42.0, 0.0], 'GSM4096399': [1.0, 18.0, 0.0], 'GSM4096400': [1.0, 42.0, 0.0], 'GSM4096401': [1.0, 36.0, 1.0], 'GSM4096402': [1.0, 28.0, 0.0], 'GSM4096403': [1.0, 55.0, 0.0], 'GSM4096404': [1.0, 54.0, 1.0], 'GSM4096405': [1.0, 34.0, 1.0], 'GSM4096406': [1.0, 51.0, 0.0], 'GSM4096407': [1.0, 46.0, 0.0], 'GSM4096408': [1.0, 52.0, 0.0], 'GSM4096409': [0.0, 53.0, 0.0], 'GSM4096410': [0.0, 54.0, 1.0], 'GSM4096411': [0.0, 40.0, 0.0], 'GSM4096412': [0.0, 55.0, 0.0], 'GSM4096413': [0.0, 57.0, 0.0], 'GSM4096414': [0.0, 28.0, 0.0], 'GSM4096415': [0.0, 39.0, 0.0], 'GSM4096416': [0.0, 59.0, 0.0], 'GSM4096417': [0.0, 20.0, 0.0], 'GSM4096418': [0.0, 32.0, 1.0], 'GSM4096419': [0.0, 37.0, 1.0], 'GSM4096420': [0.0, 34.0, 0.0], 'GSM4096421': [0.0, 28.0, 0.0], 'GSM4096422': [0.0, 28.0, 0.0], 'GSM4096423': [0.0, 29.0, 1.0], 'GSM4096424': [0.0, 19.0, 0.0], 'GSM4096425': [0.0, 25.0, 0.0], 'GSM4096426': [0.0, 25.0, 1.0], 'GSM4096427': [0.0, 34.0, 0.0], 'GSM4096428': [0.0, 22.0, 0.0]}\n",
      "Linking clinical and genetic data...\n",
      "Linked data shape: (40, 20781)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Data shape after handling missing values: (40, 20781)\n",
      "\n",
      "Checking for bias in feature variables:\n",
      "For the feature 'Aniridia', the least common label is '1.0' with 20 occurrences. This represents 50.00% of the dataset.\n",
      "The distribution of the feature 'Aniridia' in this dataset is fine.\n",
      "\n",
      "Quartiles for 'Age':\n",
      "  25%: 25.75\n",
      "  50% (Median): 34.0\n",
      "  75%: 47.25\n",
      "Min: 18.0\n",
      "Max: 59.0\n",
      "The distribution of the feature 'Age' in this dataset is fine.\n",
      "\n",
      "For the feature 'Gender', the least common label is '1.0' with 10 occurrences. This represents 25.00% of the dataset.\n",
      "The distribution of the feature 'Gender' in this dataset is fine.\n",
      "\n",
      "A new JSON file was created at: ../../output/preprocess/Aniridia/cohort_info.json\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Aniridia/GSE137996.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "print(\"Normalizing gene symbols in the gene expression data...\")\n",
    "# From the previous step output, we can see the data already contains gene symbols\n",
    "# like 'A1BG', 'A1CF', 'A2M' which need to be normalized\n",
    "gene_data_normalized = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Original gene data shape: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
    "print(f\"Normalized gene data shape: {gene_data_normalized.shape[0]} genes × {gene_data_normalized.shape[1]} samples\")\n",
    "\n",
    "# Save the normalized gene data\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "gene_data_normalized.to_csv(out_gene_data_file)\n",
    "print(f\"Normalized gene expression data saved to {out_gene_data_file}\")\n",
    "\n",
    "# 2. Extract clinical features from scratch instead of loading the empty file\n",
    "print(\"Extracting clinical features from original clinical data...\")\n",
    "clinical_features = geo_select_clinical_features(\n",
    "    clinical_data, \n",
    "    trait, \n",
    "    trait_row,\n",
    "    convert_trait,\n",
    "    age_row,\n",
    "    convert_age,\n",
    "    gender_row,\n",
    "    convert_gender\n",
    ")\n",
    "\n",
    "# Save the extracted clinical features\n",
    "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "clinical_features.to_csv(out_clinical_data_file)\n",
    "print(f\"Clinical features saved to {out_clinical_data_file}\")\n",
    "\n",
    "print(\"Clinical features preview:\")\n",
    "print(preview_df(clinical_features))\n",
    "\n",
    "# Check if clinical features were successfully extracted\n",
    "if clinical_features.empty:\n",
    "    print(\"Failed to extract clinical features. Dataset cannot be processed further.\")\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=False,\n",
    "        is_biased=True,\n",
    "        df=pd.DataFrame(),\n",
    "        note=\"Clinical features could not be extracted from the dataset.\"\n",
    "    )\n",
    "    print(\"Dataset deemed not usable due to lack of clinical features.\")\n",
    "else:\n",
    "    # 2. Link clinical and genetic data\n",
    "    print(\"Linking clinical and genetic data...\")\n",
    "    linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data_normalized)\n",
    "    print(f\"Linked data shape: {linked_data.shape}\")\n",
    "\n",
    "    # 3. Handle missing values systematically\n",
    "    linked_data = handle_missing_values(linked_data, trait_col=trait)\n",
    "    print(f\"Data shape after handling missing values: {linked_data.shape}\")\n",
    "\n",
    "    # 4. Check if the dataset is biased\n",
    "    print(\"\\nChecking for bias in feature variables:\")\n",
    "    is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "\n",
    "    # 5. Conduct final quality validation\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=\"Dataset contains gene expression data for aniridia patients and healthy controls.\"\n",
    "    )\n",
    "\n",
    "    # 6. Save linked data if 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(\"Dataset deemed not usable for trait association studies, linked data not 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
}