File size: 21,410 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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "73691dc0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:31.346254Z",
     "iopub.status.busy": "2025-03-25T08:31:31.346017Z",
     "iopub.status.idle": "2025-03-25T08:31:31.516536Z",
     "shell.execute_reply": "2025-03-25T08:31:31.516141Z"
    }
   },
   "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 = \"GSE227080\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/COVID-19\"\n",
    "in_cohort_dir = \"../../input/GEO/COVID-19/GSE227080\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/COVID-19/GSE227080.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/COVID-19/gene_data/GSE227080.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/COVID-19/clinical_data/GSE227080.csv\"\n",
    "json_path = \"../../output/preprocess/COVID-19/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1e1ef1bf",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "f223171d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:31.518009Z",
     "iopub.status.busy": "2025-03-25T08:31:31.517847Z",
     "iopub.status.idle": "2025-03-25T08:31:31.544659Z",
     "shell.execute_reply": "2025-03-25T08:31:31.544327Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Early differentially expressed immunological genes   in mild and severe COVID-19\"\n",
      "!Series_summary\t\"We retrospectively analysed the expression of 579 immunological genes in 60 COVID-19 subjects (SARS +ve) and 59 COVID-negative (SARS -ve) subjects using the NanoString nCounter (Immunology panel), a technology based on multiplexed single-molecule counting. Biobanked Human peripheral blood mononuclear cells (PBMCs) samples underwent Nucleic Acid extraction and digital detection of mRNA to evaluate changes in antiviral gene expression between SARS -ve controls and patients with mild (SARS +ve Mild) and moderate/severe (SARS +ve Mod/Sev) disease.\"\n",
      "!Series_overall_design\t\"119 samples (60 SARS-CoV-2 positive / 59 SARS-CoV-2 negative)\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['gender: F', 'gender: M'], 1: ['age: 38', 'age: 66', 'age: 21', 'age: 29', 'age: 73', 'age: 35', 'age: 48', 'age: 70', 'age: 69', 'age: 31', 'age: 72', 'age: 41', 'age: 85', 'age: 79', 'age: 46', 'age: 57', 'age: 87', 'age: 52', 'age: 36', 'age: 77', 'age: 82', 'age: 89', 'age: 94', 'age: 54', 'age: 23', 'age: 61', 'age: 75', 'age: 25', 'age: 43', 'age: 24'], 2: ['severity: MILD', 'severity: MOD_SEV', 'severity: NEG']}\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": "79392c3f",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "800842fc",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:31.545953Z",
     "iopub.status.busy": "2025-03-25T08:31:31.545836Z",
     "iopub.status.idle": "2025-03-25T08:31:31.551564Z",
     "shell.execute_reply": "2025-03-25T08:31:31.551236Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Processing clinical data with sample characteristics\n",
      "Trait row: 2, Age row: 1, Gender row: 0\n",
      "Clinical data is available for processing. Trait data (2): ['severity: MILD', 'severity: MOD_SEV', 'severity: NEG']\n",
      "Age data (1): ['age: 38', 'age: 66', 'age: 21', 'age: 29', 'age: 73']...\n",
      "Gender data (0): ['gender: F', 'gender: M']\n",
      "Clinical feature extraction will be completed when the full dataset is available.\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import os\n",
    "import json\n",
    "from typing import Optional, Callable, Dict, Any, List\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information, this dataset contains expression data of 579 immunological genes\n",
    "# This is gene expression data, not miRNA or methylation data\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "trait_row = 2  # \"severity\" indicates COVID-19 severity status\n",
    "age_row = 1    # Age information is available\n",
    "gender_row = 0  # Gender information is available\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "def convert_trait(value: str) -> int:\n",
    "    \"\"\"Convert COVID-19 severity trait to binary (0 for negative/mild, 1 for moderate/severe)\"\"\"\n",
    "    if not value or ':' not in value:\n",
    "        return None\n",
    "    severity = value.split(':', 1)[1].strip().upper()\n",
    "    if severity == 'NEG':  # COVID-negative\n",
    "        return 0\n",
    "    elif severity == 'MILD':  # Mild COVID\n",
    "        return 0\n",
    "    elif severity == 'MOD_SEV':  # Moderate/Severe COVID\n",
    "        return 1\n",
    "    return None\n",
    "\n",
    "def convert_age(value: str) -> float:\n",
    "    \"\"\"Convert age string to float\"\"\"\n",
    "    if not value or ':' not in value:\n",
    "        return None\n",
    "    age_str = value.split(':', 1)[1].strip()\n",
    "    try:\n",
    "        return float(age_str)\n",
    "    except ValueError:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value: str) -> int:\n",
    "    \"\"\"Convert gender string to binary (0 for female, 1 for male)\"\"\"\n",
    "    if not value or ':' not in value:\n",
    "        return None\n",
    "    gender = value.split(':', 1)[1].strip().upper()\n",
    "    if gender == 'F':\n",
    "        return 0\n",
    "    elif gender == 'M':\n",
    "        return 1\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait data availability\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Initial filtering and saving metadata\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",
    "# Since trait_row is not None, we need to extract clinical features\n",
    "if trait_row is not None:\n",
    "    # Create a DataFrame from the sample characteristics dictionary\n",
    "    # This simulates clinical data based on the provided sample characteristics\n",
    "    sample_characteristics = {\n",
    "        0: ['gender: F', 'gender: M'], \n",
    "        1: ['age: 38', 'age: 66', 'age: 21', 'age: 29', 'age: 73', 'age: 35', 'age: 48', 'age: 70', 'age: 69', 'age: 31', 'age: 72', 'age: 41', 'age: 85', 'age: 79', 'age: 46', 'age: 57', 'age: 87', 'age: 52', 'age: 36', 'age: 77', 'age: 82', 'age: 89', 'age: 94', 'age: 54', 'age: 23', 'age: 61', 'age: 75', 'age: 25', 'age: 43', 'age: 24'], \n",
    "        2: ['severity: MILD', 'severity: MOD_SEV', 'severity: NEG']\n",
    "    }\n",
    "    \n",
    "    # We don't have the actual samples yet, so we'll create placeholder sample IDs\n",
    "    # The actual clinical_data processing will happen later when we have the full data\n",
    "    print(\"Processing clinical data with sample characteristics\")\n",
    "    print(f\"Trait row: {trait_row}, Age row: {age_row}, Gender row: {gender_row}\")\n",
    "    \n",
    "    # Since we're just doing initial validation at this point, we'll note that clinical data\n",
    "    # is available but requires further processing in subsequent steps\n",
    "    print(f\"Clinical data is available for processing. Trait data ({trait_row}): {sample_characteristics[trait_row]}\")\n",
    "    print(f\"Age data ({age_row}): {sample_characteristics[age_row][:5]}...\")\n",
    "    print(f\"Gender data ({gender_row}): {sample_characteristics[gender_row]}\")\n",
    "    \n",
    "    # Note: We need the actual GEO data matrix with sample IDs to properly extract clinical features\n",
    "    # This will be done in a later step when we have access to the complete dataset\n",
    "    print(\"Clinical feature extraction will be completed when the full dataset is available.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dbfaa3fa",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "4c05bce2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:31.552806Z",
     "iopub.status.busy": "2025-03-25T08:31:31.552693Z",
     "iopub.status.idle": "2025-03-25T08:31:31.572345Z",
     "shell.execute_reply": "2025-03-25T08:31:31.572010Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SOFT file: ../../input/GEO/COVID-19/GSE227080/GSE227080_family.soft.gz\n",
      "Matrix file: ../../input/GEO/COVID-19/GSE227080/GSE227080_series_matrix.txt.gz\n",
      "Found the matrix table marker at line 63\n",
      "Gene data shape: (579, 119)\n",
      "First 20 gene/probe identifiers:\n",
      "['ABCB1', 'ABL1', 'ADA', 'AHR', 'AICDA', 'AIRE', 'APP', 'ARG1', 'ARG2', 'ARHGDIB', 'ATG10', 'ATG12', 'ATG16L1', 'ATG5', 'ATG7', 'ATM', 'B2M', 'B3GAT1', 'BATF', 'BATF3']\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": "dcc914f9",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "0ca9df9e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:31.573521Z",
     "iopub.status.busy": "2025-03-25T08:31:31.573407Z",
     "iopub.status.idle": "2025-03-25T08:31:31.575226Z",
     "shell.execute_reply": "2025-03-25T08:31:31.574906Z"
    }
   },
   "outputs": [],
   "source": [
    "# The gene identifiers appear to be standard human gene symbols (like ABCB1, ABL1, ADA, etc.)\n",
    "# These are official gene symbols that don't require mapping to other identifiers\n",
    "\n",
    "requires_gene_mapping = False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "22fede8b",
   "metadata": {},
   "source": [
    "### Step 5: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "21361c86",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:31:31.576404Z",
     "iopub.status.busy": "2025-03-25T08:31:31.576291Z",
     "iopub.status.idle": "2025-03-25T08:31:31.839969Z",
     "shell.execute_reply": "2025-03-25T08:31:31.839607Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape after normalization: (561, 119)\n",
      "Normalized gene data saved to ../../output/preprocess/COVID-19/gene_data/GSE227080.csv\n",
      "Clinical features saved to ../../output/preprocess/COVID-19/clinical_data/GSE227080.csv\n",
      "Clinical features preview:\n",
      "{'COVID-19': [0.0, 1.0, 1.0, 0.0, 1.0], 'Age': [38.0, 66.0, 21.0, 29.0, 73.0], 'Gender': [0.0, 1.0, 1.0, 1.0, 1.0]}\n",
      "Linked data shape: (119, 564)\n",
      "Linked data shape after handling missing values: (119, 564)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "For the feature 'COVID-19', the least common label is '1.0' with 34 occurrences. This represents 28.57% of the dataset.\n",
      "The distribution of the feature 'COVID-19' in this dataset is fine.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Quartiles for 'Age':\n",
      "  25%: 47.0\n",
      "  50% (Median): 63.0\n",
      "  75%: 75.0\n",
      "Min: 21.0\n",
      "Max: 94.0\n",
      "The distribution of the feature 'Age' in this dataset is fine.\n",
      "\n",
      "For the feature 'Gender', the least common label is '0.0' with 44 occurrences. This represents 36.97% 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/GSE227080.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the 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",
    "\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 normalized gene data\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. Extract clinical features using the previously identified feature rows\n",
    "# Use the clinical data from Step 1 and the row identifiers from Step 2\n",
    "clinical_features = geo_select_clinical_features(\n",
    "    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",
    "# Create directory for clinical data output\n",
    "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "\n",
    "# Save the clinical features\n",
    "clinical_features.to_csv(out_clinical_data_file)\n",
    "print(f\"Clinical features saved to {out_clinical_data_file}\")\n",
    "\n",
    "# Preview the clinical features\n",
    "clinical_features_preview = preview_df(clinical_features.T)\n",
    "print(\"Clinical features preview:\")\n",
    "print(clinical_features_preview)\n",
    "\n",
    "# 3. Link clinical and genetic data\n",
    "linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "\n",
    "# 4. Handle missing values in the linked data\n",
    "linked_data = handle_missing_values(linked_data, trait)\n",
    "print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
    "\n",
    "# 5. Determine if trait and demographic features are biased\n",
    "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "\n",
    "# 6. 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=is_gene_available,\n",
    "    is_trait_available=True,  # We have trait data as identified in Step 2\n",
    "    is_biased=is_biased,\n",
    "    df=linked_data,\n",
    "    note=\"Dataset contains gene expression data for COVID-19 severity analysis.\"\n",
    ")\n",
    "\n",
    "# 7. Save the linked data if it's usable\n",
    "if is_usable:\n",
    "    # Create output directory if it doesn't exist\n",
    "    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "    \n",
    "    # Save the linked data\n",
    "    linked_data.to_csv(out_data_file)\n",
    "    print(f\"Linked data saved to {out_data_file}\")\n",
    "else:\n",
    "    print(\"Linked data not saved due to quality issues.\")"
   ]
  }
 ],
 "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
}