File size: 29,463 Bytes
e4183cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "d963c554",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:04:19.845294Z",
     "iopub.status.busy": "2025-03-25T08:04:19.845111Z",
     "iopub.status.idle": "2025-03-25T08:04:20.014253Z",
     "shell.execute_reply": "2025-03-25T08:04:20.013763Z"
    }
   },
   "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 = \"Endometriosis\"\n",
    "cohort = \"GSE75427\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Endometriosis\"\n",
    "in_cohort_dir = \"../../input/GEO/Endometriosis/GSE75427\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Endometriosis/GSE75427.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Endometriosis/gene_data/GSE75427.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Endometriosis/clinical_data/GSE75427.csv\"\n",
    "json_path = \"../../output/preprocess/Endometriosis/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6d47b385",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "e6aa32fa",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:04:20.015875Z",
     "iopub.status.busy": "2025-03-25T08:04:20.015719Z",
     "iopub.status.idle": "2025-03-25T08:04:20.089645Z",
     "shell.execute_reply": "2025-03-25T08:04:20.089336Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Expression profiles in decidualized and non-decidualized endometriotic cyst stromal cells (ECSCs) and normal endometrial stromal cells (NESCs)\"\n",
      "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n",
      "!Series_overall_design\t\"Refer to individual Series\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['cell type: endometriotic cyst stromal cells'], 1: ['gender: Female'], 2: ['age: 34y', 'age: 42y', 'age: 30y', 'age: 28y'], 3: ['treatment: 12d 10% charcoal-stripped heat-inactivated FBS', 'treatment: 12d dibutyryl-cAMP and dienogest']}\n"
     ]
    }
   ],
   "source": [
    "from tools.preprocess import *\n",
    "# 1. Identify the paths to the SOFT file and the matrix file\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
    "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
    "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
    "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
    "\n",
    "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
    "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
    "\n",
    "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
    "print(\"Background Information:\")\n",
    "print(background_info)\n",
    "print(\"Sample Characteristics Dictionary:\")\n",
    "print(sample_characteristics_dict)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2dd6c053",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "28115b07",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:04:20.090749Z",
     "iopub.status.busy": "2025-03-25T08:04:20.090638Z",
     "iopub.status.idle": "2025-03-25T08:04:20.098704Z",
     "shell.execute_reply": "2025-03-25T08:04:20.098408Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical Data Preview:\n",
      "{'GSM1954898': [1.0, 34.0], 'GSM1954899': [1.0, 42.0], 'GSM1954900': [1.0, 30.0], 'GSM1954901': [1.0, 28.0], 'GSM1954902': [1.0, 34.0], 'GSM1954903': [1.0, 42.0], 'GSM1954904': [1.0, 30.0], 'GSM1954905': [1.0, 28.0]}\n",
      "Clinical data saved to ../../output/preprocess/Endometriosis/clinical_data/GSE75427.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Based on the title mentioning \"Expression profiles\", this dataset likely contains gene expression data\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# For trait (Endometriosis), we can see \"cell type: proliferative phase normal endometrium\" in row 0\n",
    "# Row 0 likely distinguishes between normal and endometriotic cells\n",
    "trait_row = 0\n",
    "\n",
    "# For gender, we see \"gender: Female\" in row 1, but it appears to be constant (only Female)\n",
    "# Since there's only one unique value, we consider it not available\n",
    "gender_row = None\n",
    "\n",
    "# For age, we see \"age: 37y\", \"age: 47y\", etc. in row 2\n",
    "age_row = 2\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert cell type to binary where 1 indicates endometriotic cells and 0 indicates normal cells.\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Based on the title, we're comparing normal endometrial stromal cells (NESCs)\n",
    "    # vs endometriotic cyst stromal cells (ECSCs)\n",
    "    if 'normal' in value.lower():\n",
    "        return 0  # Normal cells\n",
    "    elif 'endometrio' in value.lower():\n",
    "        return 1  # Endometriotic cells\n",
    "    else:\n",
    "        return None  # Unknown\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age to continuous numeric value.\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Extract numeric age, typically formatted as \"XXy\" (XX years)\n",
    "    if 'y' in value:\n",
    "        try:\n",
    "            age = int(value.replace('y', '').strip())\n",
    "            return age\n",
    "        except ValueError:\n",
    "            pass\n",
    "    \n",
    "    return None  # If conversion fails\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"\n",
    "    Convert gender to binary (0 for female, 1 for male).\n",
    "    Not used in this dataset as gender is constant.\n",
    "    \"\"\"\n",
    "    # This function is included for completeness but not used since gender_row = None\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip().lower()\n",
    "    \n",
    "    if 'female' in value:\n",
    "        return 0\n",
    "    elif 'male' in value:\n",
    "        return 1\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",
    "# Validate and save cohort info (initial filtering)\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",
    "    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",
    "    preview = preview_df(clinical_df)\n",
    "    print(\"Clinical Data 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_df.to_csv(out_clinical_data_file, index=True)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b7f4352b",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "cd1e5a9d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:04:20.099787Z",
     "iopub.status.busy": "2025-03-25T08:04:20.099678Z",
     "iopub.status.idle": "2025-03-25T08:04:20.148945Z",
     "shell.execute_reply": "2025-03-25T08:04:20.148572Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found data marker at line 63\n",
      "Header line: \"ID_REF\"\t\"GSM1954898\"\t\"GSM1954899\"\t\"GSM1954900\"\t\"GSM1954901\"\t\"GSM1954902\"\t\"GSM1954903\"\t\"GSM1954904\"\t\"GSM1954905\"\n",
      "First data line: \"A_23_P100001\"\t354.3793375\t172.500875\t58.17458\t89.16528875\t1994.738375\t146.5653413\t39.38974125\t28.5603025\n",
      "Index(['A_23_P100001', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074',\n",
      "       'A_23_P100127', 'A_23_P100141', 'A_23_P100189', 'A_23_P100196',\n",
      "       'A_23_P100203', 'A_23_P100220', 'A_23_P100240', 'A_23_P10025',\n",
      "       'A_23_P100292', 'A_23_P100315', 'A_23_P100326', 'A_23_P100344',\n",
      "       'A_23_P100355', 'A_23_P100386', 'A_23_P100392', 'A_23_P100420'],\n",
      "      dtype='object', name='ID')\n"
     ]
    }
   ],
   "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": "4a055de0",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "67c606ab",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:04:20.150197Z",
     "iopub.status.busy": "2025-03-25T08:04:20.150088Z",
     "iopub.status.idle": "2025-03-25T08:04:20.151919Z",
     "shell.execute_reply": "2025-03-25T08:04:20.151628Z"
    }
   },
   "outputs": [],
   "source": [
    "# These identifiers don't appear to be standard human gene symbols\n",
    "# They have a format like \"A_19_P00315452\" which looks like probe IDs from a microarray platform\n",
    "# These will need to be mapped to standard gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b8c9b575",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "24177971",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:04:20.153289Z",
     "iopub.status.busy": "2025-03-25T08:04:20.153177Z",
     "iopub.status.idle": "2025-03-25T08:04:21.890283Z",
     "shell.execute_reply": "2025-03-25T08:04:21.889891Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107', '(+)E1A_r60_a135'], 'SPOT_ID': ['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107', '(+)E1A_r60_a135'], 'CONTROL_TYPE': ['pos', 'pos', 'pos', 'pos', 'pos'], 'REFSEQ': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan], 'GENE': [nan, nan, nan, nan, nan], 'GENE_SYMBOL': [nan, nan, nan, nan, nan], 'GENE_NAME': [nan, nan, nan, nan, nan], 'UNIGENE_ID': [nan, nan, nan, nan, nan], 'ENSEMBL_ID': [nan, nan, nan, nan, nan], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': [nan, nan, nan, nan, nan], 'CHROMOSOMAL_LOCATION': [nan, nan, nan, nan, nan], 'CYTOBAND': [nan, nan, nan, nan, nan], 'DESCRIPTION': [nan, nan, nan, nan, nan], 'GO_ID': [nan, nan, nan, nan, nan], 'SEQUENCE': [nan, nan, nan, nan, nan]}\n"
     ]
    }
   ],
   "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. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
    "print(\"Gene annotation preview:\")\n",
    "print(preview_df(gene_annotation))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b59ce36e",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "ac5ebb30",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:04:21.891804Z",
     "iopub.status.busy": "2025-03-25T08:04:21.891669Z",
     "iopub.status.idle": "2025-03-25T08:04:22.645925Z",
     "shell.execute_reply": "2025-03-25T08:04:22.645555Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene IDs in gene expression data (first 5):\n",
      "Index(['A_23_P100001', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074',\n",
      "       'A_23_P100127'],\n",
      "      dtype='object', name='ID')\n",
      "\n",
      "Further examination of gene annotation (10 more rows):\n",
      "              ID GENE_SYMBOL\n",
      "10     (-)3xSLv1         NaN\n",
      "11  A_23_P100001     FAM174B\n",
      "12  A_23_P100022        SV2B\n",
      "13  A_23_P100056      RBPMS2\n",
      "14  A_23_P100074        AVEN\n",
      "15  A_23_P100127       CASC5\n",
      "16  A_23_P100141        UNKL\n",
      "17  A_23_P100189        PRM1\n",
      "18  A_23_P100196       USP10\n",
      "19  A_23_P100203       HSBP1\n",
      "\n",
      "Sample rows with gene symbols (if any):\n",
      "              ID GENE_SYMBOL\n",
      "11  A_23_P100001     FAM174B\n",
      "12  A_23_P100022        SV2B\n",
      "13  A_23_P100056      RBPMS2\n",
      "14  A_23_P100074        AVEN\n",
      "15  A_23_P100127       CASC5\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Rows with matching ID pattern:\n",
      "              ID GENE_SYMBOL\n",
      "11  A_23_P100001     FAM174B\n",
      "12  A_23_P100022        SV2B\n",
      "13  A_23_P100056      RBPMS2\n",
      "14  A_23_P100074        AVEN\n",
      "15  A_23_P100127       CASC5\n",
      "\n",
      "Rows with both ID and GENE_SYMBOL:\n",
      "              ID GENE_SYMBOL\n",
      "11  A_23_P100001     FAM174B\n",
      "12  A_23_P100022        SV2B\n",
      "13  A_23_P100056      RBPMS2\n",
      "14  A_23_P100074        AVEN\n",
      "15  A_23_P100127       CASC5\n",
      "\n",
      "Rows with both ID and GENE:\n",
      "              ID    GENE\n",
      "11  A_23_P100001  400451\n",
      "12  A_23_P100022    9899\n",
      "13  A_23_P100056  348093\n",
      "14  A_23_P100074   57099\n",
      "15  A_23_P100127   57082\n",
      "\n",
      "Rows with both ID and GENE_NAME:\n",
      "              ID                                      GENE_NAME\n",
      "11  A_23_P100001  family with sequence similarity 174, member B\n",
      "12  A_23_P100022               synaptic vesicle glycoprotein 2B\n",
      "13  A_23_P100056   RNA binding protein with multiple splicing 2\n",
      "14  A_23_P100074        apoptosis, caspase activation inhibitor\n",
      "15  A_23_P100127              cancer susceptibility candidate 5\n",
      "\n",
      "Rows with both ID and REFSEQ:\n",
      "              ID     REFSEQ\n",
      "11  A_23_P100001  NM_207446\n",
      "12  A_23_P100022  NM_014848\n",
      "13  A_23_P100056  NM_194272\n",
      "14  A_23_P100074  NM_020371\n",
      "15  A_23_P100127  NM_170589\n",
      "\n",
      "Rows with both ID and GB_ACC:\n",
      "              ID     GB_ACC\n",
      "11  A_23_P100001  NM_207446\n",
      "12  A_23_P100022  NM_014848\n",
      "13  A_23_P100056  NM_194272\n",
      "14  A_23_P100074  NM_020371\n",
      "15  A_23_P100127  NM_170589\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene mapping dataframe (first 5 rows):\n",
      "              ID     Gene\n",
      "11  A_23_P100001  FAM174B\n",
      "12  A_23_P100022     SV2B\n",
      "13  A_23_P100056   RBPMS2\n",
      "14  A_23_P100074     AVEN\n",
      "15  A_23_P100127    CASC5\n",
      "\n",
      "Gene expression data after mapping (first 5 genes):\n",
      "           GSM1954898   GSM1954899   GSM1954900    GSM1954901   GSM1954902  \\\n",
      "Gene                                                                         \n",
      "A1BG      3028.378695  2731.904201  3157.886390   3028.031645  3820.889868   \n",
      "A1BG-AS1   852.177600   601.155425   758.254475   1017.400850   803.633850   \n",
      "A1CF        13.638512    10.773817    15.022629     10.245584    21.209031   \n",
      "A2LD1     1528.978615  1301.985750  3653.101250   2065.590500  1868.458601   \n",
      "A2M       1702.062389  4474.020852  3434.653770  13126.539044   213.549137   \n",
      "\n",
      "           GSM1954903   GSM1954904   GSM1954905  \n",
      "Gene                                             \n",
      "A1BG      3227.197977  3969.369038  5763.236649  \n",
      "A1BG-AS1   550.132250   894.482050  1676.084700  \n",
      "A1CF        10.897716     9.151911    12.580970  \n",
      "A2LD1     1256.928650  2231.617550  1938.389575  \n",
      "A2M        406.783548  1552.944676  5180.086498  \n",
      "\n",
      "Number of genes after mapping: 19818\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to ../../output/preprocess/Endometriosis/gene_data/GSE75427.csv\n"
     ]
    }
   ],
   "source": [
    "# Examining the structure of gene IDs in both datasets\n",
    "print(\"Gene IDs in gene expression data (first 5):\")\n",
    "print(gene_data.index[:5])\n",
    "\n",
    "# Let's look at more rows of the gene annotation to find the matching columns\n",
    "print(\"\\nFurther examination of gene annotation (10 more rows):\")\n",
    "print(gene_annotation.iloc[10:20][['ID', 'GENE_SYMBOL']].head(10))\n",
    "\n",
    "# Try to find any rows with non-null gene symbols\n",
    "print(\"\\nSample rows with gene symbols (if any):\")\n",
    "symbol_sample = gene_annotation[gene_annotation['GENE_SYMBOL'].notna()].head(5)\n",
    "print(symbol_sample[['ID', 'GENE_SYMBOL']])\n",
    "\n",
    "# Check which ID format in the annotation matches our expression data\n",
    "# Since the standard gene_data IDs look like A_19_P00315452, we need to find the matching pattern\n",
    "import re\n",
    "\n",
    "# Find the first few rows where ID matches our expression data pattern\n",
    "pattern = r'A_\\d+_P\\d+'\n",
    "matching_rows = gene_annotation[gene_annotation['ID'].str.contains(pattern, na=False)].head(5)\n",
    "print(\"\\nRows with matching ID pattern:\")\n",
    "print(matching_rows[['ID', 'GENE_SYMBOL']])\n",
    "\n",
    "# For probe-gene mapping, we need to determine which columns to use\n",
    "# Based on the column names, 'ID' should contain probe IDs and 'GENE_SYMBOL' should contain gene symbols\n",
    "# Let's confirm if there are any rows with both values\n",
    "valid_mapping_rows = gene_annotation[(gene_annotation['ID'].notna()) & \n",
    "                                    (gene_annotation['GENE_SYMBOL'].notna())].head(5)\n",
    "print(\"\\nRows with both ID and GENE_SYMBOL:\")\n",
    "print(valid_mapping_rows[['ID', 'GENE_SYMBOL']])\n",
    "\n",
    "# If GENE_SYMBOL is mostly empty, check other potential gene identifier columns\n",
    "potential_gene_cols = ['GENE', 'GENE_NAME', 'REFSEQ', 'GB_ACC']\n",
    "for col in potential_gene_cols:\n",
    "    valid_rows = gene_annotation[(gene_annotation['ID'].notna()) & \n",
    "                                (gene_annotation[col].notna())].head(5)\n",
    "    if not valid_rows.empty:\n",
    "        print(f\"\\nRows with both ID and {col}:\")\n",
    "        print(valid_rows[['ID', col]])\n",
    "\n",
    "# Based on the above analysis, create the mapping dataframe\n",
    "# Assuming we've identified the correct columns\n",
    "prob_col = 'ID'  # Column with probe IDs\n",
    "gene_col = 'GENE_SYMBOL'  # Column with gene symbols (adjust if needed based on results)\n",
    "\n",
    "# Get the mapping dataframe\n",
    "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n",
    "print(\"\\nGene mapping dataframe (first 5 rows):\")\n",
    "print(mapping_df.head())\n",
    "\n",
    "# Convert probe-level measurements to gene expression data\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
    "print(\"\\nGene expression data after mapping (first 5 genes):\")\n",
    "print(gene_data.head())\n",
    "\n",
    "# If the mapping has very few valid entries (or none), we might need to try an alternative approach\n",
    "# Check the mapping statistics\n",
    "mapped_count = len(gene_data)\n",
    "print(f\"\\nNumber of genes after mapping: {mapped_count}\")\n",
    "\n",
    "# If the mapping resulted in very few genes, try an alternative column\n",
    "if mapped_count < 100:\n",
    "    print(\"Poor mapping results. Trying alternative gene column...\")\n",
    "    # Try using 'GENE' instead of 'GENE_SYMBOL'\n",
    "    gene_col_alt = 'GENE'\n",
    "    mapping_df_alt = get_gene_mapping(gene_annotation, prob_col, gene_col_alt)\n",
    "    gene_data = apply_gene_mapping(gene_data, mapping_df_alt)\n",
    "    print(f\"Number of genes after alternative mapping: {len(gene_data)}\")\n",
    "\n",
    "# Save the gene expression data to a file\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": "ead2aff8",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "1cdb52dd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:04:22.647311Z",
     "iopub.status.busy": "2025-03-25T08:04:22.647191Z",
     "iopub.status.idle": "2025-03-25T08:04:28.683830Z",
     "shell.execute_reply": "2025-03-25T08:04:28.683467Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Endometriosis/gene_data/GSE75427.csv\n",
      "Clinical data saved to ../../output/preprocess/Endometriosis/clinical_data/GSE75427.csv\n",
      "Linked data shape: (8, 19449)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Quartiles for 'Endometriosis':\n",
      "  25%: 1.0\n",
      "  50% (Median): 1.0\n",
      "  75%: 1.0\n",
      "Min: 1.0\n",
      "Max: 1.0\n",
      "The distribution of the feature 'Endometriosis' in this dataset is severely biased.\n",
      "\n",
      "Quartiles for 'Age':\n",
      "  25%: 29.5\n",
      "  50% (Median): 32.0\n",
      "  75%: 36.0\n",
      "Min: 28.0\n",
      "Max: 42.0\n",
      "The distribution of the feature 'Age' in this dataset is fine.\n",
      "\n",
      "Data was determined to be unusable and was not saved\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.\n",
    "normalized_gene_data = normalize_gene_symbols_in_index(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",
    "# Create clinical features directly from clinical_data using the conversion functions defined earlier\n",
    "clinical_features_df = geo_select_clinical_features(\n",
    "    clinical_data, \n",
    "    trait=trait, \n",
    "    trait_row=trait_row, \n",
    "    convert_trait=convert_trait,\n",
    "    age_row=age_row,\n",
    "    convert_age=convert_age,\n",
    "    gender_row=gender_row,\n",
    "    convert_gender=convert_gender\n",
    ")\n",
    "\n",
    "# Save the clinical data\n",
    "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "clinical_features_df.to_csv(out_clinical_data_file)\n",
    "print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "\n",
    "# Now link the clinical and genetic data\n",
    "linked_data = geo_link_clinical_genetic_data(clinical_features_df, normalized_gene_data)\n",
    "print(\"Linked data shape:\", linked_data.shape)\n",
    "\n",
    "# Handle missing values in the linked data\n",
    "linked_data = handle_missing_values(linked_data, trait)\n",
    "\n",
    "# 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.\n",
    "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "\n",
    "# 5. Conduct quality check and save the cohort information.\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_trait_biased, \n",
    "    df=unbiased_linked_data,\n",
    "    note=\"Dataset contains gene expression from monocytes of rheumatoid arthritis patients, with osteoporosis status included in comorbidity information.\"\n",
    ")\n",
    "\n",
    "# 6. If the linked data is usable, save it as a CSV file to 'out_data_file'.\n",
    "if is_usable:\n",
    "    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "    unbiased_linked_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 and was not saved\")"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}