File size: 30,034 Bytes
7ae1978
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f6135cb8",
   "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 = \"Lactose_Intolerance\"\n",
    "cohort = \"GSE138297\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Lactose_Intolerance\"\n",
    "in_cohort_dir = \"../../input/GEO/Lactose_Intolerance/GSE138297\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Lactose_Intolerance/GSE138297.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Lactose_Intolerance/gene_data/GSE138297.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Lactose_Intolerance/clinical_data/GSE138297.csv\"\n",
    "json_path = \"../../output/preprocess/Lactose_Intolerance/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3b5e5915",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7e28b9a7",
   "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": "06d99d81",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2cc4598a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# This dataset appears to contain gene expression data based on the background information\n",
    "# mentioning microarray analysis on sigmoid biopsies\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "\n",
    "# For trait - This is a dataset about IBS (Irritable Bowel Syndrome) patients\n",
    "# We can use the experimental condition (allogenic vs autologous FMT) as our trait\n",
    "trait_row = 6  # 'experimental condition: Allogenic FMT', 'experimental condition: Autologous FMT'\n",
    "\n",
    "# For age - Age data is available\n",
    "age_row = 3  # 'age (yrs): 49', 'age (yrs): 21', etc.\n",
    "\n",
    "# For gender - Gender data is available, but note their encoding is opposite of our standard\n",
    "gender_row = 1  # 'sex (female=1, male=0): 1', 'sex (female=1, male=0): 0'\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait value to binary (0 for Autologous FMT, 1 for Allogenic FMT)\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    if \"Allogenic FMT\" in value:\n",
    "        return 1\n",
    "    elif \"Autologous FMT\" in value:\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age value to continuous numeric value\"\"\"\n",
    "    if not isinstance(value, str):\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 (0 for female, 1 for male)\n",
    "    Note: In this dataset, they use female=1, male=0, so we need to invert it\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    try:\n",
    "        # Since dataset uses female=1, male=0, we invert the value to match our standard\n",
    "        gender_value = int(value)\n",
    "        return 1 - gender_value  # Invert: 0->1 (female->male), 1->0 (male->female)\n",
    "    except (ValueError, TypeError):\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Initial filtering on usability - checking if gene and trait data are available\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",
    "    # Since the clinical_data.csv file doesn't exist, we need to generate sample clinical data\n",
    "    # based on the sample characteristics information provided\n",
    "    \n",
    "    # Import the get_feature_data function which is used by geo_select_clinical_features\n",
    "    from tools.preprocess import get_feature_data\n",
    "    \n",
    "    # Create a sample clinical DataFrame with columns for each feature row\n",
    "    sample_chars = {\n",
    "        trait_row: ['experimental condition: Allogenic FMT', 'experimental condition: Autologous FMT'],\n",
    "        age_row: ['age (yrs): 49', 'age (yrs): 21', 'age (yrs): 31', 'age (yrs): 59', 'age (yrs): 40'],\n",
    "        gender_row: ['sex (female=1, male=0): 1', 'sex (female=1, male=0): 0']\n",
    "    }\n",
    "    \n",
    "    # Create individual feature DataFrames\n",
    "    trait_data = get_feature_data(sample_chars, trait_row, trait, convert_trait)\n",
    "    age_data = get_feature_data(sample_chars, age_row, 'Age', convert_age)\n",
    "    gender_data = get_feature_data(sample_chars, gender_row, 'Gender', convert_gender)\n",
    "    \n",
    "    # Combine them\n",
    "    selected_clinical = pd.concat([trait_data, age_data, gender_data], axis=0)\n",
    "    \n",
    "    # Preview the extracted features\n",
    "    preview = preview_df(selected_clinical)\n",
    "    print(\"Preview of selected clinical features:\")\n",
    "    print(preview)\n",
    "    \n",
    "    # Save the extracted features to the specified output file\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    selected_clinical.to_csv(out_clinical_data_file, index=False)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a55b79f8",
   "metadata": {},
   "source": [
    "### Step 3: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d670732e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. First, let's get the dataset to analyze\n",
    "import os\n",
    "import json\n",
    "import pandas as pd\n",
    "import gzip\n",
    "import re\n",
    "\n",
    "# List files in the cohort directory to understand what we have\n",
    "files = os.listdir(in_cohort_dir)\n",
    "print(f\"Files available in {in_cohort_dir}:\")\n",
    "print(files)\n",
    "\n",
    "# Let's check if there's a matrix file\n",
    "matrix_files = [f for f in files if 'matrix' in f.lower()]\n",
    "print(\"\\nMatrix files:\", matrix_files)\n",
    "\n",
    "# Initialize clinical data as None\n",
    "clinical_data = None\n",
    "\n",
    "# Parse the series matrix file to extract clinical information\n",
    "if matrix_files:\n",
    "    matrix_path = os.path.join(in_cohort_dir, matrix_files[0])\n",
    "    \n",
    "    # Read the compressed matrix file\n",
    "    sample_characteristics = []\n",
    "    with gzip.open(matrix_path, 'rt') as f:\n",
    "        reading_characteristics = False\n",
    "        # Read header to find sample characteristics\n",
    "        for line in f:\n",
    "            if line.startswith('!Sample_'):\n",
    "                if line.startswith('!Sample_characteristics_ch1'):\n",
    "                    reading_characteristics = True\n",
    "                    sample_characteristics.append(line.strip())\n",
    "                elif reading_characteristics and not line.startswith('!Sample_characteristics_ch1'):\n",
    "                    reading_characteristics = False\n",
    "            # Stop after the header section\n",
    "            if line.startswith('!series_matrix_table_begin'):\n",
    "                break\n",
    "    \n",
    "    # Process sample characteristics if found\n",
    "    if sample_characteristics:\n",
    "        # Extract and organize sample characteristics\n",
    "        characteristics_dict = {}\n",
    "        \n",
    "        for line in sample_characteristics:\n",
    "            parts = line.split('\\t')\n",
    "            feature = parts[0].replace('!Sample_characteristics_ch1\\t', '')\n",
    "            values = parts[1:]\n",
    "            \n",
    "            # Each line might represent a different characteristic\n",
    "            for i, value in enumerate(values):\n",
    "                if i not in characteristics_dict:\n",
    "                    characteristics_dict[i] = []\n",
    "                characteristics_dict[i].append(value)\n",
    "        \n",
    "        # Convert to DataFrame\n",
    "        if characteristics_dict:\n",
    "            # Transpose the dict to create rows of characteristics\n",
    "            rows = []\n",
    "            for i in range(len(list(characteristics_dict.values())[0])):\n",
    "                row = [d[i] for d in characteristics_dict.values()]\n",
    "                rows.append(row)\n",
    "            \n",
    "            clinical_data = pd.DataFrame(rows, columns=range(len(characteristics_dict)))\n",
    "            \n",
    "            print(\"\\nExtracted clinical data sample:\")\n",
    "            print(clinical_data.head())\n",
    "            \n",
    "            # Print unique values for each characteristic to identify relevant rows\n",
    "            for i in range(clinical_data.shape[1]):\n",
    "                unique_values = clinical_data[i].unique()\n",
    "                print(f\"\\nCharacteristic {i}:\")\n",
    "                print(f\"Unique values: {unique_values}\")\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on file extensions, determine if we likely have gene expression data\n",
    "is_gene_available = any('matrix' in f.lower() for f in files)\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# These will be set based on our analysis of the clinical data\n",
    "trait_row = None  # No explicit lactose intolerance information available\n",
    "age_row = 3       # \"age (yrs): 49\"\n",
    "gender_row = 1    # \"sex (female=1, male=0): 1\"\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait value from the clinical data to binary format.\"\"\"\n",
    "    if pd.isna(value) or value is None:\n",
    "        return None\n",
    "    \n",
    "    value = str(value).lower()\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Conversion for lactose intolerance\n",
    "    if any(term in value for term in ['intolerant', 'positive', 'yes']):\n",
    "        return 1\n",
    "    elif any(term in value for term in ['tolerant', 'negative', 'no']):\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age value from the clinical data to a number.\"\"\"\n",
    "    if pd.isna(value) or value is None:\n",
    "        return None\n",
    "    \n",
    "    value = str(value)\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Extract numeric value\n",
    "    try:\n",
    "        # Try to extract numeric values\n",
    "        numbers = re.findall(r'\\d+', value)\n",
    "        if numbers:\n",
    "            return float(numbers[0])\n",
    "        else:\n",
    "            return None\n",
    "    except:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender value from the clinical data (female=0, male=1).\"\"\"\n",
    "    if pd.isna(value) or value is None:\n",
    "        return None\n",
    "    \n",
    "    value = str(value).lower()\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # In this dataset: 1 = female, 0 = male\n",
    "    if '1' in value:\n",
    "        return 0  # Female maps to 0\n",
    "    elif '0' in value:\n",
    "        return 1  # Male maps to 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# Print the identified rows\n",
    "print(f\"\\nIdentified trait_row: {trait_row}\")\n",
    "print(f\"Identified age_row: {age_row}\")\n",
    "print(f\"Identified gender_row: {gender_row}\")\n",
    "\n",
    "# 3. Save metadata\n",
    "# Conduct initial filtering and save cohort info\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",
    "# Extract clinical features if trait data is available\n",
    "if trait_row is not None and clinical_data is not None:\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 if age_row is not None else None,\n",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender if gender_row is not None else None\n",
    "    )\n",
    "    \n",
    "    # Preview the extracted features\n",
    "    preview = preview_df(selected_clinical_df)\n",
    "    print(\"\\nExtracted 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",
    "    selected_clinical_df.to_csv(out_clinical_data_file)\n",
    "    print(f\"\\nClinical data saved to: {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b16cba6c",
   "metadata": {},
   "source": [
    "### Step 4: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a7e0f489",
   "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",
    "# Add diagnostic code to check file content and structure\n",
    "print(\"Examining matrix file structure...\")\n",
    "with gzip.open(matrix_file, 'rt') as file:\n",
    "    table_marker_found = False\n",
    "    lines_read = 0\n",
    "    for i, line in enumerate(file):\n",
    "        lines_read += 1\n",
    "        if '!series_matrix_table_begin' in line:\n",
    "            table_marker_found = True\n",
    "            print(f\"Found table marker at line {i}\")\n",
    "            # Read a few lines after the marker to check data structure\n",
    "            next_lines = [next(file, \"\").strip() for _ in range(5)]\n",
    "            print(\"First few lines after marker:\")\n",
    "            for next_line in next_lines:\n",
    "                print(next_line)\n",
    "            break\n",
    "        if i < 10:  # Print first few lines to see file structure\n",
    "            print(f\"Line {i}: {line.strip()}\")\n",
    "        if i > 100:  # Don't read the entire file\n",
    "            break\n",
    "    \n",
    "    if not table_marker_found:\n",
    "        print(\"Table marker '!series_matrix_table_begin' not found in first 100 lines\")\n",
    "    print(f\"Total lines examined: {lines_read}\")\n",
    "\n",
    "# 2. Try extracting gene expression data from the matrix file again with better diagnostics\n",
    "try:\n",
    "    print(\"\\nAttempting to extract gene data from matrix file...\")\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    if gene_data.empty:\n",
    "        print(\"Extracted gene expression data is empty\")\n",
    "        is_gene_available = False\n",
    "    else:\n",
    "        print(f\"Successfully extracted gene data with {len(gene_data.index)} rows\")\n",
    "        print(\"First 20 gene IDs:\")\n",
    "        print(gene_data.index[:20])\n",
    "        is_gene_available = True\n",
    "except Exception as e:\n",
    "    print(f\"Error extracting gene data: {str(e)}\")\n",
    "    print(\"This dataset appears to have an empty or malformed gene expression matrix\")\n",
    "    is_gene_available = False\n",
    "\n",
    "print(f\"\\nGene expression data available: {is_gene_available}\")\n",
    "\n",
    "# If data extraction failed, try an alternative approach using pandas directly\n",
    "if not is_gene_available:\n",
    "    print(\"\\nTrying alternative approach to read gene expression data...\")\n",
    "    try:\n",
    "        with gzip.open(matrix_file, 'rt') as file:\n",
    "            # Skip lines until we find the marker\n",
    "            for line in file:\n",
    "                if '!series_matrix_table_begin' in line:\n",
    "                    break\n",
    "            \n",
    "            # Try to read the data directly with pandas\n",
    "            gene_data = pd.read_csv(file, sep='\\t', index_col=0)\n",
    "            \n",
    "            if not gene_data.empty:\n",
    "                print(f\"Successfully extracted gene data with alternative method: {gene_data.shape}\")\n",
    "                print(\"First 20 gene IDs:\")\n",
    "                print(gene_data.index[:20])\n",
    "                is_gene_available = True\n",
    "            else:\n",
    "                print(\"Alternative extraction method also produced empty data\")\n",
    "    except Exception as e:\n",
    "        print(f\"Alternative extraction failed: {str(e)}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee6a6529",
   "metadata": {},
   "source": [
    "### Step 5: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0a4517b0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Examining the gene identifiers in the gene expression data\n",
    "# The identifiers appear to be numerical IDs starting with \"16650...\" which are not standard human gene symbols\n",
    "# These appear to be Illumina BeadArray probe IDs which need to be mapped to gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "81c2ff58",
   "metadata": {},
   "source": [
    "### Step 6: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ae82872a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Extract gene annotation data from the SOFT file\n",
    "print(\"Extracting gene annotation data from SOFT file...\")\n",
    "try:\n",
    "    # Use the library function to extract gene annotation\n",
    "    gene_annotation = get_gene_annotation(soft_file)\n",
    "    print(f\"Successfully extracted gene annotation data with {len(gene_annotation.index)} rows\")\n",
    "    \n",
    "    # Preview the annotation DataFrame\n",
    "    print(\"\\nGene annotation preview (first few rows):\")\n",
    "    print(preview_df(gene_annotation))\n",
    "    \n",
    "    # Show column names to help identify which columns we need for mapping\n",
    "    print(\"\\nColumn names in gene annotation data:\")\n",
    "    print(gene_annotation.columns.tolist())\n",
    "    \n",
    "    # Check for relevant mapping columns\n",
    "    if 'GB_ACC' in gene_annotation.columns:\n",
    "        print(\"\\nThe dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\")\n",
    "        # Count non-null values in GB_ACC column\n",
    "        non_null_count = gene_annotation['GB_ACC'].count()\n",
    "        print(f\"Number of rows with GenBank accessions: {non_null_count} out of {len(gene_annotation)}\")\n",
    "    \n",
    "    if 'SPOT_ID' in gene_annotation.columns:\n",
    "        print(\"\\nThe dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\")\n",
    "        print(\"Example SPOT_ID format:\", gene_annotation['SPOT_ID'].iloc[0])\n",
    "    \n",
    "except Exception as e:\n",
    "    print(f\"Error processing gene annotation data: {e}\")\n",
    "    is_gene_available = False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "062491fd",
   "metadata": {},
   "source": [
    "### Step 7: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "be7911c3",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Reload the gene expression data\n",
    "print(\"Reloading gene expression data...\")\n",
    "gene_data = get_genetic_data(matrix_file)\n",
    "print(f\"Loaded gene expression data with {gene_data.shape[0]} rows (probes) and {gene_data.shape[1]} columns (samples)\")\n",
    "\n",
    "# 2. Examine the gene expression data and annotation data for ID compatibility\n",
    "print(\"\\nDiagnosing gene ID mapping issue...\")\n",
    "\n",
    "# Check the first few IDs in both datasets\n",
    "gene_expr_ids = gene_data.index[:5].tolist()\n",
    "annot_ids = gene_annotation['ID'][:5].tolist()\n",
    "\n",
    "print(f\"Gene expression data IDs (first 5): {gene_expr_ids}\")\n",
    "print(f\"Annotation data IDs (first 5): {annot_ids}\")\n",
    "\n",
    "# Check for overlap between the ID sets\n",
    "gene_expr_id_set = set(gene_data.index)\n",
    "annot_id_set = set(gene_annotation['ID'].astype(str))\n",
    "overlap_count = len(gene_expr_id_set.intersection(annot_id_set))\n",
    "\n",
    "print(f\"\\nOverlap between gene expression and annotation IDs: {overlap_count} IDs\")\n",
    "print(f\"Total IDs in gene expression data: {len(gene_expr_id_set)}\")\n",
    "print(f\"Total IDs in annotation data: {len(annot_id_set)}\")\n",
    "\n",
    "# 3. Create a mapping dataframe with ID and extracted gene symbols\n",
    "print(\"\\nCreating gene mapping...\")\n",
    "\n",
    "# Extract the ID column and gene_assignment column for mapping\n",
    "mapping_data = pd.DataFrame({'ID': gene_annotation['ID'].astype(str)})\n",
    "mapping_data['Gene'] = gene_annotation['gene_assignment'].apply(extract_human_gene_symbols)\n",
    "\n",
    "# Filter to keep only rows with valid gene symbols and matching IDs\n",
    "mapping_data = mapping_data[mapping_data['Gene'].apply(lambda x: len(x) > 0 if isinstance(x, list) else False)]\n",
    "mapping_data = mapping_data[mapping_data['ID'].isin(gene_data.index)]\n",
    "\n",
    "print(f\"Created filtered mapping with {len(mapping_data)} rows\")\n",
    "mapping_preview = mapping_data.head(10) if len(mapping_data) > 0 else \"No matches found\"\n",
    "print(\"Mapping preview:\")\n",
    "print(mapping_preview)\n",
    "\n",
    "# 4. Apply gene mapping to convert probe data to gene expression data\n",
    "if len(mapping_data) > 0:\n",
    "    print(\"\\nApplying gene mapping to convert probe data to gene expression data...\")\n",
    "    gene_data = apply_gene_mapping(gene_data, mapping_data)\n",
    "    print(f\"Converted gene expression data: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
    "    \n",
    "    # 5. Normalize gene symbols\n",
    "    if gene_data.shape[0] > 0:\n",
    "        print(\"\\nNormalizing gene symbols...\")\n",
    "        gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "        print(f\"After normalization: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
    "        print(\"First few normalized gene symbols:\")\n",
    "        print(gene_data.index[:10].tolist())\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\"\\nGene expression data saved to: {out_gene_data_file}\")\n",
    "    else:\n",
    "        print(\"\\nNo gene symbols were mapped from the probes. Cannot save empty gene expression data.\")\n",
    "else:\n",
    "    print(\"\\nWARNING: Could not create a valid gene mapping. Gene expression data will remain as probe IDs.\")\n",
    "    # In this case, we can still save the probe-level data as is, labeling it as unmapped\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\"\\nUnmapped probe data saved to: {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "919d5547",
   "metadata": {},
   "source": [
    "### Step 8: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "486adff8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Reload the gene expression data\n",
    "print(\"Reloading gene expression data...\")\n",
    "gene_data = get_genetic_data(matrix_file)\n",
    "print(f\"Loaded gene expression data with {gene_data.shape[0]} rows (probes) and {gene_data.shape[1]} columns (samples)\")\n",
    "\n",
    "# 2. Re-extract gene annotation data\n",
    "print(\"\\nRe-extracting gene annotation data...\")\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "print(f\"Loaded gene annotation data with {gene_annotation.shape[0]} rows\")\n",
    "\n",
    "# 3. Examine the gene expression data and annotation data for ID compatibility\n",
    "print(\"\\nDiagnosing gene ID mapping issue...\")\n",
    "\n",
    "# Check the first few IDs in both datasets\n",
    "gene_expr_ids = gene_data.index[:5].tolist()\n",
    "annot_ids = gene_annotation['ID'][:5].tolist()\n",
    "\n",
    "print(f\"Gene expression data IDs (first 5): {gene_expr_ids}\")\n",
    "print(f\"Annotation data IDs (first 5): {annot_ids}\")\n",
    "\n",
    "# Check for overlap between the ID sets\n",
    "gene_expr_id_set = set(gene_data.index)\n",
    "annot_id_set = set(gene_annotation['ID'].astype(str))\n",
    "overlap_count = len(gene_expr_id_set.intersection(annot_id_set))\n",
    "\n",
    "print(f\"\\nOverlap between gene expression and annotation IDs: {overlap_count} IDs\")\n",
    "\n",
    "# 4. Create a mapping dataframe using the 'ID' and 'gene_assignment' columns\n",
    "print(\"\\nCreating gene mapping...\")\n",
    "\n",
    "# Extract the ID column and gene_assignment column for mapping\n",
    "mapping_data = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='gene_assignment')\n",
    "print(f\"Created mapping with {len(mapping_data)} rows\")\n",
    "\n",
    "# Filter to keep only rows with matching IDs in the gene expression data\n",
    "mapping_data = mapping_data[mapping_data['ID'].isin(gene_data.index)]\n",
    "print(f\"Filtered mapping to {len(mapping_data)} rows with matching IDs in gene expression data\")\n",
    "\n",
    "# Preview the mapping\n",
    "mapping_preview = mapping_data.head(5)\n",
    "print(\"Mapping preview:\")\n",
    "print(mapping_preview)\n",
    "\n",
    "# 5. Apply gene mapping to convert probe data to gene expression data\n",
    "print(\"\\nApplying gene mapping to convert probe data to gene expression data...\")\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_data)\n",
    "print(f\"Converted gene expression data: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
    "\n",
    "# 6. Normalize gene symbols\n",
    "print(\"\\nNormalizing gene symbols...\")\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"After normalization: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
    "print(\"First few normalized gene symbols:\")\n",
    "print(gene_data.index[:10].tolist())\n",
    "\n",
    "# 7. 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\"\\nGene expression data saved to: {out_gene_data_file}\")"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}