File size: 23,744 Bytes
d1894e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bbc640a5",
   "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 = \"Gastroesophageal_reflux_disease_(GERD)\"\n",
    "cohort = \"GSE77563\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Gastroesophageal_reflux_disease_(GERD)\"\n",
    "in_cohort_dir = \"../../input/GEO/Gastroesophageal_reflux_disease_(GERD)/GSE77563\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Gastroesophageal_reflux_disease_(GERD)/GSE77563.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Gastroesophageal_reflux_disease_(GERD)/gene_data/GSE77563.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Gastroesophageal_reflux_disease_(GERD)/clinical_data/GSE77563.csv\"\n",
    "json_path = \"../../output/preprocess/Gastroesophageal_reflux_disease_(GERD)/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e790ff46",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d39fbcc3",
   "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": "e43ecd56",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "62084be8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Analyze gene expression data availability\n",
    "# Based on the background information, this dataset contains Affymetrix expression array profiles\n",
    "# which indicates it's likely to contain gene expression data\n",
    "is_gene_available = True  # Affymetrix Human Gene 2.1 ST arrays data is available\n",
    "\n",
    "# 2. Analyze variable availability and data type conversion\n",
    "# 2.1 Data Availability\n",
    "\n",
    "# For trait (GERD):\n",
    "# Key 5 contains GERD status information\n",
    "trait_row = 5\n",
    "\n",
    "# For age:\n",
    "# Key 1 contains age information\n",
    "age_row = 1\n",
    "\n",
    "# For gender:\n",
    "# Key 2 contains gender information\n",
    "gender_row = 2\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "\n",
    "# For trait (GERD):\n",
    "def convert_trait(value):\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary (0 for No GERD, 1 for GERD)\n",
    "    if \"No GERD\" in value:\n",
    "        return 0\n",
    "    elif \"GERD\" in value:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# For age:\n",
    "def convert_age(value):\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Convert to continuous\n",
    "    try:\n",
    "        return float(value)\n",
    "    except:\n",
    "        return None\n",
    "\n",
    "# For gender:\n",
    "def convert_gender(value):\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary (0 for female, 1 for male)\n",
    "    if \"female\" in value.lower():\n",
    "        return 0\n",
    "    elif \"male\" in value.lower():\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine if trait data is available\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# 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",
    "    # Extract clinical features\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 data\n",
    "    print(\"Preview of extracted clinical data:\")\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, index=False)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0340368b",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "33feb428",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Get the file paths for the SOFT file and matrix file\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. First, let's examine the structure of the matrix file to understand its format\n",
    "import gzip\n",
    "\n",
    "# Peek at the first few lines of the file to understand its structure\n",
    "with gzip.open(matrix_file, 'rt') as file:\n",
    "    # Read first 100 lines to find the header structure\n",
    "    for i, line in enumerate(file):\n",
    "        if '!series_matrix_table_begin' in line:\n",
    "            print(f\"Found data marker at line {i}\")\n",
    "            # Read the next line which should be the header\n",
    "            header_line = next(file)\n",
    "            print(f\"Header line: {header_line.strip()}\")\n",
    "            # And the first data line\n",
    "            first_data_line = next(file)\n",
    "            print(f\"First data line: {first_data_line.strip()}\")\n",
    "            break\n",
    "        if i > 100:  # Limit search to first 100 lines\n",
    "            print(\"Matrix table marker not found in first 100 lines\")\n",
    "            break\n",
    "\n",
    "# 3. Now try to get the genetic data with better error handling\n",
    "try:\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    print(gene_data.index[:20])\n",
    "except KeyError as e:\n",
    "    print(f\"KeyError: {e}\")\n",
    "    \n",
    "    # Alternative approach: manually extract the data\n",
    "    print(\"\\nTrying alternative approach to read the gene data:\")\n",
    "    with gzip.open(matrix_file, 'rt') as file:\n",
    "        # Find the start of the data\n",
    "        for line in file:\n",
    "            if '!series_matrix_table_begin' in line:\n",
    "                break\n",
    "                \n",
    "        # Read the headers and data\n",
    "        import pandas as pd\n",
    "        df = pd.read_csv(file, sep='\\t', index_col=0)\n",
    "        print(f\"Column names: {df.columns[:5]}\")\n",
    "        print(f\"First 20 row IDs: {df.index[:20]}\")\n",
    "        gene_data = df\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f217182",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "00fdd04f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# The identifiers seen in the gene expression data (16657436, 16657445, etc.) appear to be \n",
    "# Affymetrix probeset IDs rather than human gene symbols. These are numeric identifiers \n",
    "# specific to the microarray platform used in this study.\n",
    "#\n",
    "# Standard human gene symbols would typically be alphabetic (like \"BRCA1\", \"TP53\", etc.) \n",
    "# or alphanumeric combinations that follow a recognizable pattern.\n",
    "#\n",
    "# These numeric IDs will need to be mapped to standard gene symbols for meaningful analysis.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0b8f0a47",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "790eea20",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Let's first examine the structure of the SOFT file before trying to parse it\n",
    "import gzip\n",
    "\n",
    "# Look at the first few lines of the SOFT file to understand its structure\n",
    "print(\"Examining SOFT file structure:\")\n",
    "try:\n",
    "    with gzip.open(soft_file, 'rt') as file:\n",
    "        # Read first 20 lines to understand the file structure\n",
    "        for i, line in enumerate(file):\n",
    "            if i < 20:\n",
    "                print(f\"Line {i}: {line.strip()}\")\n",
    "            else:\n",
    "                break\n",
    "except Exception as e:\n",
    "    print(f\"Error reading SOFT file: {e}\")\n",
    "\n",
    "# 2. Now let's try a more robust approach to extract the gene annotation\n",
    "# Instead of using the library function which failed, we'll implement a custom approach\n",
    "try:\n",
    "    # First, look for the platform section which contains gene annotation\n",
    "    platform_data = []\n",
    "    with gzip.open(soft_file, 'rt') as file:\n",
    "        in_platform_section = False\n",
    "        for line in file:\n",
    "            if line.startswith('^PLATFORM'):\n",
    "                in_platform_section = True\n",
    "                continue\n",
    "            if in_platform_section and line.startswith('!platform_table_begin'):\n",
    "                # Next line should be the header\n",
    "                header = next(file).strip()\n",
    "                platform_data.append(header)\n",
    "                # Read until the end of the platform table\n",
    "                for table_line in file:\n",
    "                    if table_line.startswith('!platform_table_end'):\n",
    "                        break\n",
    "                    platform_data.append(table_line.strip())\n",
    "                break\n",
    "    \n",
    "    # If we found platform data, convert it to a DataFrame\n",
    "    if platform_data:\n",
    "        import pandas as pd\n",
    "        import io\n",
    "        platform_text = '\\n'.join(platform_data)\n",
    "        gene_annotation = pd.read_csv(io.StringIO(platform_text), delimiter='\\t', \n",
    "                                      low_memory=False, on_bad_lines='skip')\n",
    "        print(\"\\nGene annotation preview:\")\n",
    "        print(preview_df(gene_annotation))\n",
    "    else:\n",
    "        print(\"Could not find platform table in SOFT file\")\n",
    "        \n",
    "        # Try an alternative approach - extract mapping from other sections\n",
    "        with gzip.open(soft_file, 'rt') as file:\n",
    "            for line in file:\n",
    "                if 'ANNOTATION information' in line or 'annotation information' in line:\n",
    "                    print(f\"Found annotation information: {line.strip()}\")\n",
    "                if line.startswith('!Platform_title') or line.startswith('!platform_title'):\n",
    "                    print(f\"Platform title: {line.strip()}\")\n",
    "            \n",
    "except Exception as e:\n",
    "    print(f\"Error processing gene annotation: {e}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "91185d03",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9d3902d0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. First, make sure we have the gene expression data loaded properly\n",
    "gene_data = get_genetic_data(matrix_file)\n",
    "\n",
    "# 2. Extract and prepare the gene mapping dataframe\n",
    "# Looking at the data, 'ID' contains the numeric identifiers that match the gene expression data\n",
    "# The 'gene_assignment' column contains gene symbol information\n",
    "mapping_df = gene_annotation[['ID', 'gene_assignment']]\n",
    "\n",
    "# Convert IDs to strings for consistent comparison\n",
    "mapping_df['ID'] = mapping_df['ID'].astype(str)\n",
    "\n",
    "# 3. Extract gene symbols from the complex gene_assignment field\n",
    "# Use the built-in extract_human_gene_symbols function which is more robust\n",
    "# It's able to identify gene symbols from complex text following standard patterns\n",
    "mapping_df['Gene'] = mapping_df['gene_assignment'].apply(extract_human_gene_symbols)\n",
    "\n",
    "# Print diagnostic information about the mapping\n",
    "print(f\"Number of probes in gene_data: {len(gene_data.index)}\")\n",
    "print(f\"Original mapping rows: {len(mapping_df)}\")\n",
    "print(f\"Sample of original mappings:\")\n",
    "print(mapping_df[['ID', 'Gene']].head(5))\n",
    "\n",
    "# Filter out mappings with empty gene lists\n",
    "mapping_df = mapping_df[mapping_df['Gene'].apply(len) > 0]\n",
    "print(f\"Filtered mapping rows: {len(mapping_df)}\")\n",
    "print(f\"Number of mappable probes: {len(mapping_df[mapping_df['ID'].isin(gene_data.index)])}\")\n",
    "\n",
    "# 4. Apply the gene mapping to get gene expression data\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_df[['ID', 'Gene']])\n",
    "\n",
    "# Check data before normalization\n",
    "print(f\"\\nBefore normalization - shape: {gene_data.shape}\")\n",
    "print(f\"Sample gene symbols before normalization: {list(gene_data.index[:10])}\")\n",
    "\n",
    "# 5. Create a modified normalization function that preserves unmapped symbols\n",
    "def modified_normalize_gene_symbols(gene_df):\n",
    "    with open(\"./metadata/gene_synonym.json\", \"r\") as f:\n",
    "        synonym_dict = json.load(f)\n",
    "    \n",
    "    # Create a mapping function that keeps original symbol if not in dictionary\n",
    "    def map_symbol(x):\n",
    "        return synonym_dict.get(x.upper(), x)\n",
    "    \n",
    "    gene_df.index = gene_df.index.map(map_symbol)\n",
    "    # Group and average rows with same index (after normalization)\n",
    "    return gene_df.groupby(gene_df.index).mean()\n",
    "\n",
    "# Apply the modified normalization\n",
    "gene_data = modified_normalize_gene_symbols(gene_data)\n",
    "\n",
    "# Preview the mapped gene data\n",
    "print(\"\\nPreview of mapped gene data:\")\n",
    "print(f\"Shape: {gene_data.shape}\")\n",
    "print(gene_data.head())\n",
    "\n",
    "# Save the gene expression data\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 expression data saved to {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "576d8241",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a6f8b089",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Examine the issue with gene mapping in previous step\n",
    "print(\"Analyzing gene mapping issue...\")\n",
    "gene_data = get_genetic_data(matrix_file)\n",
    "print(f\"Gene data from file: {gene_data.shape}\")\n",
    "\n",
    "# Load gene annotation data more directly\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "print(f\"Gene annotation data shape: {gene_annotation.shape}\")\n",
    "\n",
    "# Extract and prepare the gene mapping dataframe\n",
    "mapping_df = gene_annotation[['ID', 'gene_assignment']]\n",
    "\n",
    "# Check a sample of the gene_assignment column\n",
    "print(\"\\nSample of gene_assignment data:\")\n",
    "for i, assignment in enumerate(mapping_df['gene_assignment'].head(3)):\n",
    "    print(f\"Assignment {i}: {assignment[:100]}...\")\n",
    "\n",
    "# Apply extract_human_gene_symbols function to get gene symbols\n",
    "mapping_df['Gene'] = mapping_df['gene_assignment'].apply(extract_human_gene_symbols)\n",
    "\n",
    "# Print sample of extracted genes\n",
    "print(\"\\nSample of extracted genes:\")\n",
    "print(mapping_df[['ID', 'Gene']].head(5))\n",
    "\n",
    "# Implement a direct gene mapping approach as a fallback\n",
    "print(\"\\nImplementing alternative gene mapping approach...\")\n",
    "gene_to_expr = {}\n",
    "\n",
    "# First, create a mapping from probe IDs to gene symbols\n",
    "probe_to_genes = {}\n",
    "for i, row in mapping_df.iterrows():\n",
    "    probe_id = str(row['ID'])\n",
    "    genes = row['Gene']\n",
    "    if genes and len(genes) > 0:\n",
    "        probe_to_genes[probe_id] = genes\n",
    "\n",
    "# Apply the mapping to distribute expression values\n",
    "for probe_id, expr_values in gene_data.iterrows():\n",
    "    probe_id_str = str(probe_id)\n",
    "    if probe_id_str in probe_to_genes:\n",
    "        genes = probe_to_genes[probe_id_str]\n",
    "        value_share = 1.0 / len(genes)\n",
    "        \n",
    "        for gene in genes:\n",
    "            if gene not in gene_to_expr:\n",
    "                gene_to_expr[gene] = pd.Series(0, index=expr_values.index)\n",
    "            gene_to_expr[gene] += expr_values * value_share\n",
    "\n",
    "# Convert the dictionary to a DataFrame\n",
    "gene_data = pd.DataFrame(gene_to_expr).T\n",
    "print(f\"Gene data after direct mapping: {gene_data.shape}\")\n",
    "\n",
    "# 1. Normalize gene symbols in the obtained gene expression data\n",
    "# Normalize gene symbols using NCBI Gene database\n",
    "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
    "print(f\"Sample gene symbols after normalization: {list(normalized_gene_data.index[:10])}\")\n",
    "\n",
    "# Save the normalized gene data\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "normalized_gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
    "\n",
    "# 2. Link clinical and genetic data\n",
    "# Get raw clinical data from the matrix file\n",
    "_, clinical_raw = get_background_and_clinical_data(matrix_file)\n",
    "\n",
    "# Extract clinical features using the defined conversion functions\n",
    "clinical_features = geo_select_clinical_features(\n",
    "    clinical_df=clinical_raw,\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",
    "print(\"Clinical features shape:\", clinical_features.shape)\n",
    "\n",
    "# Save clinical features to file\n",
    "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "clinical_features.to_csv(out_clinical_data_file)\n",
    "print(f\"Clinical features saved to {out_clinical_data_file}\")\n",
    "\n",
    "# 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",
    "print(\"Linked data preview (first 5 rows, first 5 columns):\")\n",
    "if linked_data.shape[1] >= 5:\n",
    "    print(linked_data.iloc[:5, :5])\n",
    "else:\n",
    "    print(linked_data.head())\n",
    "\n",
    "# 3. Handle missing values\n",
    "print(\"\\nMissing values before handling:\")\n",
    "print(f\"  Trait ({trait}) missing: {linked_data[trait].isna().sum()} out of {len(linked_data)}\")\n",
    "if 'Age' in linked_data.columns:\n",
    "    print(f\"  Age missing: {linked_data['Age'].isna().sum()} out of {len(linked_data)}\")\n",
    "if 'Gender' in linked_data.columns:\n",
    "    print(f\"  Gender missing: {linked_data['Gender'].isna().sum()} out of {len(linked_data)}\")\n",
    "\n",
    "gene_cols = [col for col in linked_data.columns if col not in [trait, 'Age', 'Gender']]\n",
    "if gene_cols:\n",
    "    print(f\"  Genes with >20% missing: {sum(linked_data[gene_cols].isna().mean() > 0.2)}\")\n",
    "    print(f\"  Samples with >5% missing genes: {sum(linked_data[gene_cols].isna().mean(axis=1) > 0.05)}\")\n",
    "\n",
    "cleaned_data = handle_missing_values(linked_data, trait)\n",
    "print(f\"Data shape after handling missing values: {cleaned_data.shape}\")\n",
    "\n",
    "# 4. Evaluate bias in trait and demographic features\n",
    "is_trait_biased = False\n",
    "if len(cleaned_data) > 0:\n",
    "    trait_biased, cleaned_data = judge_and_remove_biased_features(cleaned_data, trait)\n",
    "    is_trait_biased = trait_biased\n",
    "else:\n",
    "    print(\"No data remains after handling missing values.\")\n",
    "    is_trait_biased = True\n",
    "\n",
    "# 5. Final validation and save\n",
    "is_usable = validate_and_save_cohort_info(\n",
    "    is_final=True, \n",
    "    cohort=cohort, \n",
    "    info_path=json_path, \n",
    "    is_gene_available=len(normalized_gene_data) > 0, \n",
    "    is_trait_available=True, \n",
    "    is_biased=is_trait_biased, \n",
    "    df=cleaned_data,\n",
    "    note=f\"Dataset contains gene expression data for {trait} analysis.\"\n",
    ")\n",
    "\n",
    "# 6. Save if usable\n",
    "if is_usable and len(cleaned_data) > 0:\n",
    "    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "    cleaned_data.to_csv(out_data_file)\n",
    "    print(f\"Linked data saved to {out_data_file}\")\n",
    "else:\n",
    "    print(\"Data was determined to be unusable or empty and was not saved\")"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}