File size: 25,124 Bytes
53eb596
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "05a8536f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:54:33.654831Z",
     "iopub.status.busy": "2025-03-25T07:54:33.654673Z",
     "iopub.status.idle": "2025-03-25T07:54:33.820347Z",
     "shell.execute_reply": "2025-03-25T07:54:33.820024Z"
    }
   },
   "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 = \"Lupus_(Systemic_Lupus_Erythematosus)\"\n",
    "cohort = \"GSE112943\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Lupus_(Systemic_Lupus_Erythematosus)\"\n",
    "in_cohort_dir = \"../../input/GEO/Lupus_(Systemic_Lupus_Erythematosus)/GSE112943\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Lupus_(Systemic_Lupus_Erythematosus)/GSE112943.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Lupus_(Systemic_Lupus_Erythematosus)/gene_data/GSE112943.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Lupus_(Systemic_Lupus_Erythematosus)/clinical_data/GSE112943.csv\"\n",
    "json_path = \"../../output/preprocess/Lupus_(Systemic_Lupus_Erythematosus)/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1256620e",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "ac43afb7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:54:33.821799Z",
     "iopub.status.busy": "2025-03-25T07:54:33.821652Z",
     "iopub.status.idle": "2025-03-25T07:54:33.988480Z",
     "shell.execute_reply": "2025-03-25T07:54:33.988070Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Genome-wide analysis of gene expression of cutaneous lupus skin samples and lupus nephritis kidney samples\"\n",
      "!Series_summary\t\"Microarray gene expression analyses were performed on human skin samples from cutaneous lupus subtypes (SCLE and CCLE) and normal patients along with human kidney samples from lupus nephritis and normal patients\"\n",
      "!Series_overall_design\t\"47 deidentified human samples from formalin fixed, paraffin-embedded skin (6 chronic cutaneous lupus, 10 subacute cutaneous lupus, 10 control skin) and formalin fixed paraffin-embedded kidney (14 lupus nephritis, 7 control kidney)\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['tissue: CCLE', 'tissue: SCLE', 'tissue: Skin Control', 'tissue: Kidney Control', 'tissue: Lupus Nephritis']}\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": "83c27e7e",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "fbbb9d5e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:54:33.989802Z",
     "iopub.status.busy": "2025-03-25T07:54:33.989687Z",
     "iopub.status.idle": "2025-03-25T07:54:33.998075Z",
     "shell.execute_reply": "2025-03-25T07:54:33.997762Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical Data Preview:\n",
      "{'GSM3091745': [1.0], 'GSM3091746': [1.0], 'GSM3091747': [1.0], 'GSM3091748': [1.0], 'GSM3091749': [1.0], 'GSM3091750': [1.0], 'GSM3091751': [1.0], 'GSM3091752': [1.0], 'GSM3091753': [1.0], 'GSM3091754': [1.0], 'GSM3091755': [1.0], 'GSM3091756': [1.0], 'GSM3091757': [1.0], 'GSM3091758': [1.0], 'GSM3091759': [1.0], 'GSM3091760': [1.0], 'GSM3091765': [0.0], 'GSM3091766': [0.0], 'GSM3091767': [0.0], 'GSM3091768': [0.0], 'GSM3091769': [0.0], 'GSM3091770': [0.0], 'GSM3091771': [0.0], 'GSM3091772': [0.0], 'GSM3091773': [0.0], 'GSM3091774': [0.0], 'GSM3091775': [0.0], 'GSM3091776': [0.0], 'GSM3091777': [0.0], 'GSM3091778': [0.0], 'GSM3091779': [0.0], 'GSM3091780': [0.0], 'GSM3091781': [0.0], 'GSM3091782': [1.0], 'GSM3091783': [1.0], 'GSM3091784': [1.0], 'GSM3091785': [1.0], 'GSM3091786': [1.0], 'GSM3091787': [1.0], 'GSM3091788': [1.0], 'GSM3091789': [1.0], 'GSM3091790': [1.0], 'GSM3091791': [1.0], 'GSM3091792': [1.0], 'GSM3091793': [1.0], 'GSM3091794': [1.0], 'GSM3091795': [1.0]}\n",
      "Clinical data saved to ../../output/preprocess/Lupus_(Systemic_Lupus_Erythematosus)/clinical_data/GSE112943.csv\n"
     ]
    }
   ],
   "source": [
    "# 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 Data Availability\n",
    "# Looking at the sample characteristics dictionary, row 0 contains tissue information\n",
    "# This can be used to determine lupus status (trait)\n",
    "trait_row = 0\n",
    "# Age and gender information are not available in the sample characteristics\n",
    "age_row = None\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "def convert_trait(value_str):\n",
    "    \"\"\"Convert tissue information to binary trait (Lupus vs Control)\"\"\"\n",
    "    if not isinstance(value_str, str):\n",
    "        return None\n",
    "    \n",
    "    if ':' in value_str:\n",
    "        value = value_str.split(':', 1)[1].strip()\n",
    "    else:\n",
    "        value = value_str.strip()\n",
    "    \n",
    "    # CCLE = Chronic Cutaneous Lupus Erythematosus\n",
    "    # SCLE = Subacute Cutaneous Lupus Erythematosus\n",
    "    # Lupus Nephritis is also a form of lupus\n",
    "    if 'CCLE' in value or 'SCLE' in value or 'Lupus Nephritis' in value:\n",
    "        return 1  # Lupus\n",
    "    elif 'Control' in value:\n",
    "        return 0  # Control\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value_str):\n",
    "    \"\"\"Convert age string to numeric value (not used in this dataset)\"\"\"\n",
    "    return None  # Age data not available\n",
    "\n",
    "def convert_gender(value_str):\n",
    "    \"\"\"Convert gender string to binary (not used in this dataset)\"\"\"\n",
    "    return None  # Gender data not available\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Check if trait data is available (trait_row is not None)\n",
    "is_trait_available = trait_row is not None\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. Clinical Feature Extraction\n",
    "if trait_row is not None:\n",
    "    # Use the function to extract clinical features\n",
    "    try:\n",
    "        # Assuming clinical_data is already available from previous step\n",
    "        # If clinical_data is not available or loaded, we need to handle it\n",
    "        if 'clinical_data' in locals() or 'clinical_data' in globals():\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 Data Preview:\")\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 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",
    "        else:\n",
    "            print(\"Clinical data not available from previous step\")\n",
    "    except Exception as e:\n",
    "        print(f\"Error in clinical feature extraction: {e}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8858dc02",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "bb71d593",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:54:33.999070Z",
     "iopub.status.busy": "2025-03-25T07:54:33.998958Z",
     "iopub.status.idle": "2025-03-25T07:54:34.266577Z",
     "shell.execute_reply": "2025-03-25T07:54:34.266187Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\n",
      "No subseries references found in the first 1000 lines of the SOFT file.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene data extraction result:\n",
      "Number of rows: 47303\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. First get the path to the soft and matrix files\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. Looking more carefully at the background information\n",
    "# This is a SuperSeries which doesn't contain direct gene expression data\n",
    "# Need to investigate the soft file to find the subseries\n",
    "print(\"This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\")\n",
    "\n",
    "# Open the SOFT file to try to identify subseries\n",
    "with gzip.open(soft_file, 'rt') as f:\n",
    "    subseries_lines = []\n",
    "    for i, line in enumerate(f):\n",
    "        if 'Series_relation' in line and 'SuperSeries of' in line:\n",
    "            subseries_lines.append(line.strip())\n",
    "        if i > 1000:  # Limit search to first 1000 lines\n",
    "            break\n",
    "\n",
    "# Display the subseries found\n",
    "if subseries_lines:\n",
    "    print(\"Found potential subseries references:\")\n",
    "    for line in subseries_lines:\n",
    "        print(line)\n",
    "else:\n",
    "    print(\"No subseries references found in the first 1000 lines of the SOFT file.\")\n",
    "\n",
    "# Despite trying to extract gene data, we expect it might fail because this is a SuperSeries\n",
    "try:\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    print(\"\\nGene data extraction result:\")\n",
    "    print(\"Number of rows:\", len(gene_data))\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",
    "    print(\"This confirms the dataset is a SuperSeries without direct gene expression data.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cdda2f72",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c0f4621f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:54:34.267923Z",
     "iopub.status.busy": "2025-03-25T07:54:34.267803Z",
     "iopub.status.idle": "2025-03-25T07:54:34.269759Z",
     "shell.execute_reply": "2025-03-25T07:54:34.269472Z"
    }
   },
   "outputs": [],
   "source": [
    "# Review of gene identifiers in the gene expression data\n",
    "# The identifiers start with \"ILMN_\" which indicates they're Illumina BeadChip probe IDs\n",
    "# These are microarray probe identifiers, not human gene symbols\n",
    "# They need to be mapped to official gene symbols for better interpretability and cross-platform analysis\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "004eaed5",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "9d0d2afd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:54:34.270881Z",
     "iopub.status.busy": "2025-03-25T07:54:34.270769Z",
     "iopub.status.idle": "2025-03-25T07:54:40.022748Z",
     "shell.execute_reply": "2025-03-25T07:54:40.022343Z"
    }
   },
   "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": "bfd5e378",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "62e857df",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:54:40.024062Z",
     "iopub.status.busy": "2025-03-25T07:54:40.023924Z",
     "iopub.status.idle": "2025-03-25T07:54:40.918389Z",
     "shell.execute_reply": "2025-03-25T07:54:40.917985Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping preview:\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": [
      "\n",
      "Gene-level expression data preview:\n",
      "Shape: (20254, 47)\n",
      "Number of genes: 20254\n",
      "First few gene symbols: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS']\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data saved to ../../output/preprocess/Lupus_(Systemic_Lupus_Erythematosus)/gene_data/GSE112943.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. After observing the gene annotation data and gene expression data:\n",
    "# - The gene identifiers in gene expression data start with \"ILMN_\"\n",
    "# - In the annotation data, these are stored in the 'ID' column\n",
    "# - The gene symbols are stored in the 'Symbol' column\n",
    "\n",
    "# 2. Create a gene mapping dataframe with the probe ID and gene symbol columns\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n",
    "\n",
    "# Let's examine the mapping dataframe\n",
    "print(\"Gene mapping preview:\")\n",
    "print(preview_df(gene_mapping))\n",
    "\n",
    "# 3. Apply the gene mapping to convert probe-level measurements to gene-level expression\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "\n",
    "# Normalize gene symbols (handle synonyms)\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "\n",
    "# Preview the converted gene expression data\n",
    "print(\"\\nGene-level expression data preview:\")\n",
    "print(f\"Shape: {gene_data.shape}\")\n",
    "print(f\"Number of genes: {len(gene_data)}\")\n",
    "print(f\"First few gene symbols: {list(gene_data.index[:10])}\")\n",
    "\n",
    "# Save the gene data to the specified output 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 data saved to {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9b9cee93",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "65aadb77",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:54:40.919810Z",
     "iopub.status.busy": "2025-03-25T07:54:40.919681Z",
     "iopub.status.idle": "2025-03-25T07:54:51.591760Z",
     "shell.execute_reply": "2025-03-25T07:54:51.591333Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Top 10 gene indices before normalization: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS']\n",
      "Top 10 gene indices after normalization: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS']\n",
      "Shape of normalized gene data: (20254, 47)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Saved normalized gene data to ../../output/preprocess/Lupus_(Systemic_Lupus_Erythematosus)/gene_data/GSE112943.csv\n",
      "Loaded clinical data with shape: (1, 47)\n",
      "Shape of linked data: (47, 20255)\n",
      "Column names in linked data: [0, 'A1BG', 'A1BG-AS1', 'A1CF', 'A2M']\n",
      "Using '0' as the trait column for handling missing values\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Shape of linked data after handling missing values: (47, 20255)\n",
      "For the feature '0', the least common label is '0.0' with 17 occurrences. This represents 36.17% of the dataset.\n",
      "The distribution of the feature '0' in this dataset is fine.\n",
      "\n",
      "A new JSON file was created at: ../../output/preprocess/Lupus_(Systemic_Lupus_Erythematosus)/cohort_info.json\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Saved processed linked data to ../../output/preprocess/Lupus_(Systemic_Lupus_Erythematosus)/GSE112943.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "print(f\"Top 10 gene indices before normalization: {gene_data.index[:10].tolist()}\")\n",
    "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Top 10 gene indices after normalization: {normalized_gene_data.index[:10].tolist()}\")\n",
    "print(f\"Shape of normalized gene data: {normalized_gene_data.shape}\")\n",
    "\n",
    "# Create directory for gene data file if it doesn't exist\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "# Save the normalized gene data\n",
    "normalized_gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Saved normalized gene data to {out_gene_data_file}\")\n",
    "\n",
    "# 2. Load the clinical data \n",
    "# Load the clinical data that was already processed in step 2\n",
    "selected_clinical_df = pd.read_csv(out_clinical_data_file)\n",
    "print(f\"Loaded clinical data with shape: {selected_clinical_df.shape}\")\n",
    "\n",
    "# 3. Link clinical and genetic data\n",
    "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n",
    "print(f\"Shape of linked data: {linked_data.shape}\")\n",
    "\n",
    "# Inspect the column names to find the trait column name\n",
    "print(f\"Column names in linked data: {linked_data.columns[:5].tolist()}\")\n",
    "\n",
    "# 4. Handle missing values in the linked data\n",
    "# Since we're dealing with a trait that was saved from a previous step,\n",
    "# we need to find the actual column name used for the trait in the linked data\n",
    "# The first column (index 0) of clinical data should be our trait\n",
    "trait_col = linked_data.columns[0]\n",
    "print(f\"Using '{trait_col}' as the trait column for handling missing values\")\n",
    "linked_data = handle_missing_values(linked_data, trait_col)\n",
    "print(f\"Shape of linked data after handling missing values: {linked_data.shape}\")\n",
    "\n",
    "# 5. Determine if the trait and demographic features are biased\n",
    "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait_col)\n",
    "\n",
    "# 6. Validate the dataset and save 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 data from skin and kidney samples of lupus patients and controls.\"\n",
    ")\n",
    "\n",
    "# 7. Save the linked data if it's usable\n",
    "if is_usable:\n",
    "    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "    unbiased_linked_data.to_csv(out_data_file)\n",
    "    print(f\"Saved processed linked data to {out_data_file}\")\n",
    "else:\n",
    "    print(\"Dataset validation failed. Final 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
}