File size: 25,351 Bytes
e4183cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "f686e699",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:35.078946Z",
     "iopub.status.busy": "2025-03-25T08:31:35.078626Z",
     "iopub.status.idle": "2025-03-25T08:31:35.242332Z",
     "shell.execute_reply": "2025-03-25T08:31:35.242015Z"
    }
   },
   "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 = \"COVID-19\"\n",
    "cohort = \"GSE275334\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/COVID-19\"\n",
    "in_cohort_dir = \"../../input/GEO/COVID-19/GSE275334\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/COVID-19/GSE275334.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/COVID-19/gene_data/GSE275334.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/COVID-19/clinical_data/GSE275334.csv\"\n",
    "json_path = \"../../output/preprocess/COVID-19/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0ddfeb03",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "95216831",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:35.243705Z",
     "iopub.status.busy": "2025-03-25T08:31:35.243565Z",
     "iopub.status.idle": "2025-03-25T08:31:35.258937Z",
     "shell.execute_reply": "2025-03-25T08:31:35.258680Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Immune Exhaustion in ME/CFS and long COVID\"\n",
      "!Series_summary\t\"Gene expression analysis of RNA was performed using the commercially available NanoString® nCounter Immune Exhaustion gene expression panel (NanoString Technologies, Seattle, WA, USA). This panel contains 785 genes to elucidate mechanisms behind T cell, B cell and NK cell exhaustion in disease.\"\n",
      "!Series_summary\t\"Ribonucleic acid (RNA) was extracted from peripheral blood mononuclear cells (PBMCs) isolated from ME/CFS (n=14), long COVID (n=15), and healthy control (HC; n=18) participants. ME/CFS participants were included according to Canadian Consensus Criteria for ME. Long COVID participants were eligible according to the working case definition for Post COVID-19 Condition published by the World Health Organization.\"\n",
      "!Series_overall_design\t\"Raw gene expression data was normalised against positive and negative controls to account for background noise and platform-associated variation. Normalisation and analysis were performed using Rosalind Bio (San Diego, CA, USA) using geometric means of housekeeping genes (ABCF1, ALAS1, EEF1G, G6PD, GAPDH, GUSB, HPRT1, OAZ1, POLR1B, POLR2A, PPIA, RPL19, SDHA, TBP, TUBB) (Supplementary Material 1). Differential expression is reported between ME/CFS and long COVID with HC.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['cell type: PBMCs'], 1: ['age (years): 24', 'age (years): 46', 'age (years): 50', 'age (years): 37', 'age (years): 19', 'age (years): 40', 'age (years): 63', 'age (years): 54', 'age (years): 48', 'age (years): 34', 'age (years): 22', 'age (years): 59', 'age (years): 39', 'age (years): 27', 'age (years): 61', 'age (years): 38', 'age (years): 44', 'age (years): 41', 'age (years): 49', 'age (years): 43', 'age (years): 62', 'age (years): 30', 'age (years): 47', 'age (years): 53', 'age (years): 29', 'age (years): 32', 'age (years): 55', 'age (years): 51', 'age (years): 31', 'age (years): 60'], 2: ['Sex: Female', 'Sex: Male'], 3: ['disease: Healthy control', 'disease: Long COVID', 'disease: ME/CFS']}\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": "a0d7d779",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "b87dc85e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:35.259876Z",
     "iopub.status.busy": "2025-03-25T08:31:35.259774Z",
     "iopub.status.idle": "2025-03-25T08:31:35.270366Z",
     "shell.execute_reply": "2025-03-25T08:31:35.270097Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical Data Preview:\n",
      "{'GSM8475033': [0.0, 24.0, 0.0], 'GSM8475034': [0.0, 46.0, 0.0], 'GSM8475035': [0.0, 50.0, 0.0], 'GSM8475036': [0.0, 37.0, 1.0], 'GSM8475037': [0.0, 19.0, 0.0], 'GSM8475038': [0.0, 40.0, 0.0], 'GSM8475039': [0.0, 46.0, 1.0], 'GSM8475040': [0.0, 63.0, 0.0], 'GSM8475041': [0.0, 54.0, 0.0], 'GSM8475042': [0.0, 46.0, 0.0], 'GSM8475043': [0.0, 48.0, 0.0], 'GSM8475044': [0.0, 34.0, 1.0], 'GSM8475045': [0.0, 22.0, 1.0], 'GSM8475046': [0.0, 59.0, 0.0], 'GSM8475047': [0.0, 39.0, 0.0], 'GSM8475048': [0.0, 27.0, 0.0], 'GSM8475049': [0.0, 61.0, 0.0], 'GSM8475050': [0.0, 38.0, 1.0], 'GSM8475051': [1.0, 44.0, 0.0], 'GSM8475052': [1.0, 41.0, 1.0], 'GSM8475053': [1.0, 49.0, 0.0], 'GSM8475054': [1.0, 19.0, 0.0], 'GSM8475055': [1.0, 38.0, 0.0], 'GSM8475056': [1.0, 43.0, 0.0], 'GSM8475057': [1.0, 62.0, 0.0], 'GSM8475058': [1.0, 30.0, 0.0], 'GSM8475059': [1.0, 59.0, 0.0], 'GSM8475060': [1.0, 40.0, 1.0], 'GSM8475061': [1.0, 61.0, 1.0], 'GSM8475062': [1.0, 47.0, 0.0], 'GSM8475063': [1.0, 59.0, 1.0], 'GSM8475064': [1.0, 37.0, 0.0], 'GSM8475065': [1.0, 53.0, 0.0], 'GSM8475066': [0.0, 30.0, 0.0], 'GSM8475067': [0.0, 29.0, 0.0], 'GSM8475068': [0.0, 48.0, 0.0], 'GSM8475069': [0.0, 32.0, 0.0], 'GSM8475070': [0.0, 55.0, 0.0], 'GSM8475071': [0.0, 51.0, 1.0], 'GSM8475072': [0.0, 48.0, 0.0], 'GSM8475073': [0.0, 31.0, 0.0], 'GSM8475074': [0.0, 60.0, 0.0], 'GSM8475075': [0.0, 24.0, 0.0], 'GSM8475076': [0.0, 47.0, 0.0], 'GSM8475077': [0.0, 20.0, 0.0], 'GSM8475078': [0.0, 42.0, 1.0], 'GSM8475079': [0.0, 41.0, 1.0]}\n",
      "Clinical data saved to ../../output/preprocess/COVID-19/clinical_data/GSE275334.csv\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\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 appears to contain gene expression data\n",
    "# from NanoString nCounter Immune Exhaustion gene expression panel, which includes 785 genes.\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# From the sample characteristics dictionary:\n",
    "# - trait (COVID-19) can be inferred from \"disease\" in row 3\n",
    "# - age is available in row 1\n",
    "# - gender/sex is available in row 2\n",
    "trait_row = 3\n",
    "age_row = 1\n",
    "gender_row = 2\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "def convert_trait(value: str) -> int:\n",
    "    \"\"\"\n",
    "    Convert trait values to binary (0 or 1).\n",
    "    For this dataset, we're looking for COVID-19 which maps to \"Long COVID\".\n",
    "    \"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after colon if present\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary based on whether it's \"Long COVID\" or not\n",
    "    if \"long covid\" in value.lower():\n",
    "        return 1\n",
    "    else:\n",
    "        return 0\n",
    "\n",
    "def convert_age(value: str) -> float:\n",
    "    \"\"\"\n",
    "    Convert age values to continuous (float).\n",
    "    \"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after colon if present\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    try:\n",
    "        return float(value)\n",
    "    except (ValueError, TypeError):\n",
    "        return None\n",
    "\n",
    "def convert_gender(value: str) -> int:\n",
    "    \"\"\"\n",
    "    Convert gender values to binary (0 for female, 1 for male).\n",
    "    \"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after colon if present\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    if value.lower() == \"female\":\n",
    "        return 0\n",
    "    elif value.lower() == \"male\":\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait data availability\n",
    "is_trait_available = trait_row is not None\n",
    "# Initial filtering on usability\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",
    "    # Using the clinical_data variable that should be available from previous steps\n",
    "    try:\n",
    "        # Extract clinical features using the pre-existing clinical_data DataFrame\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 dataframe\n",
    "        preview = preview_df(selected_clinical_df)\n",
    "        print(\"Clinical Data Preview:\")\n",
    "        print(preview)\n",
    "        \n",
    "        # Save to CSV\n",
    "        os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "        selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
    "        print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "    except Exception as e:\n",
    "        print(f\"Error extracting clinical features: {e}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ca6318a9",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "323f70ed",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:35.271233Z",
     "iopub.status.busy": "2025-03-25T08:31:35.271132Z",
     "iopub.status.idle": "2025-03-25T08:31:35.284994Z",
     "shell.execute_reply": "2025-03-25T08:31:35.284735Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SOFT file: ../../input/GEO/COVID-19/GSE275334/GSE275334_family.soft.gz\n",
      "Matrix file: ../../input/GEO/COVID-19/GSE275334/GSE275334_series_matrix.txt.gz\n",
      "Found the matrix table marker at line 65\n",
      "Gene data shape: (635, 47)\n",
      "First 20 gene/probe identifiers:\n",
      "['ACACA', 'ACADVL', 'ACAT2', 'ACOT1/2', 'ACSL3', 'ACSL4', 'ACSL6', 'ADORA2A', 'ADORA2B', 'AHR', 'AIFM1', 'AK4', 'AKT1', 'AKT2', 'AKT3', 'ALDH1A1', 'ALDH1B1', 'ALDOA', 'ALOX5', 'ANAPC4']\n"
     ]
    }
   ],
   "source": [
    "# 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",
    "print(f\"SOFT file: {soft_file}\")\n",
    "print(f\"Matrix file: {matrix_file}\")\n",
    "\n",
    "# Set gene availability flag\n",
    "is_gene_available = True  # Initially assume gene data is available\n",
    "\n",
    "# First check if the matrix file contains the expected marker\n",
    "found_marker = False\n",
    "marker_row = None\n",
    "try:\n",
    "    with gzip.open(matrix_file, 'rt') as file:\n",
    "        for i, line in enumerate(file):\n",
    "            if \"!series_matrix_table_begin\" in line:\n",
    "                found_marker = True\n",
    "                marker_row = i\n",
    "                print(f\"Found the matrix table marker at line {i}\")\n",
    "                break\n",
    "    \n",
    "    if not found_marker:\n",
    "        print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
    "        is_gene_available = False\n",
    "        \n",
    "    # If marker was found, try to extract gene data\n",
    "    if is_gene_available:\n",
    "        try:\n",
    "            # Try using the library function\n",
    "            gene_data = get_genetic_data(matrix_file)\n",
    "            \n",
    "            if gene_data.shape[0] == 0:\n",
    "                print(\"Warning: Extracted gene data has 0 rows.\")\n",
    "                is_gene_available = False\n",
    "            else:\n",
    "                print(f\"Gene data shape: {gene_data.shape}\")\n",
    "                # Print the first 20 gene/probe identifiers\n",
    "                print(\"First 20 gene/probe identifiers:\")\n",
    "                print(gene_data.index[:20].tolist())\n",
    "        except Exception as e:\n",
    "            print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
    "            is_gene_available = False\n",
    "    \n",
    "    # If gene data extraction failed, examine file content to diagnose\n",
    "    if not is_gene_available:\n",
    "        print(\"Examining file content to diagnose the issue:\")\n",
    "        try:\n",
    "            with gzip.open(matrix_file, 'rt') as file:\n",
    "                # Print lines around the marker if found\n",
    "                if marker_row is not None:\n",
    "                    for i, line in enumerate(file):\n",
    "                        if i >= marker_row - 2 and i <= marker_row + 10:\n",
    "                            print(f\"Line {i}: {line.strip()[:100]}...\")\n",
    "                        if i > marker_row + 10:\n",
    "                            break\n",
    "                else:\n",
    "                    # If marker not found, print first 10 lines\n",
    "                    for i, line in enumerate(file):\n",
    "                        if i < 10:\n",
    "                            print(f\"Line {i}: {line.strip()[:100]}...\")\n",
    "                        else:\n",
    "                            break\n",
    "        except Exception as e2:\n",
    "            print(f\"Error examining file: {e2}\")\n",
    "        \n",
    "except Exception as e:\n",
    "    print(f\"Error processing file: {e}\")\n",
    "    is_gene_available = False\n",
    "\n",
    "# Update validation information if gene data extraction failed\n",
    "if not is_gene_available:\n",
    "    print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
    "    # Update the validation record since gene data isn't available\n",
    "    is_trait_available = False  # We already determined trait data isn't available in step 2\n",
    "    validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
    "                                 is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "95b737f2",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "41a6d09a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:35.285932Z",
     "iopub.status.busy": "2025-03-25T08:31:35.285831Z",
     "iopub.status.idle": "2025-03-25T08:31:35.287480Z",
     "shell.execute_reply": "2025-03-25T08:31:35.287221Z"
    }
   },
   "outputs": [],
   "source": [
    "# Based on the first 20 identifiers shown, these appear to be human gene symbols.\n",
    "# The identifiers are in the format of human gene symbols like ACACA, ACADVL, etc.\n",
    "# There is a mix of standard gene symbols and some combined identifiers (e.g., ACOT1/2)\n",
    "# but overall these are human gene symbols and don't require mapping.\n",
    "\n",
    "requires_gene_mapping = False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c481bb08",
   "metadata": {},
   "source": [
    "### Step 5: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "a7672867",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:35.288428Z",
     "iopub.status.busy": "2025-03-25T08:31:35.288330Z",
     "iopub.status.idle": "2025-03-25T08:31:35.430080Z",
     "shell.execute_reply": "2025-03-25T08:31:35.429743Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data saved to ../../output/preprocess/COVID-19/gene_data/GSE275334.csv\n",
      "Loaded clinical data shape: (3, 47)\n",
      "Clinical features columns after transformation: ['COVID-19', 'Age', 'Gender']\n",
      "Initial linked data shape: (47, 638)\n",
      "Linked data shape after handling missing values: (46, 638)\n",
      "For the feature 'COVID-19', the least common label is '1.0' with 15 occurrences. This represents 32.61% of the dataset.\n",
      "The distribution of the feature 'COVID-19' in this dataset is fine.\n",
      "\n",
      "Quartiles for 'Age':\n",
      "  25%: 34.75\n",
      "  50% (Median): 43.5\n",
      "  75%: 50.75\n",
      "Min: 19.0\n",
      "Max: 63.0\n",
      "The distribution of the feature 'Age' in this dataset is fine.\n",
      "\n",
      "For the feature 'Gender', the least common label is '1.0' with 12 occurrences. This represents 26.09% of the dataset.\n",
      "The distribution of the feature 'Gender' in this dataset is fine.\n",
      "\n",
      "Linked data saved to ../../output/preprocess/COVID-19/GSE275334.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols and prepare for linking\n",
    "try:\n",
    "    # Create output directory if it doesn't exist\n",
    "    os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "    \n",
    "    # Save the gene data\n",
    "    gene_data.to_csv(out_gene_data_file)\n",
    "    print(f\"Gene data saved to {out_gene_data_file}\")\n",
    "    \n",
    "    # Attempt to link clinical and gene data\n",
    "    if 'trait_row' in locals() and trait_row is not None:\n",
    "        # Load clinical data from the previous step\n",
    "        try:\n",
    "            clinical_features = pd.read_csv(out_clinical_data_file)\n",
    "            print(f\"Loaded clinical data shape: {clinical_features.shape}\")\n",
    "            \n",
    "            # Convert clinical_features to the correct format for linking\n",
    "            clinical_features.set_index(clinical_features.columns[0], inplace=True)\n",
    "            clinical_features = clinical_features.T\n",
    "            clinical_features.columns = [trait, 'Age', 'Gender']\n",
    "            \n",
    "            print(\"Clinical features columns after transformation:\", clinical_features.columns.tolist())\n",
    "            \n",
    "            # Link the clinical and genetic data\n",
    "            linked_data = pd.concat([clinical_features, gene_data.T], axis=1)\n",
    "            print(f\"Initial linked data shape: {linked_data.shape}\")\n",
    "            \n",
    "            # Handle missing values\n",
    "            linked_data = handle_missing_values(linked_data, trait)\n",
    "            print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
    "            \n",
    "            if linked_data.shape[0] > 0:\n",
    "                # Check for bias in trait and demographic features\n",
    "                is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "                \n",
    "                # Validate data quality 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=is_gene_available,\n",
    "                    is_trait_available=True,\n",
    "                    is_biased=is_biased,\n",
    "                    df=linked_data,\n",
    "                    note=\"Successfully processed gene expression data for COVID-19.\"\n",
    "                )\n",
    "                \n",
    "                # 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",
    "                    linked_data.to_csv(out_data_file)\n",
    "                    print(f\"Linked data saved to {out_data_file}\")\n",
    "                else:\n",
    "                    print(\"Data not usable for trait study - not saving final linked data.\")\n",
    "            else:\n",
    "                print(\"After handling missing values, no samples remain.\")\n",
    "                validate_and_save_cohort_info(\n",
    "                    is_final=True,\n",
    "                    cohort=cohort,\n",
    "                    info_path=json_path,\n",
    "                    is_gene_available=is_gene_available,\n",
    "                    is_trait_available=True,\n",
    "                    is_biased=True,\n",
    "                    df=pd.DataFrame(),\n",
    "                    note=\"No valid samples after handling missing values.\"\n",
    "                )\n",
    "        except Exception as e:\n",
    "            print(f\"Error loading or processing clinical data: {e}\")\n",
    "            # Try to create a minimal response in case of error\n",
    "            validate_and_save_cohort_info(\n",
    "                is_final=True,\n",
    "                cohort=cohort,\n",
    "                info_path=json_path,\n",
    "                is_gene_available=is_gene_available,\n",
    "                is_trait_available=False,\n",
    "                is_biased=True,\n",
    "                df=pd.DataFrame(),\n",
    "                note=f\"Error processing clinical data: {str(e)}\"\n",
    "            )\n",
    "    else:\n",
    "        # Cannot proceed with linking if trait data is missing\n",
    "        validate_and_save_cohort_info(\n",
    "            is_final=True,\n",
    "            cohort=cohort,\n",
    "            info_path=json_path,\n",
    "            is_gene_available=is_gene_available,\n",
    "            is_trait_available=False,\n",
    "            is_biased=True,\n",
    "            df=pd.DataFrame(),\n",
    "            note=\"Cannot link data because trait information is not available.\"\n",
    "        )\n",
    "except Exception as e:\n",
    "    print(f\"Error in data processing: {e}\")\n",
    "    \n",
    "    # Log the error and mark the dataset as unusable\n",
    "    validate_and_save_cohort_info(\n",
    "        is_final=True,\n",
    "        cohort=cohort,\n",
    "        info_path=json_path,\n",
    "        is_gene_available=False,\n",
    "        is_trait_available=False,\n",
    "        is_biased=True,\n",
    "        df=pd.DataFrame(),\n",
    "        note=f\"Error during normalization or linking: {str(e)}\"\n",
    "    )"
   ]
  }
 ],
 "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
}