File size: 24,234 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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "1594aefd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:30:00.457368Z",
     "iopub.status.busy": "2025-03-25T06:30:00.457262Z",
     "iopub.status.idle": "2025-03-25T06:30:00.623285Z",
     "shell.execute_reply": "2025-03-25T06:30:00.622917Z"
    }
   },
   "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 = \"GSE204791\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Aniridia\"\n",
    "in_cohort_dir = \"../../input/GEO/Aniridia/GSE204791\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Aniridia/GSE204791.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Aniridia/gene_data/GSE204791.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Aniridia/clinical_data/GSE204791.csv\"\n",
    "json_path = \"../../output/preprocess/Aniridia/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a493803a",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "6980f79a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:30:00.624719Z",
     "iopub.status.busy": "2025-03-25T06:30:00.624583Z",
     "iopub.status.idle": "2025-03-25T06:30:00.763469Z",
     "shell.execute_reply": "2025-03-25T06:30:00.763117Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Altered regulation of mRNA and miRNA expression in epithelial and stromal tissue of keratoconus corneas [RNA]\"\n",
      "!Series_summary\t\"Purpose:  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.  Methods:  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.   Results:  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.  Conclusion:  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 epithelial and stromal cells from 8 patients with keratoconus compared to controls\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['age: 59', 'age: 28', 'age: 58', 'age: 56', 'age: 50', 'age: 30', 'age: 53', 'age: 77', 'age: 67', 'age: 29', 'age: 46', 'age: 65', 'age: 81', 'age: 87', 'age: 70', 'age: 79', 'age: 55'], 1: ['gender: F', 'gender: M'], 2: ['disease: KC', 'disease: healthy control'], 3: ['Stage: A4 B4 C3 D4 +', 'Stage: A4 B4 C3 D1 -', 'Stage: A4 B4 C3 D4 ++', nan, 'Stage: A2 B4 C1 D3 -', 'Stage: A2 B4 C1 D1 +', 'Stage: A4 B4 C2 D3']}\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": "44d8e170",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "40f37372",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:30:00.764688Z",
     "iopub.status.busy": "2025-03-25T06:30:00.764576Z",
     "iopub.status.idle": "2025-03-25T06:30:00.769700Z",
     "shell.execute_reply": "2025-03-25T06:30:00.769366Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data available: True\n",
      "Trait data available: True\n",
      "Age data available: True\n",
      "Gender data available: True\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information, this dataset contains both mRNA and miRNA expression data\n",
    "# The study is about \"microRNA and mRNA expression analysis,\" which indicates gene expression data is available\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability and 2.2 Data Type Conversion\n",
    "\n",
    "# For trait (Aniridia)\n",
    "# Looking at disease status in row 2 (KC = keratoconus, healthy control)\n",
    "trait_row = 2\n",
    "\n",
    "def convert_trait(value):\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    value_lower = str(value).lower()\n",
    "    if ':' in value_lower:\n",
    "        value_lower = value_lower.split(':', 1)[1].strip()\n",
    "    \n",
    "    if 'kc' in value_lower or 'keratoconus' in value_lower:\n",
    "        return 1  # Disease present\n",
    "    elif 'healthy' in value_lower or 'control' in value_lower:\n",
    "        return 0  # Disease absent\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# For age - available in row 0\n",
    "age_row = 0\n",
    "\n",
    "def convert_age(value):\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    if ':' in value:\n",
    "        age_str = value.split(':', 1)[1].strip()\n",
    "        try:\n",
    "            return float(age_str)\n",
    "        except ValueError:\n",
    "            return None\n",
    "    return None\n",
    "\n",
    "# For gender - available in row 1\n",
    "gender_row = 1\n",
    "\n",
    "def convert_gender(value):\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    value_lower = str(value).lower()\n",
    "    if ':' in value_lower:\n",
    "        value_lower = value_lower.split(':', 1)[1].strip()\n",
    "    \n",
    "    if value_lower == 'f' or value_lower == 'female':\n",
    "        return 0\n",
    "    elif value_lower == 'm' or value_lower == 'male':\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata - Initial filtering\n",
    "# Determine if trait data is available (trait_row is not None)\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Validate and save cohort info (initial filtering)\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 (if trait_row is not None)\n",
    "# Note: In this case, we're unable to perform clinical feature extraction\n",
    "# because we don't have access to the properly formatted clinical data.\n",
    "# The sample characteristics dictionary only shows unique values for each characteristic\n",
    "# and cannot be directly converted to the expected clinical data format.\n",
    "\n",
    "# We will print the information we've determined about the dataset\n",
    "print(f\"Gene expression data available: {is_gene_available}\")\n",
    "print(f\"Trait data available: {is_trait_available}\")\n",
    "print(f\"Age data available: {age_row is not None}\")\n",
    "print(f\"Gender data available: {gender_row is not None}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e7796fd0",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "562d2f84",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:30:00.770798Z",
     "iopub.status.busy": "2025-03-25T06:30:00.770689Z",
     "iopub.status.idle": "2025-03-25T06:30:00.963602Z",
     "shell.execute_reply": "2025-03-25T06:30:00.963199Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "First 20 gene/probe identifiers:\n",
      "Index(['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107',\n",
      "       '(+)E1A_r60_a135', '(+)E1A_r60_a20', '(+)E1A_r60_a22', '(+)E1A_r60_a97',\n",
      "       '(+)E1A_r60_n11', '(+)E1A_r60_n9', '3xSLv1', 'A_19_P00315452',\n",
      "       'A_19_P00315492', 'A_19_P00315493', 'A_19_P00315502', 'A_19_P00315506',\n",
      "       'A_19_P00315518', 'A_19_P00315519', 'A_19_P00315529', 'A_19_P00315541'],\n",
      "      dtype='object', name='ID')\n",
      "\n",
      "Gene data dimensions: 58341 genes × 31 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": "7409acec",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "11810dec",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:30:00.964919Z",
     "iopub.status.busy": "2025-03-25T06:30:00.964801Z",
     "iopub.status.idle": "2025-03-25T06:30:00.966780Z",
     "shell.execute_reply": "2025-03-25T06:30:00.966471Z"
    }
   },
   "outputs": [],
   "source": [
    "# Examining the gene identifiers from the output\n",
    "# These identifiers appear to be Agilent microarray probe IDs (starting with \"A_19_P\") \n",
    "# and control probes (like \"(+)E1A_r60_1\"), not standard human gene symbols\n",
    "\n",
    "# These probe IDs will need to be mapped to standard gene symbols\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1809d954",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "453692f3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:30:00.967872Z",
     "iopub.status.busy": "2025-03-25T06:30:00.967763Z",
     "iopub.status.idle": "2025-03-25T06:30:03.987734Z",
     "shell.execute_reply": "2025-03-25T06:30:03.987318Z"
    }
   },
   "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": "4bc299ef",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "c44f06e0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:30:03.989171Z",
     "iopub.status.busy": "2025-03-25T06:30:03.989030Z",
     "iopub.status.idle": "2025-03-25T06:30:04.211131Z",
     "shell.execute_reply": "2025-03-25T06:30:04.210694Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data after mapping: 29222 genes × 31 samples\n",
      "First 10 gene symbols:\n",
      "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A1CF-2', 'A1CF-3', 'A2M', 'A2M-1',\n",
      "       'A2M-AS1', 'A2ML1', 'A2MP1'],\n",
      "      dtype='object', name='Gene')\n"
     ]
    }
   ],
   "source": [
    "# 1. Based on the preview, determine the columns for gene mapping\n",
    "# From the preview, we can see 'ID' is the column with probe identifiers\n",
    "# and 'GENE_SYMBOL' is the column with gene symbols\n",
    "prob_col = 'ID'  \n",
    "gene_col = 'GENE_SYMBOL'\n",
    "\n",
    "# 2. Get a mapping dataframe by extracting the relevant columns\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)\n",
    "\n",
    "# 3. Apply the gene mapping to convert probe-level data to gene-level data\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "\n",
    "# Print information about the mapped data\n",
    "print(f\"Gene data after mapping: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
    "print(\"First 10 gene symbols:\")\n",
    "print(gene_data.index[:10])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e718c798",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "7802cfdd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:30:04.212568Z",
     "iopub.status.busy": "2025-03-25T06:30:04.212447Z",
     "iopub.status.idle": "2025-03-25T06:30:13.216443Z",
     "shell.execute_reply": "2025-03-25T06:30:13.215676Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Aniridia/gene_data/GSE204791.csv\n",
      "Gene data after normalization: 20778 genes × 31 samples\n",
      "Clinical features saved to ../../output/preprocess/Aniridia/clinical_data/GSE204791.csv\n",
      "Clinical features preview:\n",
      "{'GSM6193900': [1.0, 59.0, 0.0], 'GSM6193903': [1.0, 28.0, 1.0], 'GSM6193906': [1.0, 58.0, 0.0], 'GSM6193908': [1.0, 56.0, 1.0], 'GSM6193911': [0.0, 50.0, 0.0], 'GSM6193913': [0.0, 30.0, 1.0], 'GSM6193916': [0.0, 53.0, 0.0], 'GSM6193918': [0.0, 77.0, 1.0], 'GSM6193920': [1.0, 50.0, 0.0], 'GSM6193923': [1.0, 67.0, 1.0], 'GSM6193925': [1.0, 29.0, 0.0], 'GSM6193928': [1.0, 46.0, 1.0], 'GSM6193930': [0.0, 56.0, 0.0], 'GSM6193933': [0.0, 65.0, 1.0], 'GSM6193935': [0.0, 58.0, 0.0], 'GSM6193938': [0.0, 81.0, 1.0], 'GSM6193940': [1.0, 28.0, 1.0], 'GSM6193943': [1.0, 58.0, 0.0], 'GSM6193945': [1.0, 67.0, 1.0], 'GSM6193948': [1.0, 46.0, 1.0], 'GSM6193950': [0.0, 87.0, 0.0], 'GSM6193953': [0.0, 87.0, 1.0], 'GSM6193955': [0.0, 70.0, 0.0], 'GSM6193957': [1.0, 50.0, 0.0], 'GSM6193960': [1.0, 29.0, 0.0], 'GSM6193962': [1.0, 56.0, 1.0], 'GSM6193965': [1.0, 59.0, 0.0], 'GSM6193967': [0.0, 79.0, 1.0], 'GSM6193970': [0.0, 55.0, 0.0], 'GSM6193972': [0.0, 65.0, 1.0], 'GSM6193975': [0.0, 87.0, 1.0]}\n",
      "Linked data shape: (31, 20781)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Data shape after handling missing values: (31, 20781)\n",
      "\n",
      "Checking for bias in the trait variable:\n",
      "For the feature 'Aniridia', the least common label is '0.0' with 15 occurrences. This represents 48.39% of the dataset.\n",
      "The distribution of the feature 'Aniridia' in this dataset is fine.\n",
      "\n",
      "Quartiles for 'Age':\n",
      "  25%: 50.0\n",
      "  50% (Median): 58.0\n",
      "  75%: 67.0\n",
      "Min: 28.0\n",
      "Max: 87.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 48.39% of the dataset.\n",
      "The distribution of the feature 'Gender' in this dataset is fine.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Aniridia/GSE204791.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the index\n",
    "gene_data_normalized = normalize_gene_symbols_in_index(gene_data)\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 data saved to {out_gene_data_file}\")\n",
    "print(f\"Gene data after normalization: {gene_data_normalized.shape[0]} genes × {gene_data_normalized.shape[1]} samples\")\n",
    "\n",
    "# Extract clinical features first (missed in previous steps)\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 clinical data\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",
    "print(\"Clinical features preview:\")\n",
    "print(preview_df(clinical_features))\n",
    "\n",
    "# 2. Link 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\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. Determine if trait is biased\n",
    "print(\"\\nChecking for bias in the trait variable:\")\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
}