File size: 24,721 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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "e1978157",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:27:53.378968Z",
     "iopub.status.busy": "2025-03-25T06:27:53.378566Z",
     "iopub.status.idle": "2025-03-25T06:27:53.551025Z",
     "shell.execute_reply": "2025-03-25T06:27:53.550668Z"
    }
   },
   "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 = \"Amyotrophic_Lateral_Sclerosis\"\n",
    "cohort = \"GSE212131\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Amyotrophic_Lateral_Sclerosis\"\n",
    "in_cohort_dir = \"../../input/GEO/Amyotrophic_Lateral_Sclerosis/GSE212131\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/GSE212131.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE212131.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE212131.csv\"\n",
    "json_path = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f2541d9b",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "42088e0a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:27:53.552448Z",
     "iopub.status.busy": "2025-03-25T06:27:53.552296Z",
     "iopub.status.idle": "2025-03-25T06:27:53.625987Z",
     "shell.execute_reply": "2025-03-25T06:27:53.625641Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Establishing mRNA and miRNA interactions driving disease heterogeneity in ALS patient survival (microarray)\"\n",
      "!Series_summary\t\"Transcriptomic analysis of lymphoblastoid cell lines from ALS patients with varying disease duration\"\n",
      "!Series_summary\t\"Amyotrophic lateral sclerosis (ALS) is a fatal neurodegenerative disease, associated with the degeneration of both upper and lower motor neurons of the motor cortex, brainstem and spinal cord. Death in most patients results from respiratory failure within 3-4 years from symptom onset. However, due to disease heterogeneity some individuals survive only months from symptom onset while others live for several years. Identifying specific biomarkers that aid in establishing disease prognosis, particularly in terms of predicting disease progression, will help our understanding of ALS pathophysiology and could be used to monitor a patient’s response to drugs and therapeutic agents.  Transcriptomic profiling technologies are continually evolving, enabling us to identify key gene changes in biological processes associated with disease. MicroRNAs (miRNAs) are small non-coding RNAs typically associated with regulating gene expression, by degrading mRNA or reducing levels of gene expression. Being able to associate gene expression changes with corresponding miRNA changes would help to distinguish a more complex biomarker signature enabling us to address key challenges associated with complex diseases such as ALS.\"\n",
      "!Series_overall_design\t\"The present study aimed to investigate the transcriptomic profile (mRNA and miRNA) of lymphoblastoid cell lines (LCLs) from ALS patients to identify key signatures that are distinguishable in those patients who suffered a short disease duration (< 12 months) compared to those that had a longer disease duration (>6 years). Affymetrix Human Exon 1.0ST GeneChip microarrays were used to assess mRNA/gene changes, while small RNA sequencing of miRNA extracted from peripheral LCL’s from ALS patients with short and long disease was performed using the Illumina TruSeq Small RNA library preparation kit and Illumina HiScanSQ.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['gender: Female', 'gender: Male']}\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": "0ec1c5a4",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "ed0f9c6c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:27:53.627310Z",
     "iopub.status.busy": "2025-03-25T06:27:53.627197Z",
     "iopub.status.idle": "2025-03-25T06:27:53.633087Z",
     "shell.execute_reply": "2025-03-25T06:27:53.632752Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import os\n",
    "import json\n",
    "from typing import Optional, Callable, Dict, Any\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information, this dataset contains gene expression data from microarray analysis\n",
    "is_gene_available = True  # Affymetrix Human Exon 1.0ST GeneChip microarrays were used\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "\n",
    "# For trait: The dataset is comparing ALS patients with short duration (<12 months) vs long duration (>6 years)\n",
    "# This can be inferred from the background information, but not directly available in the sample characteristics\n",
    "trait_row = None  # Not directly available in sample characteristics\n",
    "\n",
    "# For age: Not provided in the sample characteristics\n",
    "age_row = None\n",
    "\n",
    "# For gender: Available in the sample characteristics at index 0\n",
    "gender_row = 0\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "\n",
    "# For trait (not used since trait_row is None, but defined for completeness)\n",
    "def convert_trait(value):\n",
    "    return None  # Not directly available\n",
    "\n",
    "# For age (not used since age_row is None, but defined for completeness)\n",
    "def convert_age(value):\n",
    "    return None\n",
    "\n",
    "# For gender\n",
    "def convert_gender(value):\n",
    "    if value is None:\n",
    "        return None\n",
    "    # Extract the value after the colon\n",
    "    if \":\" in value:\n",
    "        gender = value.split(\":\")[1].strip().lower()\n",
    "        if \"female\" in gender:\n",
    "            return 0\n",
    "        elif \"male\" in gender:\n",
    "            return 1\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Trait data availability is determined by whether trait_row is None\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Initial validation\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 - Skip this step since trait_row is None\n",
    "# No clinical feature extraction needed as trait_row is None\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4c92c5cb",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "cc3b51e3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:27:53.634184Z",
     "iopub.status.busy": "2025-03-25T06:27:53.634079Z",
     "iopub.status.idle": "2025-03-25T06:27:53.719059Z",
     "shell.execute_reply": "2025-03-25T06:27:53.718718Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "First 20 gene/probe identifiers:\n",
      "Index(['2315554', '2315633', '2315674', '2315739', '2315894', '2315918',\n",
      "       '2315951', '2316218', '2316245', '2316379', '2316558', '2316605',\n",
      "       '2316746', '2316905', '2316953', '2317246', '2317317', '2317434',\n",
      "       '2317472', '2317512'],\n",
      "      dtype='object', name='ID')\n",
      "\n",
      "Gene data dimensions: 22011 genes × 42 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": "3a01cd03",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "034483df",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:27:53.720412Z",
     "iopub.status.busy": "2025-03-25T06:27:53.720300Z",
     "iopub.status.idle": "2025-03-25T06:27:53.722310Z",
     "shell.execute_reply": "2025-03-25T06:27:53.722017Z"
    }
   },
   "outputs": [],
   "source": [
    "# Review the gene identifiers in the data\n",
    "# Looking at the identifiers '2315554', '2315633', etc., these appear to be probe IDs \n",
    "# from a microarray platform rather than standard human gene symbols.\n",
    "# Standard human gene symbols would be alphanumeric like GAPDH, TP53, etc.\n",
    "# These purely numeric identifiers likely need to be mapped to gene symbols.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e4af1676",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "69267cc2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:27:53.723506Z",
     "iopub.status.busy": "2025-03-25T06:27:53.723400Z",
     "iopub.status.idle": "2025-03-25T06:27:56.269893Z",
     "shell.execute_reply": "2025-03-25T06:27:56.269506Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['2315100', '2315106', '2315109', '2315111', '2315113'], 'GB_LIST': ['NR_024005,NR_034090,NR_024004,AK093685', 'DQ786314', nan, nan, 'DQ786265'], 'SPOT_ID': ['chr1:11884-14409', 'chr1:14760-15198', 'chr1:19408-19712', 'chr1:25142-25532', 'chr1:27563-27813'], 'seqname': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], 'RANGE_GB': ['NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10'], 'RANGE_STRAND': ['+', '+', '+', '+', '+'], 'RANGE_START': ['11884', '14760', '19408', '25142', '27563'], 'RANGE_STOP': ['14409', '15198', '19712', '25532', '27813'], 'total_probes': ['20', '8', '4', '4', '4'], 'gene_assignment': ['NR_024005 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771 /// NR_034090 // DDX11L9 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 9 // 15q26.3 // 100288486 /// NR_024004 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771 /// AK093685 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771', '---', '---', '---', '---'], 'mrna_assignment': ['NR_024005 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 (DDX11L2), transcript variant 2, non-coding RNA. // chr1 // 100 // 80 // 16 // 16 // 0 /// NR_034090 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 9 (DDX11L9), non-coding RNA. // chr1 // 100 // 80 // 16 // 16 // 0 /// NR_024004 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 (DDX11L2), transcript variant 1, non-coding RNA. // chr1 // 100 // 75 // 15 // 15 // 0 /// AK093685 // GenBank // Homo sapiens cDNA FLJ36366 fis, clone THYMU2007824. // chr1 // 94 // 80 // 15 // 16 // 0 /// ENST00000513886 // ENSEMBL // cdna:known chromosome:GRCh37:16:61555:64090:1 gene:ENSG00000233614 // chr1 // 100 // 80 // 16 // 16 // 0 /// ENST00000456328 // ENSEMBL // cdna:known chromosome:GRCh37:1:11869:14409:1 gene:ENSG00000223972 // chr1 // 100 // 80 // 16 // 16 // 0 /// ENST00000518655 // ENSEMBL // cdna:known chromosome:GRCh37:1:11869:14409:1 gene:ENSG00000253101 // chr1 // 100 // 80 // 16 // 16 // 0', 'DQ786314 // GenBank // Homo sapiens clone HLS_IMAGE_811138 mRNA sequence. // chr1 // 100 // 38 // 3 // 3 // 0', '---', '---', 'DQ786265 // GenBank // Homo sapiens clone HLS_IMAGE_298685 mRNA sequence. // chr1 // 100 // 100 // 4 // 4 // 0'], 'category': ['main', 'main', '---', '---', 'main']}\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": "0d881b65",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "889fb86e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:27:56.271253Z",
     "iopub.status.busy": "2025-03-25T06:27:56.271130Z",
     "iopub.status.idle": "2025-03-25T06:27:56.700734Z",
     "shell.execute_reply": "2025-03-25T06:27:56.700332Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping preview:\n",
      "{'ID': ['2315100', '2315106', '2315109', '2315111', '2315113'], 'Gene': ['NR_024005 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771 /// NR_034090 // DDX11L9 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 9 // 15q26.3 // 100288486 /// NR_024004 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771 /// AK093685 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771', '---', '---', '---', '---']}\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene data dimensions after mapping: 48895 genes × 42 samples\n",
      "\n",
      "First 20 gene symbols after mapping:\n",
      "Index(['A-', 'A-2', 'A-52', 'A-E', 'A-I', 'A-II', 'A-IV', 'A-V', 'A0', 'A1',\n",
      "       'A1-', 'A10', 'A11', 'A12', 'A13', 'A14', 'A16', 'A1BG', 'A1BG-AS',\n",
      "       'A1CF'],\n",
      "      dtype='object', name='Gene')\n",
      "\n",
      "Number of genes after mapping: 48895\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the relevant columns in the gene annotation dataframe\n",
    "# From the preview, we can see:\n",
    "# - 'ID' column contains the numeric identifiers (like 2315100) which match the gene expression indices\n",
    "# - 'gene_assignment' column contains the gene symbols and additional information\n",
    "\n",
    "# 2. Extract gene mapping from gene annotation\n",
    "# We'll use the 'ID' and 'gene_assignment' columns for mapping\n",
    "gene_mapping = get_gene_mapping(gene_annotation, 'ID', 'gene_assignment')\n",
    "\n",
    "# Print a preview of the gene mapping\n",
    "print(\"Gene mapping preview:\")\n",
    "print(preview_df(gene_mapping))\n",
    "\n",
    "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n",
    "# This handles many-to-many relationships between probes and genes\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "\n",
    "# Print the dimensions of the gene expression data after mapping\n",
    "print(f\"\\nGene data dimensions after mapping: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
    "\n",
    "# Print the first 20 gene symbols after mapping\n",
    "print(\"\\nFirst 20 gene symbols after mapping:\")\n",
    "print(gene_data.index[:20])\n",
    "\n",
    "# Check if any genes were filtered out during mapping (genes with no symbols)\n",
    "print(f\"\\nNumber of genes after mapping: {len(gene_data)}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "52b26b7b",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "3fe03a50",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:27:56.702129Z",
     "iopub.status.busy": "2025-03-25T06:27:56.702007Z",
     "iopub.status.idle": "2025-03-25T06:27:57.310662Z",
     "shell.execute_reply": "2025-03-25T06:27:57.310273Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape after normalization: (18418, 42)\n",
      "First 5 gene symbols after normalization: Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1'], dtype='object', name='Gene')\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE212131.csv\n",
      "Sample IDs in clinical data:\n",
      "Index(['!Sample_geo_accession', 'GSM6509811', 'GSM6509812', 'GSM6509813',\n",
      "       'GSM6509814'],\n",
      "      dtype='object') ...\n",
      "Sample IDs in gene expression data:\n",
      "Index(['GSM6509811', 'GSM6509812', 'GSM6509813', 'GSM6509814', 'GSM6509815'], dtype='object') ...\n",
      "Trait data is unavailable in this dataset.\n",
      "Abnormality detected in the cohort: GSE212131. Preprocessing failed.\n",
      "Dataset deemed not usable for associational studies.\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the index of gene expression data\n",
    "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
    "print(f\"First 5 gene symbols after normalization: {normalized_gene_data.index[:5]}\")\n",
    "\n",
    "# Save the normalized gene data\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "normalized_gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
    "\n",
    "# 2. Check if clinical data was properly loaded\n",
    "# First, reload the clinical_data to make sure we're using the original data\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n",
    "\n",
    "# Print the sample IDs to understand the data structure\n",
    "print(\"Sample IDs in clinical data:\")\n",
    "print(clinical_data.columns[:5], \"...\")  # Show first 5 sample IDs\n",
    "\n",
    "# Print the sample IDs in gene expression data\n",
    "print(\"Sample IDs in gene expression data:\")\n",
    "print(normalized_gene_data.columns[:5], \"...\")  # Show first 5 sample IDs\n",
    "\n",
    "# Explicitly set trait availability based on findings from previous steps\n",
    "is_trait_available = False  # From step 2, we determined trait_row was None\n",
    "linked_data = None\n",
    "\n",
    "if is_trait_available:\n",
    "    # This block won't execute because is_trait_available=False\n",
    "    # But keeping it here for completeness\n",
    "    selected_clinical_df = geo_select_clinical_features(\n",
    "        clinical_df=clinical_data,\n",
    "        trait=trait,\n",
    "        trait_row=0,  # Placeholder, won't be used\n",
    "        convert_trait=lambda x: None,  # Placeholder, won't be used\n",
    "        age_row=None,\n",
    "        convert_age=None,\n",
    "        gender_row=0,\n",
    "        convert_gender=lambda x: None  # Placeholder, won't be used\n",
    "    )\n",
    "    \n",
    "    print(f\"Clinical data shape: {selected_clinical_df.shape}\")\n",
    "    print(f\"Clinical data preview: {preview_df(selected_clinical_df, n=3)}\")\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 saved to {out_clinical_data_file}\")\n",
    "    \n",
    "    # Link clinical and genetic data\n",
    "    linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n",
    "    print(f\"Linked data shape before handling missing values: {linked_data.shape}\")\n",
    "    \n",
    "    # 3. Handle missing values\n",
    "    linked_data = handle_missing_values(linked_data, trait)\n",
    "    print(f\"Data shape after handling missing values: {linked_data.shape}\")\n",
    "    \n",
    "    # 4. Determine if trait and demographic features are biased\n",
    "    is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "    print(f\"Data shape after removing biased features: {linked_data.shape}\")\n",
    "else:\n",
    "    print(\"Trait data is unavailable in this dataset.\")\n",
    "    is_biased = True  # Dataset can't be used without trait data\n",
    "    linked_data = pd.DataFrame()  # Empty DataFrame\n",
    "\n",
    "# 5. Validate and save cohort info\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=is_trait_available,\n",
    "    is_biased=is_biased,\n",
    "    df=linked_data if not linked_data.empty else pd.DataFrame(index=normalized_gene_data.columns),\n",
    "    note=\"Dataset contains gene expression data from ALS patients, but lacks trait information (disease status) required for associational studies.\"\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 associational studies.\")"
   ]
  }
 ],
 "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
}