File size: 30,672 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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "4d415b3f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:28:42.673897Z",
     "iopub.status.busy": "2025-03-25T06:28:42.673682Z",
     "iopub.status.idle": "2025-03-25T06:28:42.841808Z",
     "shell.execute_reply": "2025-03-25T06:28:42.841478Z"
    }
   },
   "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 = \"GSE61322\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Amyotrophic_Lateral_Sclerosis\"\n",
    "in_cohort_dir = \"../../input/GEO/Amyotrophic_Lateral_Sclerosis/GSE61322\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/GSE61322.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE61322.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE61322.csv\"\n",
    "json_path = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "19a9c285",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "dc9d5f91",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:28:42.843277Z",
     "iopub.status.busy": "2025-03-25T06:28:42.843128Z",
     "iopub.status.idle": "2025-03-25T06:28:42.906276Z",
     "shell.execute_reply": "2025-03-25T06:28:42.905959Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Mutation of senataxin alters disease-specific transcriptional networks in patients with ataxia with oculomotor apraxia type 2 [03_AOA2_patient_blood_2011]\"\n",
      "!Series_summary\t\"Senataxin, encoded by the SETX gene, contributes to multiple aspects of gene expression, including transcription and RNA processing. Mutations in SETX cause the recessive disorder ataxia with oculomotor apraxia type 2 (AOA2) and a dominant juvenile form of amyotrophic lateral sclerosis (ALS4). To assess the functional role of senataxin in disease, we examined differential gene expression in AOA2 patient fibroblasts, identifying a core set of genes showing altered expression by microarray and RNA-sequencing. To determine whether AOA2 and ALS4 mutations differentially affect gene expression, we overexpressed disease-specific SETX mutations in senataxin-haploinsufficient fibroblasts and observed changes in distinct sets of genes. This implicates mutation-specific alterations of senataxin function in disease pathogenesis and provides a novel example of allelic neurogenetic disorders with differing gene expression profiles. Weighted gene co-expression network analysis (WGCNA) demonstrated these senataxin-associated genes to be involved in both mutation-specific and shared functional gene networks. To assess this in vivo, we performed gene expression analysis on peripheral blood from members of 12 different AOA2 families and identified an AOA2-specific transcriptional signature. WGCNA identified two gene modules highly enriched for this transcriptional signature in the peripheral blood of all AOA2 patients studied. These modules were disease-specific and preserved in patient fibroblasts and in the cerebellum of Setx knockout mice demonstrating conservation across species and cell types, including neurons. These results identify novel genes and cellular pathways related to senataxin function in normal and disease states, and implicate alterations in gene expression as underlying the phenotypic differences between AOA2 and ALS4.\"\n",
      "!Series_overall_design\t\"Total RNA samples obtained from 1) an AOA2 patient and carrier fibroblast cell lines, 2) 2 biological replicates of haploinsufficient SETX fibroblast cell lines transfected with one of 4 different wild-type and mutant SETX constructs, 3) peripheral blood from 33 patients and carriers across 12 families, and 4) 2 tissues from 2 Setx knockout and 2 control mice were analyzed using expression microarray.\"\n",
      "!Series_overall_design\t\"\"\n",
      "!Series_overall_design\t\"This submission represents the microarray component of study.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['diagnosis: carrier', 'diagnosis: affected'], 1: ['disease: AOA2'], 2: ['definite analysis: definite', 'definite analysis: presumed']}\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": "ae8b27e5",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "5f3da0a4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:28:42.907407Z",
     "iopub.status.busy": "2025-03-25T06:28:42.907294Z",
     "iopub.status.idle": "2025-03-25T06:28:42.913238Z",
     "shell.execute_reply": "2025-03-25T06:28:42.912936Z"
    }
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "import json\n",
    "from typing import Callable, Optional, Dict, Any\n",
    "import numpy as np\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\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Identify the keys for trait, age, and gender\n",
    "# From the Sample Characteristics, we can see that:\n",
    "# Key 0 has ['diagnosis: carrier', 'diagnosis: affected'] which can be used for the trait\n",
    "trait_row = 0\n",
    "# Age is not explicitly available in the provided sample characteristics\n",
    "age_row = None\n",
    "# Gender is not explicitly available in the provided sample characteristics\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "def convert_trait(value: str) -> int:\n",
    "    \"\"\"Convert trait value to binary format.\"\"\"\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    if isinstance(value, str):\n",
    "        value = value.lower().strip()\n",
    "        if \":\" in value:\n",
    "            value = value.split(\":\", 1)[1].strip()\n",
    "        \n",
    "        if \"affected\" in value:\n",
    "            return 1  # For affected patients (AOA2)\n",
    "        elif \"carrier\" in value:\n",
    "            return 0  # For carriers/controls\n",
    "    \n",
    "    return None\n",
    "\n",
    "def convert_age(value: str) -> float:\n",
    "    \"\"\"Convert age value to continuous format.\"\"\"\n",
    "    # Age data is not available, but this function is defined for completeness\n",
    "    return None\n",
    "\n",
    "def convert_gender(value: str) -> int:\n",
    "    \"\"\"Convert gender value to binary format.\"\"\"\n",
    "    # Gender data is not available, but this function is defined for completeness\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait data availability\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Save initial information\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 is_trait_available:\n",
    "    # Load clinical data\n",
    "    try:\n",
    "        files = os.listdir(in_cohort_dir)\n",
    "        clinical_data_file = None\n",
    "        for file in files:\n",
    "            if file.endswith(\"_series_matrix.txt\"):\n",
    "                clinical_data_file = os.path.join(in_cohort_dir, file)\n",
    "                break\n",
    "        \n",
    "        if clinical_data_file:\n",
    "            # Load the file to extract sample characteristics\n",
    "            sample_data = []\n",
    "            with open(clinical_data_file, 'r') as f:\n",
    "                for line in f:\n",
    "                    if line.startswith('!Sample_char') or line.startswith('!Sample_characteristics'):\n",
    "                        parts = line.strip().split('\\t')\n",
    "                        if len(parts) > 1:\n",
    "                            sample_data.append(parts[1:])\n",
    "            \n",
    "            # Create clinical dataframe if data is found\n",
    "            if sample_data:\n",
    "                # Transpose the data to have samples as columns\n",
    "                clinical_df = pd.DataFrame(sample_data)\n",
    "                \n",
    "                # Extract clinical features using the library function\n",
    "                selected_clinical_df = geo_select_clinical_features(\n",
    "                    clinical_df=clinical_df,\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 selected clinical features\n",
    "                preview = preview_df(selected_clinical_df)\n",
    "                print(\"Preview of selected clinical features:\")\n",
    "                print(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 clinical data\n",
    "                selected_clinical_df.to_csv(out_clinical_data_file)\n",
    "                print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "    except Exception as e:\n",
    "        print(f\"Error processing clinical data: {str(e)}\")\n",
    "        # Even if extraction fails, we've already recorded the trait availability\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "346b19fd",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "579dcf78",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:28:42.914260Z",
     "iopub.status.busy": "2025-03-25T06:28:42.914154Z",
     "iopub.status.idle": "2025-03-25T06:28:42.983705Z",
     "shell.execute_reply": "2025-03-25T06:28:42.983326Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "First 20 gene/probe identifiers:\n",
      "Index(['ILMN_1343291', 'ILMN_1651209', 'ILMN_1651228', 'ILMN_1651229',\n",
      "       'ILMN_1651235', 'ILMN_1651236', 'ILMN_1651237', 'ILMN_1651238',\n",
      "       'ILMN_1651254', 'ILMN_1651260', 'ILMN_1651262', 'ILMN_1651268',\n",
      "       'ILMN_1651278', 'ILMN_1651282', 'ILMN_1651285', 'ILMN_1651286',\n",
      "       'ILMN_1651292', 'ILMN_1651303', 'ILMN_1651309', 'ILMN_1651315'],\n",
      "      dtype='object', name='ID')\n",
      "\n",
      "Gene data dimensions: 24525 genes × 33 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": "2432e69a",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "f59b41a2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:28:42.985047Z",
     "iopub.status.busy": "2025-03-25T06:28:42.984927Z",
     "iopub.status.idle": "2025-03-25T06:28:42.986743Z",
     "shell.execute_reply": "2025-03-25T06:28:42.986465Z"
    }
   },
   "outputs": [],
   "source": [
    "# The identifiers starting with \"ILMN_\" are Illumina probe IDs, not human gene symbols\n",
    "# These are microarray probe identifiers from Illumina's BeadArray technology\n",
    "# They need to be mapped to human gene symbols for biological interpretation\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7d442aa2",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "8b159250",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:28:42.987930Z",
     "iopub.status.busy": "2025-03-25T06:28:42.987827Z",
     "iopub.status.idle": "2025-03-25T06:28:44.715592Z",
     "shell.execute_reply": "2025-03-25T06:28:44.715197Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['ILMN_1722532', 'ILMN_1708805', 'ILMN_1672526', 'ILMN_1703284', 'ILMN_2185604'], 'Species': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Source': ['RefSeq', 'RefSeq', 'RefSeq', 'RefSeq', 'RefSeq'], 'Search_Key': ['ILMN_25544', 'ILMN_10519', 'ILMN_17234', 'ILMN_502', 'ILMN_19244'], 'Transcript': ['ILMN_25544', 'ILMN_10519', 'ILMN_17234', 'ILMN_502', 'ILMN_19244'], 'ILMN_Gene': ['JMJD1A', 'NCOA3', 'LOC389834', 'SPIRE2', 'C17ORF77'], 'Source_Reference_ID': ['NM_018433.3', 'NM_006534.2', 'NM_001013655.1', 'NM_032451.1', 'NM_152460.2'], 'RefSeq_ID': ['NM_018433.3', 'NM_006534.2', 'NM_001013655.1', 'NM_032451.1', 'NM_152460.2'], 'Entrez_Gene_ID': [55818.0, 8202.0, 389834.0, 84501.0, 146723.0], 'GI': [46358420.0, 32307123.0, 61966764.0, 55749599.0, 48255961.0], 'Accession': ['NM_018433.3', 'NM_006534.2', 'NM_001013655.1', 'NM_032451.1', 'NM_152460.2'], 'Symbol': ['JMJD1A', 'NCOA3', 'LOC389834', 'SPIRE2', 'C17orf77'], 'Protein_Product': ['NP_060903.2', 'NP_006525.2', 'NP_001013677.1', 'NP_115827.1', 'NP_689673.2'], 'Array_Address_Id': [1240504.0, 2760390.0, 1740239.0, 6040014.0, 6550343.0], 'Probe_Type': ['S', 'A', 'S', 'S', 'S'], 'Probe_Start': [4359.0, 7834.0, 3938.0, 3080.0, 2372.0], 'SEQUENCE': ['CCAGGCTGTAAAAGCAAAACCTCGTATCAGCTCTGGAACAATACCTGCAG', 'CCACATGAAATGACTTATGGGGGATGGTGAGCTGTGACTGCTTTGCTGAC', 'CCATTGGTTCTGTTTGGCATAACCCTATTAAATGGTGCGCAGAGCTGAAT', 'ACATGTGTCCTGCCTCTCCTGGCCCTACCACATTCTGGTGCTGTCCTCAC', 'CTGCTCCAGTGAAGGGTGCACCAAAATCTCAGAAGTCACTGCTAAAGACC'], 'Chromosome': ['2', '20', '4', '16', '17'], 'Probe_Chr_Orientation': ['+', '+', '-', '+', '+'], 'Probe_Coordinates': ['86572991-86573040', '45718934-45718983', '51062-51111', '88465064-88465113', '70101790-70101839'], 'Cytoband': ['2p11.2e', '20q13.12c', nan, '16q24.3b', '17q25.1b'], 'Definition': ['Homo sapiens jumonji domain containing 1A (JMJD1A), mRNA.', 'Homo sapiens nuclear receptor coactivator 3 (NCOA3), transcript variant 2, mRNA.', 'Homo sapiens hypothetical gene supported by AK123403 (LOC389834), mRNA.', 'Homo sapiens spire homolog 2 (Drosophila) (SPIRE2), mRNA.', 'Homo sapiens chromosome 17 open reading frame 77 (C17orf77), mRNA.'], 'Ontology_Component': ['nucleus [goid 5634] [evidence IEA]', 'nucleus [goid 5634] [pmid 9267036] [evidence NAS]', nan, nan, nan], 'Ontology_Process': ['chromatin modification [goid 16568] [evidence IEA]; transcription [goid 6350] [evidence IEA]; regulation of transcription, DNA-dependent [goid 6355] [evidence IEA]', 'positive regulation of transcription, DNA-dependent [goid 45893] [pmid 15572661] [evidence NAS]; androgen receptor signaling pathway [goid 30521] [pmid 15572661] [evidence NAS]; signal transduction [goid 7165] [evidence IEA]', nan, nan, nan], 'Ontology_Function': ['oxidoreductase activity [goid 16491] [evidence IEA]; oxidoreductase activity, acting on single donors with incorporation of molecular oxygen, incorporation of two atoms of oxygen [goid 16702] [evidence IEA]; zinc ion binding [goid 8270] [evidence IEA]; metal ion binding [goid 46872] [evidence IEA]; iron ion binding [goid 5506] [evidence IEA]', 'acyltransferase activity [goid 8415] [evidence IEA]; thyroid hormone receptor binding [goid 46966] [pmid 9346901] [evidence NAS]; transferase activity [goid 16740] [evidence IEA]; transcription coactivator activity [goid 3713] [pmid 15572661] [evidence NAS]; androgen receptor binding [goid 50681] [pmid 15572661] [evidence NAS]; histone acetyltransferase activity [goid 4402] [pmid 9267036] [evidence TAS]; signal transducer activity [goid 4871] [evidence IEA]; transcription regulator activity [goid 30528] [evidence IEA]; protein binding [goid 5515] [pmid 15698540] [evidence IPI]', nan, 'zinc ion binding [goid 8270] [evidence IEA]', nan], 'Synonyms': ['JHMD2A; JMJD1; TSGA; KIAA0742; DKFZp686A24246; DKFZp686P07111', 'CAGH16; TNRC14; pCIP; ACTR; MGC141848; CTG26; AIB-1; TRAM-1; TNRC16; AIB1; SRC3; SRC-1; RAC3', nan, 'MGC117166; Spir-2', 'FLJ31882'], 'GB_ACC': ['NM_018433.3', 'NM_006534.2', 'NM_001013655.1', 'NM_032451.1', 'NM_152460.2']}\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": "46cdd07c",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "5a9013bd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:28:44.717008Z",
     "iopub.status.busy": "2025-03-25T06:28:44.716873Z",
     "iopub.status.idle": "2025-03-25T06:28:44.827400Z",
     "shell.execute_reply": "2025-03-25T06:28:44.827017Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping preview (first 5 rows):\n",
      "             ID       Gene\n",
      "0  ILMN_1722532     JMJD1A\n",
      "1  ILMN_1708805      NCOA3\n",
      "2  ILMN_1672526  LOC389834\n",
      "3  ILMN_1703284     SPIRE2\n",
      "4  ILMN_2185604   C17orf77\n",
      "\n",
      "Converted gene expression data dimensions: 17824 genes × 33 samples\n",
      "\n",
      "First 10 gene symbols:\n",
      "Index(['A1BG', 'A2BP1', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1',\n",
      "       'AAAS', 'AACS'],\n",
      "      dtype='object', name='Gene')\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the columns for probe IDs and gene symbols\n",
    "# From the annotation preview, we can see:\n",
    "# - 'ID' column contains the Illumina probe IDs matching the gene expression data index\n",
    "# - 'Symbol' column contains the corresponding gene symbols\n",
    "\n",
    "# 2. Get the gene mapping dataframe using the get_gene_mapping function\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n",
    "\n",
    "# Print a preview of the mapping\n",
    "print(\"Gene mapping preview (first 5 rows):\")\n",
    "print(gene_mapping.head())\n",
    "\n",
    "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "\n",
    "# Print information about the resulting gene expression data\n",
    "print(f\"\\nConverted gene expression data dimensions: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
    "print(\"\\nFirst 10 gene symbols:\")\n",
    "print(gene_data.index[:10])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee5ee48d",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "f64d8077",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:28:44.828773Z",
     "iopub.status.busy": "2025-03-25T06:28:44.828653Z",
     "iopub.status.idle": "2025-03-25T06:28:51.576480Z",
     "shell.execute_reply": "2025-03-25T06:28:51.575887Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape after normalization: (16856, 33)\n",
      "First 5 gene symbols after normalization: Index(['A1BG', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT'], dtype='object', name='Gene')\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE61322.csv\n",
      "Sample IDs in clinical data:\n",
      "Index(['!Sample_geo_accession', 'GSM1502059', 'GSM1502060', 'GSM1502061',\n",
      "       'GSM1502062'],\n",
      "      dtype='object') ...\n",
      "Sample IDs in gene expression data:\n",
      "Index(['GSM1502059', 'GSM1502060', 'GSM1502061', 'GSM1502062', 'GSM1502063'], dtype='object') ...\n",
      "Clinical data shape: (1, 33)\n",
      "Clinical data preview: {'GSM1502059': [0.0], 'GSM1502060': [0.0], 'GSM1502061': [0.0], 'GSM1502062': [1.0], 'GSM1502063': [0.0], 'GSM1502064': [1.0], 'GSM1502065': [1.0], 'GSM1502066': [1.0], 'GSM1502067': [1.0], 'GSM1502068': [0.0], 'GSM1502069': [1.0], 'GSM1502070': [1.0], 'GSM1502071': [1.0], 'GSM1502072': [0.0], 'GSM1502073': [1.0], 'GSM1502074': [0.0], 'GSM1502075': [1.0], 'GSM1502076': [0.0], 'GSM1502077': [1.0], 'GSM1502078': [1.0], 'GSM1502079': [0.0], 'GSM1502080': [0.0], 'GSM1502081': [0.0], 'GSM1502082': [0.0], 'GSM1502083': [0.0], 'GSM1502084': [0.0], 'GSM1502085': [0.0], 'GSM1502086': [0.0], 'GSM1502087': [1.0], 'GSM1502088': [1.0], 'GSM1502089': [0.0], 'GSM1502090': [1.0], 'GSM1502091': [0.0]}\n",
      "Clinical data saved to ../../output/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE61322.csv\n",
      "Linked data shape before handling missing values: (33, 16857)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Data shape after handling missing values: (33, 16857)\n",
      "For the feature 'Amyotrophic_Lateral_Sclerosis', the least common label is '1.0' with 15 occurrences. This represents 45.45% of the dataset.\n",
      "The distribution of the feature 'Amyotrophic_Lateral_Sclerosis' in this dataset is fine.\n",
      "\n",
      "Data shape after removing biased features: (33, 16857)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Amyotrophic_Lateral_Sclerosis/GSE61322.csv\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",
    "# Extract clinical features using the actual sample IDs\n",
    "is_trait_available = trait_row is not None\n",
    "linked_data = None\n",
    "\n",
    "if is_trait_available:\n",
    "    # Extract clinical features with proper sample IDs\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 if age_row is not None else None,\n",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender if gender_row is not None else None\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",
    "    # Make sure both dataframes have compatible indices/columns\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",
    "    if linked_data.shape[0] == 0:\n",
    "        print(\"WARNING: No samples matched between clinical and genetic data!\")\n",
    "        # Create a sample dataset for demonstration\n",
    "        print(\"Using gene data with artificial trait values for demonstration\")\n",
    "        is_trait_available = False\n",
    "        is_biased = True\n",
    "        linked_data = pd.DataFrame(index=normalized_gene_data.columns)\n",
    "        linked_data[trait] = 1  # Placeholder\n",
    "    else:\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 was determined to be unavailable in previous steps.\")\n",
    "    is_biased = True  # Set to True since we can't evaluate without trait data\n",
    "    linked_data = pd.DataFrame(index=normalized_gene_data.columns)\n",
    "    linked_data[trait] = 1  # Add a placeholder trait column\n",
    "    print(f\"Using placeholder data due to missing trait information, shape: {linked_data.shape}\")\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,\n",
    "    note=\"Dataset contains gene expression data from multiple sclerosis patients, but there were issues linking clinical and genetic data.\"\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
}