File size: 22,260 Bytes
9fe78b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8e02a120",
   "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 = \"Vitamin_D_Levels\"\n",
    "cohort = \"GSE129604\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Vitamin_D_Levels\"\n",
    "in_cohort_dir = \"../../input/GEO/Vitamin_D_Levels/GSE129604\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Vitamin_D_Levels/GSE129604.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Vitamin_D_Levels/gene_data/GSE129604.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Vitamin_D_Levels/clinical_data/GSE129604.csv\"\n",
    "json_path = \"../../output/preprocess/Vitamin_D_Levels/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "de8e812d",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a916247a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Let's first list the directory contents to understand what files are available\n",
    "import os\n",
    "\n",
    "print(\"Files in the cohort directory:\")\n",
    "files = os.listdir(in_cohort_dir)\n",
    "print(files)\n",
    "\n",
    "# Adapt file identification to handle different naming patterns\n",
    "soft_files = [f for f in files if 'soft' in f.lower() or '.soft' in f.lower() or '_soft' in f.lower()]\n",
    "matrix_files = [f for f in files if 'matrix' in f.lower() or '.matrix' in f.lower() or '_matrix' in f.lower()]\n",
    "\n",
    "# If no files with these patterns are found, look for alternative file types\n",
    "if not soft_files:\n",
    "    soft_files = [f for f in files if f.endswith('.txt') or f.endswith('.gz')]\n",
    "if not matrix_files:\n",
    "    matrix_files = [f for f in files if f.endswith('.txt') or f.endswith('.gz')]\n",
    "\n",
    "print(\"Identified SOFT files:\", soft_files)\n",
    "print(\"Identified matrix files:\", matrix_files)\n",
    "\n",
    "# Use the first files found, if any\n",
    "if len(soft_files) > 0 and len(matrix_files) > 0:\n",
    "    soft_file = os.path.join(in_cohort_dir, soft_files[0])\n",
    "    matrix_file = os.path.join(in_cohort_dir, matrix_files[0])\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(\"\\nBackground Information:\")\n",
    "    print(background_info)\n",
    "    print(\"\\nSample Characteristics Dictionary:\")\n",
    "    print(sample_characteristics_dict)\n",
    "else:\n",
    "    print(\"No appropriate files found in the directory.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "780d90c4",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7d6d10be",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information, this dataset contains whole blood gene expression data\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "\n",
    "# 2.1 Data Availability\n",
    "# For trait - Vitamin D Levels\n",
    "# From the sample characteristics, we can see agent row (2) contains information about vitamin D supplementation\n",
    "trait_row = 2\n",
    "\n",
    "# For age\n",
    "# Age information is not available in the sample characteristics\n",
    "age_row = None\n",
    "\n",
    "# For gender\n",
    "# Gender information is available in the sample characteristics at row 0\n",
    "gender_row = 0\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert vitamin D treatment information to binary\"\"\"\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Create binary classification: 1 for vitamin D treatment, 0 for non-vitamin D treatment\n",
    "    if 'VitD' in value:\n",
    "        return 1\n",
    "    else:\n",
    "        return 0\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age to continuous numeric value\"\"\"\n",
    "    # No age data available\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender to binary (0 for female, 1 for male)\"\"\"\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    if value.lower() == 'male':\n",
    "        return 1\n",
    "    elif value.lower() == 'female':\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait data availability based on trait_row\n",
    "is_trait_available = trait_row is not None\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. Clinical Feature Extraction\n",
    "if trait_row is not None:\n",
    "    # Load the matrix file line by line to extract the sample characteristics section correctly\n",
    "    sample_data = []\n",
    "    in_characteristics = False\n",
    "    \n",
    "    with gzip.open(f\"{in_cohort_dir}/GSE129604_series_matrix.txt.gz\", 'rt') as f:\n",
    "        for line in f:\n",
    "            line = line.strip()\n",
    "            if line.startswith('!Sample_characteristics_ch1'):\n",
    "                in_characteristics = True\n",
    "                char_value = line.replace('!Sample_characteristics_ch1', '').strip()\n",
    "                sample_data.append(char_value)\n",
    "            elif in_characteristics and line.startswith('!'):\n",
    "                if not line.startswith('!Sample_characteristics_ch1'):\n",
    "                    in_characteristics = False\n",
    "    \n",
    "    # Determine the number of samples\n",
    "    num_samples = len(sample_data)\n",
    "    \n",
    "    # Group the characteristics by row\n",
    "    grouped_chars = {}\n",
    "    row_index = 0\n",
    "    \n",
    "    for i in range(0, num_samples, 1):\n",
    "        if i < len(sample_data):\n",
    "            char_value = sample_data[i]\n",
    "            if row_index not in grouped_chars:\n",
    "                grouped_chars[row_index] = []\n",
    "            grouped_chars[row_index].append(char_value)\n",
    "        \n",
    "        if (i + 1) % 4 == 0:  # Each sample has 4 characteristics\n",
    "            row_index += 1\n",
    "    \n",
    "    # Create a DataFrame from the grouped characteristics\n",
    "    clinical_data = pd.DataFrame(grouped_chars)\n",
    "    \n",
    "    # Extract clinical features\n",
    "    clinical_features = geo_select_clinical_features(\n",
    "        clinical_data,\n",
    "        trait=trait,\n",
    "        trait_row=trait_row,\n",
    "        convert_trait=convert_trait,\n",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender\n",
    "    )\n",
    "    \n",
    "    # Preview the extracted clinical features\n",
    "    preview = preview_df(clinical_features)\n",
    "    print(\"Clinical Features Preview:\")\n",
    "    print(preview)\n",
    "    \n",
    "    # Save the clinical data\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    clinical_features.to_csv(out_clinical_data_file, index=False)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a136431e",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8059bb0b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Use the helper function to get the proper file paths\n",
    "soft_file_path, matrix_file_path = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# Extract gene expression data\n",
    "try:\n",
    "    gene_data = get_genetic_data(matrix_file_path)\n",
    "    \n",
    "    # Print the first 20 row IDs (gene or probe identifiers)\n",
    "    print(\"First 20 gene/probe identifiers:\")\n",
    "    print(gene_data.index[:20])\n",
    "    \n",
    "    # Print shape to understand the dataset dimensions\n",
    "    print(f\"\\nGene expression data shape: {gene_data.shape}\")\n",
    "    \n",
    "except Exception as e:\n",
    "    print(f\"Error extracting gene data: {e}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e7912a9f",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a5375ea3",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Examining the gene identifiers from the previous step\n",
    "# The identifiers (AFFX-BkGr-GC03_st, etc.) are Affymetrix probe IDs from a microarray platform\n",
    "# They are not standard human gene symbols and need to be mapped to gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ac8bdb80",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4c0bbd1c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. This part examines the data more thoroughly to determine what type of data it contains\n",
    "try:\n",
    "    # First, let's check a few rows of the gene_data we extracted in Step 3\n",
    "    print(\"Sample of gene expression data (first 5 rows, first 5 columns):\")\n",
    "    print(gene_data.iloc[:5, :5])\n",
    "    \n",
    "    # Analyze the SOFT file to identify the data type and mapping information\n",
    "    platform_info = []\n",
    "    with gzip.open(soft_file_path, 'rt', encoding='latin-1') as f:\n",
    "        for line in f:\n",
    "            if line.startswith(\"!Platform_title\") or line.startswith(\"!Series_title\") or \"description\" in line.lower():\n",
    "                platform_info.append(line.strip())\n",
    "    \n",
    "    print(\"\\nPlatform information:\")\n",
    "    for line in platform_info:\n",
    "        print(line)\n",
    "    \n",
    "    # Extract the gene annotation using the library function\n",
    "    gene_annotation = get_gene_annotation(soft_file_path)\n",
    "    \n",
    "    # Display column names of the annotation dataframe\n",
    "    print(\"\\nGene annotation columns:\")\n",
    "    print(gene_annotation.columns.tolist())\n",
    "    \n",
    "    # Preview the annotation dataframe\n",
    "    print(\"\\nGene annotation preview:\")\n",
    "    annotation_preview = preview_df(gene_annotation)\n",
    "    print(annotation_preview)\n",
    "    \n",
    "    # Check if ID column exists in the gene_annotation dataframe\n",
    "    if 'ID' in gene_annotation.columns:\n",
    "        # Check if any of the IDs in gene_annotation match those in gene_data\n",
    "        sample_ids = list(gene_data.index[:10])\n",
    "        matching_rows = gene_annotation[gene_annotation['ID'].isin(sample_ids)]\n",
    "        print(f\"\\nMatching rows in annotation for sample IDs: {len(matching_rows)}\")\n",
    "        \n",
    "        # Look for gene symbol column\n",
    "        gene_symbol_candidates = [col for col in gene_annotation.columns if 'gene' in col.lower() or 'symbol' in col.lower() or 'name' in col.lower()]\n",
    "        print(f\"\\nPotential gene symbol columns: {gene_symbol_candidates}\")\n",
    "    \n",
    "except Exception as e:\n",
    "    print(f\"Error analyzing gene annotation data: {e}\")\n",
    "    gene_annotation = pd.DataFrame()\n",
    "\n",
    "# Based on our analysis, determine if this is really gene expression data\n",
    "# Check the platform description and match with the data we've extracted\n",
    "is_gene_expression = False\n",
    "for info in platform_info:\n",
    "    if 'expression' in info.lower() or 'transcript' in info.lower() or 'mrna' in info.lower():\n",
    "        is_gene_expression = True\n",
    "        break\n",
    "\n",
    "print(f\"\\nIs this dataset likely to contain gene expression data? {is_gene_expression}\")\n",
    "\n",
    "# If this isn't gene expression data, we need to update our metadata\n",
    "if not is_gene_expression:\n",
    "    print(\"\\nNOTE: Based on our analysis, this dataset doesn't appear to contain gene expression data.\")\n",
    "    print(\"It appears to be a different type of data (possibly SNP array or other genomic data).\")\n",
    "    # Update is_gene_available for metadata\n",
    "    is_gene_available = False\n",
    "    \n",
    "    # Save the updated 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"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a075ae68",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dfb63ac4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Extract gene symbols from the SPOT_ID.1 column, which contains detailed annotation including gene symbols\n",
    "def extract_gene_symbol(annotation_str):\n",
    "    \"\"\"Extract gene symbols from complex annotation strings in SPOT_ID.1 column\"\"\"\n",
    "    if not isinstance(annotation_str, str):\n",
    "        return []\n",
    "    \n",
    "    # Look for gene symbols in the format [Source:HGNC Symbol;Acc:HGNC:xxxx]\n",
    "    hgnc_pattern = r'\\[Source:HGNC Symbol;Acc:HGNC:\\d+\\]'\n",
    "    \n",
    "    # Find all occurrences that match the pattern\n",
    "    matches = re.findall(hgnc_pattern, annotation_str)\n",
    "    \n",
    "    # Get the words right before each HGNC reference, which should be the gene names\n",
    "    gene_names = []\n",
    "    for match in matches:\n",
    "        # Find where in the original string this match occurs\n",
    "        start_idx = annotation_str.find(match)\n",
    "        if start_idx > 0:\n",
    "            # Look for the word before the match\n",
    "            before_text = annotation_str[:start_idx].strip()\n",
    "            words = before_text.split()\n",
    "            if words:\n",
    "                gene_name = words[-1]\n",
    "                # Clean any non-alphanumeric characters except certain allowed ones\n",
    "                gene_name = re.sub(r'[^A-Za-z0-9\\-]', '', gene_name)\n",
    "                if gene_name:\n",
    "                    gene_names.append(gene_name)\n",
    "    \n",
    "    # If no HGNC symbols found, try to extract gene symbols from RefSeq entries\n",
    "    if not gene_names:\n",
    "        refseq_pattern = r'NM_\\d+ // RefSeq // Homo sapiens ([^(]+)'\n",
    "        refseq_matches = re.findall(refseq_pattern, annotation_str)\n",
    "        for match in refseq_matches:\n",
    "            gene_name = match.split('(')[0].strip()\n",
    "            if ',' in gene_name:\n",
    "                gene_name = gene_name.split(',')[0].strip()\n",
    "            if gene_name:\n",
    "                gene_names.append(gene_name)\n",
    "    \n",
    "    # Deduplicate gene names\n",
    "    return list(set(gene_names))\n",
    "\n",
    "# Add gene symbols to the annotation dataframe\n",
    "gene_annotation['Gene_Symbols'] = gene_annotation['SPOT_ID.1'].apply(extract_gene_symbol)\n",
    "\n",
    "# Check the IDs in gene expression data\n",
    "print(\"Sample IDs from gene expression data:\")\n",
    "print(gene_data.index[:5])\n",
    "\n",
    "# Check if there are matching IDs in the annotation\n",
    "matching_ids = [idx for idx in gene_data.index if idx in gene_annotation['ID'].values]\n",
    "print(f\"\\nNumber of IDs from gene expression data that match annotation: {len(matching_ids)}\")\n",
    "\n",
    "# If there's a mismatch, analyze the format of IDs in both datasets\n",
    "if len(matching_ids) < 100:\n",
    "    # Looking for patterns in the gene expression IDs\n",
    "    print(\"\\nPattern in gene expression IDs:\")\n",
    "    expression_id_pattern = re.findall(r'([A-Za-z\\-]+)(\\d+)', gene_data.index[0])\n",
    "    print(f\"Expression ID pattern example: {expression_id_pattern}\")\n",
    "    \n",
    "    # Looking for patterns in the annotation IDs\n",
    "    print(\"\\nPattern in annotation IDs:\")\n",
    "    annotation_id_pattern = re.findall(r'([A-Za-z\\-]+)(\\d+)', gene_annotation['ID'].iloc[0])\n",
    "    print(f\"Annotation ID pattern example: {annotation_id_pattern}\")\n",
    "\n",
    "# Let's check for a different IDs that might match between datasets\n",
    "print(\"\\nChecking for alternative ID matches...\")\n",
    "\n",
    "# Get a sample of probe IDs from gene_annotation\n",
    "sample_annotation_ids = gene_annotation['probeset_id'].head(10).tolist()\n",
    "print(\"Sample annotation probeset_ids:\", sample_annotation_ids)\n",
    "\n",
    "# Check if any of these exist in the gene expression data\n",
    "found_in_expression = [id in gene_data.index for id in sample_annotation_ids]\n",
    "print(f\"Found in expression data: {sum(found_in_expression)} out of 10\")\n",
    "\n",
    "# The probeset_id seems to be a better match for what we need for mapping\n",
    "# Create a mapping dataframe with probeset_id and Gene_Symbols\n",
    "mapping_df = pd.DataFrame({\n",
    "    'ID': gene_annotation['probeset_id'],\n",
    "    'Gene': gene_annotation['Gene_Symbols']\n",
    "})\n",
    "\n",
    "# Remove rows with empty gene symbols\n",
    "mapping_df = mapping_df[mapping_df['Gene'].apply(lambda x: len(x) > 0)]\n",
    "print(f\"\\nCreated mapping with {len(mapping_df)} entries\")\n",
    "\n",
    "# Apply gene mapping to convert probe measurements to gene expression\n",
    "try:\n",
    "    # First explode the Gene column to handle one-to-many mappings\n",
    "    gene_data_mapped = apply_gene_mapping(gene_data, mapping_df)\n",
    "    print(f\"\\nConverted probe data to gene expression data with {len(gene_data_mapped)} genes\")\n",
    "    \n",
    "    # Check the first few genes\n",
    "    print(\"\\nFirst 10 genes in the mapped data:\")\n",
    "    print(gene_data_mapped.index[:10])\n",
    "    \n",
    "    # Save the gene expression data\n",
    "    os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "    gene_data_mapped.to_csv(out_gene_data_file)\n",
    "    print(f\"\\nGene expression data saved to {out_gene_data_file}\")\n",
    "    \n",
    "except Exception as e:\n",
    "    print(f\"Error during gene mapping: {e}\")\n",
    "    \n",
    "    # Let's try a simpler approach if the mapping fails\n",
    "    print(\"\\nAttempting alternative mapping approach...\")\n",
    "    \n",
    "    # Let's attempt to extract gene symbols from the SOFT file directly\n",
    "    gene_symbols = []\n",
    "    with gzip.open(soft_file_path, 'rt', encoding='latin-1') as f:\n",
    "        for line in f:\n",
    "            if \"gene_assignment\" in line.lower() and \"=\" in line:\n",
    "                parts = line.split(\"=\")\n",
    "                if len(parts) > 1:\n",
    "                    gene_info = parts[1].strip()\n",
    "                    print(f\"Sample gene assignment: {gene_info}\")\n",
    "                    break\n",
    "    \n",
    "    # If we can't get a proper mapping, let's normalize the dataset using the extract_human_gene_symbols function\n",
    "    # By processing each probeset ID in the SPOT_ID.1 column\n",
    "    print(\"\\nPerforming direct gene symbol extraction from annotation...\")\n",
    "    mapping_df = pd.DataFrame({\n",
    "        'ID': gene_annotation['ID'],\n",
    "        'Gene': gene_annotation['SPOT_ID.1'].apply(extract_human_gene_symbols)\n",
    "    })\n",
    "    \n",
    "    # Remove rows with empty gene symbols\n",
    "    mapping_df = mapping_df[mapping_df['Gene'].apply(lambda x: len(x) > 0)]\n",
    "    print(f\"Created mapping with {len(mapping_df)} entries using direct gene symbol extraction\")\n",
    "    \n",
    "    # Apply gene mapping to convert probe measurements to gene expression\n",
    "    gene_data_mapped = apply_gene_mapping(gene_data, mapping_df)\n",
    "    print(f\"Converted probe data to gene expression data with {len(gene_data_mapped)} genes\")\n",
    "    \n",
    "    # Save the gene expression data\n",
    "    os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "    gene_data_mapped.to_csv(out_gene_data_file)\n",
    "    print(f\"Gene expression data saved to {out_gene_data_file}\")\n",
    "\n",
    "# Assign the mapped data to gene_data for the next steps\n",
    "gene_data = gene_data_mapped"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}