File size: 24,259 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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "9a554fe0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:01:43.848744Z",
     "iopub.status.busy": "2025-03-25T08:01:43.848628Z",
     "iopub.status.idle": "2025-03-25T08:01:44.009886Z",
     "shell.execute_reply": "2025-03-25T08:01:44.009535Z"
    }
   },
   "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 = \"Celiac_Disease\"\n",
    "cohort = \"GSE72625\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Celiac_Disease\"\n",
    "in_cohort_dir = \"../../input/GEO/Celiac_Disease/GSE72625\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Celiac_Disease/GSE72625.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Celiac_Disease/gene_data/GSE72625.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Celiac_Disease/clinical_data/GSE72625.csv\"\n",
    "json_path = \"../../output/preprocess/Celiac_Disease/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cb3ef66d",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "5dc29f26",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:01:44.011240Z",
     "iopub.status.busy": "2025-03-25T08:01:44.011099Z",
     "iopub.status.idle": "2025-03-25T08:01:44.180687Z",
     "shell.execute_reply": "2025-03-25T08:01:44.180332Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Gastrointestinal symptoms and pathology in patients with Common variable immunodeficiency\"\n",
      "!Series_summary\t\"Based on the findings of increased IEL in duodenal biopsies in CVID, an overlap with celiac disease has been suggested. In the present study, increased IEL, in particular in the pars descendens of the duodenum, was one of the most frequent histopathological finding. We therefore examined the gene expression profile in pars descendens of duodenum in CVID patients with increased IEL (n=12, IEL mean 34 [range 22-56] IEL/100 EC), CVID with normal levels of IEL (n=8), celiac disease (n=10, Marsh grade 3a or above) and healthy controls (n=17) by gene expression microarray\"\n",
      "!Series_overall_design\t\"GI histopathological findings in 53 CVID patients that underwent upper and lower endoscopic examination were addressed. For the microarray analysis 20 CVID (8 CVID_normal and 12 CVID with incresed IEL), 10 patients with celiac diseases and 17 healthy controls were included.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['disease state: CVID with increased intraepithelial lymphocytes', 'disease state: CVID without increased intraepithelial lymphocytes', 'disease state: celiac disease', 'disease state: healthy controls'], 1: ['tissue: duodenal biopsy']}\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": "935b4909",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "e348ca09",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:01:44.182108Z",
     "iopub.status.busy": "2025-03-25T08:01:44.181992Z",
     "iopub.status.idle": "2025-03-25T08:01:44.189196Z",
     "shell.execute_reply": "2025-03-25T08:01:44.188905Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical Features Preview: {0: [0.0], 1: [nan]}\n",
      "Clinical data saved to ../../output/preprocess/Celiac_Disease/clinical_data/GSE72625.csv\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "import numpy as np\n",
    "from typing import Optional, Callable, Dict, Any\n",
    "import json\n",
    "\n",
    "# Check if the cohort has gene expression data based on background information\n",
    "# This seems to contain gene expression microarray data from duodenal biopsies\n",
    "is_gene_available = True\n",
    "\n",
    "# Define the trait, age, and gender rows from the sample characteristics dictionary\n",
    "# Trait (disease state) is available at key 0\n",
    "trait_row = 0\n",
    "# Age is not available in the sample characteristics dictionary\n",
    "age_row = None\n",
    "# Gender is not available in the sample characteristics dictionary\n",
    "gender_row = None\n",
    "\n",
    "# Define conversion functions for the clinical variables\n",
    "def convert_trait(value_str):\n",
    "    \"\"\"Convert trait (disease state) string to binary value (Celiac disease = 1, others = 0)\"\"\"\n",
    "    if value_str is None or pd.isna(value_str):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon if present\n",
    "    if ':' in value_str:\n",
    "        value = value_str.split(':', 1)[1].strip().lower()\n",
    "    else:\n",
    "        value = value_str.strip().lower()\n",
    "    \n",
    "    # Convert to binary based on Celiac Disease presence\n",
    "    if 'celiac disease' in value:\n",
    "        return 1\n",
    "    elif 'cvid' in value or 'healthy control' in value:\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value_str):\n",
    "    \"\"\"Convert age string to continuous value (not used as age is not available)\"\"\"\n",
    "    return None\n",
    "\n",
    "def convert_gender(value_str):\n",
    "    \"\"\"Convert gender string to binary value (not used as gender is not available)\"\"\"\n",
    "    return None\n",
    "\n",
    "# Check trait data availability\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Save metadata for 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",
    "# If trait data is available, extract clinical features\n",
    "if is_trait_available:\n",
    "    # Load the clinical data\n",
    "    clinical_data = pd.DataFrame(\n",
    "        {0: ['disease state: CVID with increased intraepithelial lymphocytes', \n",
    "             'disease state: CVID without increased intraepithelial lymphocytes', \n",
    "             'disease state: celiac disease', \n",
    "             'disease state: healthy controls'],\n",
    "         1: ['tissue: duodenal biopsy'] * 4}\n",
    "    )\n",
    "    \n",
    "    # Extract clinical features\n",
    "    selected_clinical_df = geo_select_clinical_features(\n",
    "        clinical_df=clinical_data,\n",
    "        trait=trait,\n",
    "        trait_row=trait_row,\n",
    "        convert_trait=convert_trait,\n",
    "        age_row=age_row,\n",
    "        convert_age=convert_age,\n",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender\n",
    "    )\n",
    "    \n",
    "    # Preview the extracted clinical features\n",
    "    preview = preview_df(selected_clinical_df)\n",
    "    print(\"Clinical Features Preview:\", preview)\n",
    "    \n",
    "    # Create directory if it doesn't exist\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    \n",
    "    # Save the clinical data to CSV\n",
    "    selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3757cfed",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "1cb8f8b7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:01:44.190568Z",
     "iopub.status.busy": "2025-03-25T08:01:44.190461Z",
     "iopub.status.idle": "2025-03-25T08:01:44.451405Z",
     "shell.execute_reply": "2025-03-25T08:01:44.451014Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Matrix file found: ../../input/GEO/Celiac_Disease/GSE72625/GSE72625_series_matrix.txt.gz\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape: (47323, 47)\n",
      "First 20 gene/probe identifiers:\n",
      "Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209',\n",
      "       'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229',\n",
      "       'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236',\n",
      "       'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253',\n",
      "       'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262'],\n",
      "      dtype='object', name='ID')\n"
     ]
    }
   ],
   "source": [
    "# 1. Get the SOFT and matrix file paths again \n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "print(f\"Matrix file found: {matrix_file}\")\n",
    "\n",
    "# 2. Use the get_genetic_data function from the library to get the gene_data\n",
    "try:\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    print(f\"Gene data shape: {gene_data.shape}\")\n",
    "    \n",
    "    # 3. Print the first 20 row IDs (gene or probe identifiers)\n",
    "    print(\"First 20 gene/probe identifiers:\")\n",
    "    print(gene_data.index[:20])\n",
    "except Exception as e:\n",
    "    print(f\"Error extracting gene data: {e}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c1063e1e",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "1321fdcb",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:01:44.453182Z",
     "iopub.status.busy": "2025-03-25T08:01:44.453058Z",
     "iopub.status.idle": "2025-03-25T08:01:44.454965Z",
     "shell.execute_reply": "2025-03-25T08:01:44.454681Z"
    }
   },
   "outputs": [],
   "source": [
    "# Looking at the identifiers, these are Illumina microarray probe IDs (starting with ILMN_)\n",
    "# These are not human gene symbols and will need to be mapped to gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "862241cc",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "48da686a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:01:44.456660Z",
     "iopub.status.busy": "2025-03-25T08:01:44.456538Z",
     "iopub.status.idle": "2025-03-25T08:01:49.709282Z",
     "shell.execute_reply": "2025-03-25T08:01:49.708887Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Species': [nan, nan, nan, nan, nan], 'Source': [nan, nan, nan, nan, nan], 'Search_Key': [nan, nan, nan, nan, nan], 'Transcript': [nan, nan, nan, nan, nan], 'ILMN_Gene': [nan, nan, nan, nan, nan], 'Source_Reference_ID': [nan, nan, nan, nan, nan], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Unigene_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': [nan, nan, nan, nan, nan], 'Symbol': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB'], 'Protein_Product': [nan, nan, nan, nan, 'thrB'], 'Probe_Id': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5090180.0, 6510136.0, 7560739.0, 1450438.0, 1240647.0], 'Probe_Type': [nan, nan, nan, nan, nan], 'Probe_Start': [nan, nan, nan, nan, nan], 'SEQUENCE': ['GAATAAAGAACAATCTGCTGATGATCCCTCCGTGGATCTGATTCGTGTAA', 'CCATGTGATACGAGGGCGCGTAGTTTGCATTATCGTTTTTATCGTTTCAA', 'CCGACAGATGTATGTAAGGCCAACGTGCTCAAATCTTCATACAGAAAGAT', 'TCTGTCACTGTCAGGAAAGTGGTAAAACTGCAACTCAATTACTGCAATGC', 'CTTGTGCCTGAGCTGTCAAAAGTAGAGCACGTCGCCGAGATGAAGGGCGC'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': [nan, nan, nan, nan, nan], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan]}\n"
     ]
    }
   ],
   "source": [
    "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "\n",
    "# 2. 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": "a926a255",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "8802a84b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:01:49.711132Z",
     "iopub.status.busy": "2025-03-25T08:01:49.710964Z",
     "iopub.status.idle": "2025-03-25T08:01:50.608938Z",
     "shell.execute_reply": "2025-03-25T08:01:50.608553Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping shape: (44837, 2)\n",
      "First 5 rows of gene mapping:\n",
      "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Gene': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB']}\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data shape after mapping: (21464, 47)\n",
      "First 10 gene symbols after mapping:\n",
      "Index(['A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1', 'A3GALT2',\n",
      "       'A4GALT', 'A4GNT'],\n",
      "      dtype='object', name='Gene')\n",
      "Gene expression data shape after normalization: (20259, 47)\n",
      "First 10 normalized gene symbols:\n",
      "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT',\n",
      "       'A4GNT', 'AAA1', 'AAAS'],\n",
      "      dtype='object', name='Gene')\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to ../../output/preprocess/Celiac_Disease/gene_data/GSE72625.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify columns for gene mapping\n",
    "# From the previous outputs, we can see that:\n",
    "# - Gene expression data has index 'ID' with identifiers like ILMN_1343291\n",
    "# - Gene annotation data has 'ID' column with same ILMN_ format identifiers \n",
    "# - Gene annotation data has 'Symbol' column which contains gene symbols\n",
    "\n",
    "# 2. Get gene mapping dataframe using the get_gene_mapping function\n",
    "gene_mapping = get_gene_mapping(gene_annotation, 'ID', 'Symbol')\n",
    "print(f\"Gene mapping shape: {gene_mapping.shape}\")\n",
    "print(\"First 5 rows of gene mapping:\")\n",
    "print(preview_df(gene_mapping))\n",
    "\n",
    "# 3. Apply 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 10 gene symbols after mapping:\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# Normalize gene symbols to ensure consistency across the dataset\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Gene expression data shape after normalization: {gene_data.shape}\")\n",
    "print(\"First 10 normalized gene symbols:\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# Save the gene expression data to a CSV file\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Gene expression data saved to {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2717b10b",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "f21a2fda",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:01:50.610797Z",
     "iopub.status.busy": "2025-03-25T08:01:50.610654Z",
     "iopub.status.idle": "2025-03-25T08:02:00.764795Z",
     "shell.execute_reply": "2025-03-25T08:02:00.764369Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical data shape: (1, 47)\n",
      "Clinical data preview:\n",
      "{'GSM1866896': [0.0], 'GSM1866897': [0.0], 'GSM1866898': [0.0], 'GSM1866899': [0.0], 'GSM1866900': [0.0], 'GSM1866901': [0.0], 'GSM1866902': [0.0], 'GSM1866903': [0.0], 'GSM1866904': [0.0], 'GSM1866905': [0.0], 'GSM1866906': [0.0], 'GSM1866907': [0.0], 'GSM1866908': [0.0], 'GSM1866909': [0.0], 'GSM1866910': [0.0], 'GSM1866911': [0.0], 'GSM1866912': [0.0], 'GSM1866913': [0.0], 'GSM1866914': [0.0], 'GSM1866915': [0.0], 'GSM1866916': [1.0], 'GSM1866917': [1.0], 'GSM1866918': [1.0], 'GSM1866919': [1.0], 'GSM1866920': [1.0], 'GSM1866921': [1.0], 'GSM1866922': [1.0], 'GSM1866923': [1.0], 'GSM1866924': [1.0], 'GSM1866925': [1.0], 'GSM1866926': [0.0], 'GSM1866927': [0.0], 'GSM1866928': [0.0], 'GSM1866929': [0.0], 'GSM1866930': [0.0], 'GSM1866931': [0.0], 'GSM1866932': [0.0], 'GSM1866933': [0.0], 'GSM1866934': [0.0], 'GSM1866935': [0.0], 'GSM1866936': [0.0], 'GSM1866937': [0.0], 'GSM1866938': [0.0], 'GSM1866939': [0.0], 'GSM1866940': [0.0], 'GSM1866941': [0.0], 'GSM1866942': [0.0]}\n",
      "Linked data shape before handling missing values: (47, 20260)\n",
      "Linked data first few columns:\n",
      "Index(['Celiac_Disease', 'A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2',\n",
      "       'A4GALT', 'A4GNT', 'AAA1'],\n",
      "      dtype='object')\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data shape after handling missing values: (47, 20260)\n",
      "For the feature 'Celiac_Disease', the least common label is '1.0' with 10 occurrences. This represents 21.28% of the dataset.\n",
      "The distribution of the feature 'Celiac_Disease' in this dataset is fine.\n",
      "\n",
      "Data is usable. Saving to ../../output/preprocess/Celiac_Disease/GSE72625.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Re-load clinical data from matrix file to ensure we have the correct data\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\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",
    "# Re-extract clinical features with the properly loaded clinical data\n",
    "selected_clinical_df = geo_select_clinical_features(\n",
    "    clinical_df=clinical_data,\n",
    "    trait=trait,\n",
    "    trait_row=trait_row,\n",
    "    convert_trait=convert_trait,\n",
    "    age_row=age_row,\n",
    "    convert_age=convert_age,\n",
    "    gender_row=gender_row,\n",
    "    convert_gender=convert_gender\n",
    ")\n",
    "\n",
    "print(f\"Clinical data shape: {selected_clinical_df.shape}\")\n",
    "print(\"Clinical data preview:\")\n",
    "print(preview_df(selected_clinical_df))\n",
    "\n",
    "# 2. Link the clinical and genetic data with the 'geo_link_clinical_genetic_data' function\n",
    "try:\n",
    "    linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data)\n",
    "    print(f\"Linked data shape before handling missing values: {linked_data.shape}\")\n",
    "    print(\"Linked data first few columns:\")\n",
    "    print(linked_data.columns[:10])\n",
    "    \n",
    "    # 3. Handle missing values in the linked data\n",
    "    linked_data = handle_missing_values(linked_data, trait)\n",
    "    print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
    "    \n",
    "    # 4. Determine whether the trait and demographic features are severely biased\n",
    "    is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "    \n",
    "    # 5. Conduct quality check and save the cohort information\n",
    "    is_usable = validate_and_save_cohort_info(\n",
    "        is_final=True, \n",
    "        cohort=cohort, \n",
    "        info_path=json_path, \n",
    "        is_gene_available=True, \n",
    "        is_trait_available=True, \n",
    "        is_biased=is_trait_biased, \n",
    "        df=unbiased_linked_data,\n",
    "        note=\"Dataset contains gene expression from duodenal biopsies of Celiac Disease patients, CVID patients, and healthy controls\"\n",
    "    )\n",
    "    \n",
    "    # 6. If the linked data is usable, save it as a CSV file\n",
    "    if is_usable:\n",
    "        print(f\"Data is usable. Saving to {out_data_file}\")\n",
    "        os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "        unbiased_linked_data.to_csv(out_data_file)\n",
    "    else:\n",
    "        print(\"Data is not usable. Not saving linked data file.\")\n",
    "        \n",
    "except Exception as e:\n",
    "    print(f\"Error in data linking or processing: {e}\")\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=True, \n",
    "        df=pd.DataFrame(),\n",
    "        note=f\"Error processing data: {e}\"\n",
    "    )\n",
    "    print(\"Data is not usable due to processing error.\")"
   ]
  }
 ],
 "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
}