File size: 21,027 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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cbc04477",
   "metadata": {},
   "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 = \"Atherosclerosis\"\n",
    "cohort = \"GSE123086\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Atherosclerosis\"\n",
    "in_cohort_dir = \"../../input/GEO/Atherosclerosis/GSE123086\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Atherosclerosis/GSE123086.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Atherosclerosis/gene_data/GSE123086.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Atherosclerosis/clinical_data/GSE123086.csv\"\n",
    "json_path = \"../../output/preprocess/Atherosclerosis/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3b92ac01",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0185cd70",
   "metadata": {},
   "outputs": [],
   "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": "b0622854",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2f2570cd",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Looking at the background info: mentions microarrays and RNA extraction, suggesting gene expression data is available\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "\n",
    "# Trait: For atherosclerosis, primary diagnosis is in row 1\n",
    "trait_row = 1\n",
    "\n",
    "# Age: Available in rows 3 and 4\n",
    "age_row = 3\n",
    "\n",
    "# Gender: Available in row 2 (and also some values appear in row 3)\n",
    "gender_row = 2\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait value to binary format.\"\"\"\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # For Atherosclerosis trait\n",
    "    if \"ATHEROSCLEROSIS\" in value:\n",
    "        return 1\n",
    "    else:\n",
    "        return 0\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age value to continuous format.\"\"\"\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \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):\n",
    "    \"\"\"Convert gender value to binary format (0=female, 1=male).\"\"\"\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    if value.upper() == \"MALE\":\n",
    "        return 1\n",
    "    elif value.upper() == \"FEMALE\":\n",
    "        return 0\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",
    "\n",
    "# Conduct initial filtering and save 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",
    "if trait_row is not None:\n",
    "    # Create output directories if they don't exist\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    \n",
    "    # Use the function from the library to extract clinical features\n",
    "    clinical_features_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(clinical_features_df)\n",
    "    print(\"Clinical features preview:\", preview)\n",
    "    \n",
    "    # Save the clinical data\n",
    "    clinical_features_df.to_csv(out_clinical_data_file, index=False)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "df9b35b6",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1007b293",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Get the SOFT and matrix file paths again \n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "print(f\"Matrix file found: {matrix_file}\")\n",
    "\n",
    "# 2. Use the get_genetic_data function from the library to get the gene_data\n",
    "try:\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    print(f\"Gene data shape: {gene_data.shape}\")\n",
    "    \n",
    "    # 3. Print the first 20 row IDs (gene or probe identifiers)\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"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7389b58c",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e798066f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# The identifiers shown are numeric values ('1', '2', '3', etc.)\n",
    "# These are not standard human gene symbols, which would typically be alphanumeric\n",
    "# (like \"BRCA1\", \"TP53\", \"APOE\", etc.)\n",
    "# These appear to be probe or feature IDs that need to be mapped to actual gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0713729f",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "67f9d2f4",
   "metadata": {},
   "outputs": [],
   "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. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
    "print(\"\\nGene annotation preview:\")\n",
    "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
    "print(preview_df(gene_annotation, n=5))\n",
    "\n",
    "# Check the first few rows of the SOFT file to better understand its structure\n",
    "print(\"\\nChecking the SOFT file structure for gene symbols:\")\n",
    "gene_symbol_data = []\n",
    "with gzip.open(soft_file, 'rt') as f:\n",
    "    for i, line in enumerate(f):\n",
    "        if i < 1000:  # Examine more lines to find gene symbol information\n",
    "            if \"GENE_SYMBOL\" in line or \"gene_symbol\" in line.lower() or \"symbol\" in line.lower():\n",
    "                print(line.strip())\n",
    "                gene_symbol_data.append(line.strip())\n",
    "        else:\n",
    "            break\n",
    "\n",
    "print(\"\\nSearching for gene symbols in the SOFT file...\")\n",
    "# Look for table headers that could contain gene symbol information\n",
    "with gzip.open(soft_file, 'rt') as f:\n",
    "    for i, line in enumerate(f):\n",
    "        if i < 1000 and \"!platform_table_begin\" in line:\n",
    "            # Get the next line which should contain column headers\n",
    "            header_line = next(f, \"\").strip()\n",
    "            print(f\"Found platform table headers: {header_line}\")\n",
    "            break\n",
    "\n",
    "# We need to create a more appropriate mapping\n",
    "# First, check if we can extract gene symbols from the Entrez Gene IDs\n",
    "# Use the extract_human_gene_symbols function from the library\n",
    "print(\"\\nAttempting to map Entrez Gene IDs to gene symbols...\")\n",
    "\n",
    "# Create a basic mapping dataframe with probe IDs and Entrez Gene IDs\n",
    "mapping_data = gene_annotation[['ID', 'ENTREZ_GENE_ID']].copy()\n",
    "mapping_data = mapping_data.dropna(subset=['ENTREZ_GENE_ID'])\n",
    "mapping_data = mapping_data.rename(columns={'ENTREZ_GENE_ID': 'Gene'})\n",
    "\n",
    "# Filter out any empty gene values\n",
    "mapping_data = mapping_data[mapping_data['Gene'] != '']\n",
    "\n",
    "# Validate the mapping data\n",
    "print(f\"Mapping data shape: {mapping_data.shape}\")\n",
    "print(\"Sample mapping data:\")\n",
    "print(preview_df(mapping_data, n=5))\n",
    "\n",
    "# Check if there's additional mapping information in the annotation\n",
    "print(\"\\nLooking for gene symbols in annotation data...\")\n",
    "for col in gene_annotation.columns:\n",
    "    sample_values = gene_annotation[col].head(10).tolist()\n",
    "    print(f\"Column '{col}' sample values: {sample_values}\")\n",
    "\n",
    "# Count how many unique probes we have for mapping\n",
    "unique_probes = mapping_data['ID'].nunique()\n",
    "print(f\"\\nNumber of unique probes for mapping: {unique_probes}\")\n",
    "\n",
    "# Count how many probes map to at least one gene identifier\n",
    "genes_mapped = mapping_data.shape[0]\n",
    "total_probes = gene_annotation.shape[0]\n",
    "mapping_percentage = (genes_mapped / total_probes) * 100 if total_probes > 0 else 0\n",
    "print(f\"Found gene identifiers for {genes_mapped} out of {total_probes} probes ({mapping_percentage:.2f}%)\")\n",
    "\n",
    "# The mapping contains Entrez Gene IDs which are numeric identifiers from NCBI\n",
    "# We'll use these directly since it appears no human-readable gene symbols are available in the annotation\n",
    "gene_mapping = mapping_data\n",
    "\n",
    "# Display the final mapping we'll use\n",
    "print(\"\\nFinal gene mapping sample:\")\n",
    "print(preview_df(gene_mapping, n=5))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b2f994f0",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4c27cb5a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Analyze the gene identifiers and annotation to decide on mapping strategy\n",
    "# From previous steps, we see the gene identifiers in the expression data are numeric IDs ('1', '2', '3', etc.)\n",
    "# The gene annotation has 'ID', 'ENTREZ_GENE_ID', and 'SPOT_ID' columns\n",
    "# The 'ID' in gene annotation corresponds to the probe IDs in the expression data\n",
    "# The 'ENTREZ_GENE_ID' contains Entrez Gene IDs which we'll use as gene identifiers\n",
    "\n",
    "# 2. Create a gene mapping dataframe\n",
    "gene_mapping = gene_annotation[['ID', 'ENTREZ_GENE_ID']].copy()\n",
    "gene_mapping = gene_mapping.dropna(subset=['ENTREZ_GENE_ID'])\n",
    "gene_mapping = gene_mapping.rename(columns={'ENTREZ_GENE_ID': 'Gene'})\n",
    "\n",
    "# Display the gene mapping\n",
    "print(f\"Gene mapping shape: {gene_mapping.shape}\")\n",
    "print(\"Sample of gene mapping dataframe:\")\n",
    "print(preview_df(gene_mapping))\n",
    "\n",
    "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n",
    "# We need to handle the issue with apply_gene_mapping which expects gene symbols\n",
    "\n",
    "# First, select only the rows in gene_mapping that correspond to probes in our gene_data\n",
    "valid_mapping = gene_mapping[gene_mapping['ID'].isin(gene_data.index)]\n",
    "print(f\"Number of probes in gene_data that have mapping: {len(valid_mapping)}\")\n",
    "\n",
    "# Create a simpler mapping function that preserves the Entrez Gene IDs\n",
    "def map_probes_to_genes(expression_df, mapping_df):\n",
    "    \"\"\"Maps probe-level expression to gene-level expression using Entrez Gene IDs.\"\"\"\n",
    "    # Ensure mapping only includes probes that exist in expression data\n",
    "    mapping_df = mapping_df[mapping_df['ID'].isin(expression_df.index)].copy()\n",
    "    \n",
    "    # Set the probe ID as index for joining\n",
    "    mapping_df.set_index('ID', inplace=True)\n",
    "    \n",
    "    # Get all sample columns (all columns in expression_df)\n",
    "    sample_cols = expression_df.columns.tolist()\n",
    "    \n",
    "    # Create a mapping dictionary from probe to gene\n",
    "    probe_to_gene = mapping_df['Gene'].to_dict()\n",
    "    \n",
    "    # Initialize a dictionary to collect gene expression values\n",
    "    gene_expression = {}\n",
    "    gene_counts = {}\n",
    "    \n",
    "    # Process each probe's expression\n",
    "    for probe_id, row in expression_df.iterrows():\n",
    "        if probe_id in probe_to_gene:\n",
    "            gene = probe_to_gene[probe_id]\n",
    "            \n",
    "            # Initialize gene entry if not present\n",
    "            if gene not in gene_expression:\n",
    "                gene_expression[gene] = {col: 0 for col in sample_cols}\n",
    "                gene_counts[gene] = 0\n",
    "            \n",
    "            # Add this probe's expression to the gene\n",
    "            for col in sample_cols:\n",
    "                gene_expression[gene][col] += row[col]\n",
    "            \n",
    "            gene_counts[gene] += 1\n",
    "    \n",
    "    # Create a dataframe from the collected expression values\n",
    "    gene_df = pd.DataFrame.from_dict(gene_expression, orient='index')\n",
    "    \n",
    "    # Average the expression by the number of probes per gene\n",
    "    for gene, count in gene_counts.items():\n",
    "        gene_df.loc[gene] = gene_df.loc[gene] / count\n",
    "    \n",
    "    return gene_df\n",
    "\n",
    "# Apply the mapping function\n",
    "gene_data = map_probes_to_genes(gene_data, gene_mapping)\n",
    "\n",
    "# Display the resulting gene expression data\n",
    "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n",
    "print(\"First 5 gene IDs in the mapped data:\")\n",
    "print(gene_data.index[:5])\n",
    "print(\"Sample of gene expression data (first 5 genes, first 5 columns):\")\n",
    "print(gene_data.iloc[:5, :5])\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 gene expression data\n",
    "gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Gene expression data saved to {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cbe66119",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a02f1489",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Normalize gene symbols using NCBI database\n",
    "print(\"Normalizing gene symbols...\")\n",
    "gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Gene data shape after normalization: {gene_data.shape}\")\n",
    "print(\"First 10 normalized gene symbols:\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# Save the normalized gene data\n",
    "gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Normalized gene data saved to: {out_gene_data_file}\")\n",
    "\n",
    "# 2. Extract and prepare clinical data from the matrix file\n",
    "print(\"\\nPreparing clinical data...\")\n",
    "\n",
    "# Get the clinical data rows\n",
    "_, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
    "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
    "_, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
    "\n",
    "# Process clinical data using the parameters defined in Step 2\n",
    "selected_clinical_df = geo_select_clinical_features(\n",
    "    clinical_df=clinical_data,\n",
    "    trait=trait,\n",
    "    trait_row=0,  # From Step 2: trait_row = 0\n",
    "    convert_trait=convert_trait,  # Function defined in Step 2\n",
    "    age_row=None,  # From Step 2: age_row = None\n",
    "    convert_age=None,\n",
    "    gender_row=None,  # From Step 2: gender_row = None\n",
    "    convert_gender=None\n",
    ")\n",
    "\n",
    "print(\"Clinical data preview:\")\n",
    "print(preview_df(selected_clinical_df))\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",
    "# 3. Link clinical and genetic data\n",
    "print(\"\\nLinking clinical and genetic data...\")\n",
    "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data)\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "print(\"Linked data preview (first 5 rows, 5 columns):\")\n",
    "if linked_data.shape[0] > 0 and linked_data.shape[1] > 5:\n",
    "    print(linked_data.iloc[:5, :5])\n",
    "else:\n",
    "    print(linked_data)\n",
    "\n",
    "# 4. Handle missing values\n",
    "print(\"\\nHandling missing values...\")\n",
    "linked_data_clean = handle_missing_values(linked_data, trait)\n",
    "print(f\"Linked data shape after handling missing values: {linked_data_clean.shape}\")\n",
    "\n",
    "# 5. Check for bias in the dataset\n",
    "print(\"\\nChecking for bias in dataset features...\")\n",
    "is_biased, linked_data_clean = judge_and_remove_biased_features(linked_data_clean, trait)\n",
    "\n",
    "# 6. Conduct final quality validation\n",
    "note = \"This GSE57691 dataset contains gene expression data from patients with abdominal aortic aneurysm (AAA) and aortic occlusive disease (AOD) compared to control subjects. The dataset focuses on atherosclerosis-related vascular changes.\"\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_biased,\n",
    "    df=linked_data_clean,\n",
    "    note=note\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",
    "    linked_data_clean.to_csv(out_data_file, index=True)\n",
    "    print(f\"Linked data saved to {out_data_file}\")\n",
    "else:\n",
    "    print(\"Dataset deemed not usable for associative studies. Linked data not saved.\")"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}