File size: 32,415 Bytes
53eb596
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "ce129254",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:02:20.747404Z",
     "iopub.status.busy": "2025-03-25T08:02:20.747162Z",
     "iopub.status.idle": "2025-03-25T08:02:20.910651Z",
     "shell.execute_reply": "2025-03-25T08:02:20.910316Z"
    }
   },
   "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 = \"GSE120103\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Endometriosis\"\n",
    "in_cohort_dir = \"../../input/GEO/Endometriosis/GSE120103\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Endometriosis/GSE120103.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Endometriosis/gene_data/GSE120103.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Endometriosis/clinical_data/GSE120103.csv\"\n",
    "json_path = \"../../output/preprocess/Endometriosis/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9f7c01bd",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "749cbfec",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:02:20.911995Z",
     "iopub.status.busy": "2025-03-25T08:02:20.911863Z",
     "iopub.status.idle": "2025-03-25T08:02:21.011407Z",
     "shell.execute_reply": "2025-03-25T08:02:21.011117Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Homo sapiens whole genome expression microarray of endometrium obtained from fertile and Infertile women with stage IV ovarian endometriosis and without endometriosis\"\n",
      "!Series_summary\t\"The hypothesis that male michrochimerism in eutopic endometrium is a factor for endometriosis, as indicated by indirect evidence was examined in endometrial samples from control (Group 1) and stage IV ovarian endometriosis (Group 2), either fertile (Group 1A and 2A) or Infertile (Group 1B and 2B) pateints.\"\n",
      "!Series_summary\t\"6 coding and 10 non-coding genes showed bi-modal pattern of expression characterised by low expression in samples obtained from fertile patients and high expressions in infertile patients. Several coding and non-coding MSY-linked genes displayed michrochimerism in form of presence of their respective DNA inserts along with their microarray-detectable expression in endometrium irrespective of fertility history and disease.\"\n",
      "!Series_overall_design\t\"Whole genome expression arrays of endometrial total RNA obtained from  endometrium of women without endometriosis (Group 1) and with stage IV ovarian endometriosis (Group 2), either fertile (Group 1A and 2A) or Infertile (Group 1B and 2B).\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['gender: Female'], 1: ['sample group: Disease free Endometrium of fertile women', 'sample group: Endometrium  from Stage IV Ovarian Endometriosis of fertile women', 'sample group: Disease free Endometrium of Infertile women', 'sample group: Endometrium  from Stage IV Ovarian Endometriosis of Infertile women'], 2: ['tissue: Endometrium']}\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": "695fdc74",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "4640f563",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:02:21.012543Z",
     "iopub.status.busy": "2025-03-25T08:02:21.012442Z",
     "iopub.status.idle": "2025-03-25T08:02:21.019802Z",
     "shell.execute_reply": "2025-03-25T08:02:21.019523Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical Features Preview:\n",
      "{0: [0.0], 1: [1.0], 2: [0.0], 3: [1.0]}\n",
      "Clinical features saved to ../../output/preprocess/Endometriosis/clinical_data/GSE120103.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Based on the series description, this appears to be a whole genome expression microarray dataset,\n",
    "# so we can confidently set this to True\n",
    "is_gene_available = True\n",
    "\n",
    "# 2.1 Data Availability\n",
    "# For the trait (endometriosis), the relevant key is 1, which indicates sample group information\n",
    "trait_row = 1  \n",
    "\n",
    "# For age, there's no information available in the sample characteristics\n",
    "age_row = None\n",
    "\n",
    "# For gender, we can see that gender information is available at key 0,\n",
    "# but it shows only one value \"Female\", so it's a constant feature and should be considered unavailable\n",
    "gender_row = None  \n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert sample group to binary values for endometriosis trait.\"\"\"\n",
    "    if pd.isna(value) or value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon if present\n",
    "    if isinstance(value, str) and ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Based on the values, we need to determine who has endometriosis\n",
    "    if \"Stage IV Ovarian Endometriosis\" in value:\n",
    "        return 1  # Has endometriosis\n",
    "    elif \"Disease free Endometrium\" in value:\n",
    "        return 0  # Does not have endometriosis\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age to continuous values.\"\"\"\n",
    "    # This function is included for completeness but won't be used as age data is not available\n",
    "    if pd.isna(value) or value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon if present\n",
    "    if isinstance(value, str) and ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    try:\n",
    "        return float(value)\n",
    "    except:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender to binary values.\"\"\"\n",
    "    # This function is included for completeness but won't be used as gender data is not available\n",
    "    if pd.isna(value) or value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon if present\n",
    "    if isinstance(value, str) and ':' in value:\n",
    "        value = value.split(':', 1)[1].strip().lower()\n",
    "    \n",
    "    if value == \"female\":\n",
    "        return 0\n",
    "    elif value == \"male\":\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine if trait data is available based on whether trait_row is None\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Call the validation function\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. Clinical Feature Extraction\n",
    "if trait_row is not None:\n",
    "    # Create a proper DataFrame for the clinical data\n",
    "    # Using a more appropriate structure for geo_select_clinical_features\n",
    "    \n",
    "    # Initialize sample characteristics dictionary with proper structure\n",
    "    sample_characteristics = {\n",
    "        0: ['gender: Female'], \n",
    "        1: ['sample group: Disease free Endometrium of fertile women', \n",
    "            'sample group: Endometrium  from Stage IV Ovarian Endometriosis of fertile women', \n",
    "            'sample group: Disease free Endometrium of Infertile women', \n",
    "            'sample group: Endometrium  from Stage IV Ovarian Endometriosis of Infertile women'], \n",
    "        2: ['tissue: Endometrium']\n",
    "    }\n",
    "    \n",
    "    # Create a clinical DataFrame with appropriate format for geo_select_clinical_features\n",
    "    # Each row represents one characteristic (like trait, gender)\n",
    "    clinical_data_dict = {}\n",
    "    for key, values in sample_characteristics.items():\n",
    "        clinical_data_dict[key] = values\n",
    "    \n",
    "    clinical_data = pd.DataFrame.from_dict(clinical_data_dict, orient='index')\n",
    "    \n",
    "    # Extract clinical features\n",
    "    selected_clinical_df = geo_select_clinical_features(\n",
    "        clinical_df=clinical_data,\n",
    "        trait=trait,\n",
    "        trait_row=trait_row,\n",
    "        convert_trait=convert_trait,\n",
    "        age_row=age_row,\n",
    "        convert_age=convert_age,\n",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender\n",
    "    )\n",
    "    \n",
    "    # Preview the results\n",
    "    preview = preview_df(selected_clinical_df)\n",
    "    print(\"Clinical Features Preview:\")\n",
    "    print(preview)\n",
    "    \n",
    "    # Create directory if it doesn't exist\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    \n",
    "    # Save the clinical features to CSV\n",
    "    selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
    "    print(f\"Clinical features saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "da277219",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "55b727a6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:02:21.020819Z",
     "iopub.status.busy": "2025-03-25T08:02:21.020720Z",
     "iopub.status.idle": "2025-03-25T08:02:21.177972Z",
     "shell.execute_reply": "2025-03-25T08:02:21.177606Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found data marker at line 66\n",
      "Header line: \"ID_REF\"\t\"GSM3393491\"\t\"GSM3393492\"\t\"GSM3393493\"\t\"GSM3393494\"\t\"GSM3393495\"\t\"GSM3393496\"\t\"GSM3393497\"\t\"GSM3393498\"\t\"GSM3393499\"\t\"GSM3393500\"\t\"GSM3393501\"\t\"GSM3393502\"\t\"GSM3393503\"\t\"GSM3393504\"\t\"GSM3393505\"\t\"GSM3393506\"\t\"GSM3393507\"\t\"GSM3393508\"\t\"GSM3393509\"\t\"GSM3393510\"\t\"GSM3393511\"\t\"GSM3393512\"\t\"GSM3393513\"\t\"GSM3393514\"\t\"GSM3393515\"\t\"GSM3393516\"\t\"GSM3393517\"\t\"GSM3393518\"\t\"GSM3393519\"\t\"GSM3393520\"\t\"GSM3393521\"\t\"GSM3393522\"\t\"GSM3393523\"\t\"GSM3393524\"\t\"GSM3393525\"\t\"GSM3393526\"\n",
      "First data line: \"(+)E1A_r60_1\"\t0.2933545\t0.012980461\t-0.23412466\t-0.7159295\t-0.012980461\t-1.7718949\t-2.2321372\t-1.1389613\t0.4525237\t-1.8300767\t-2.9251266\t-2.3127236\t-1.1785226\t-2.9045892\t-0.2190404\t-1.5515742\t-2.569182\t-1.8102136\t14.862822\t14.86257\t14.874119\t14.430498\t14.441908\t14.338968\t14.85437\t-2.4582553\t-2.5016837\t-0.20707464\t0.17501879\t0.013408184\t0.5477576\t6.3862505\t5.2938547\t6.3140154\t0.4224906\t3.351428\n",
      "Index(['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107',\n",
      "       '(+)E1A_r60_a135', '(+)E1A_r60_a20', '(+)E1A_r60_a22', '(+)E1A_r60_a97',\n",
      "       '(+)E1A_r60_n11', '(+)E1A_r60_n9', '(+)eQC-39', '(+)eQC-40',\n",
      "       '(+)eQC-41', '(+)eQC-42', '(-)3xSLv1', 'A_23_P100001', 'A_23_P100011',\n",
      "       'A_23_P100022', 'A_23_P100056', 'A_23_P100074'],\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": "bfbf3528",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "e83e68a8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:02:21.179289Z",
     "iopub.status.busy": "2025-03-25T08:02:21.179175Z",
     "iopub.status.idle": "2025-03-25T08:02:21.181024Z",
     "shell.execute_reply": "2025-03-25T08:02:21.180741Z"
    }
   },
   "outputs": [],
   "source": [
    "# Review gene identifiers in the data\n",
    "# The identifiers such as 'A_23_P100001', 'A_23_P100011', etc. appear to be Agilent microarray probe IDs\n",
    "# rather than standard human gene symbols. These will need to be mapped to gene symbols.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5987223f",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "8222478f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:02:21.182453Z",
     "iopub.status.busy": "2025-03-25T08:02:21.182353Z",
     "iopub.status.idle": "2025-03-25T08:02:23.741908Z",
     "shell.execute_reply": "2025-03-25T08:02:23.741534Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074'], 'SPOT_ID': ['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074'], 'CONTROL_TYPE': ['FALSE', 'FALSE', 'FALSE', 'FALSE', 'FALSE'], 'REFSEQ': ['NM_207446', 'NM_005829', 'NM_014848', 'NM_194272', 'NM_020371'], 'GB_ACC': ['NM_207446', 'NM_005829', 'NM_014848', 'NM_194272', 'NM_020371'], 'GENE': [400451.0, 10239.0, 9899.0, 348093.0, 57099.0], 'GENE_SYMBOL': ['FAM174B', 'AP3S2', 'SV2B', 'RBPMS2', 'AVEN'], 'GENE_NAME': ['family with sequence similarity 174, member B', 'adaptor-related protein complex 3, sigma 2 subunit', 'synaptic vesicle glycoprotein 2B', 'RNA binding protein with multiple splicing 2', 'apoptosis, caspase activation inhibitor'], 'UNIGENE_ID': ['Hs.27373', 'Hs.632161', 'Hs.21754', 'Hs.436518', 'Hs.555966'], 'ENSEMBL_ID': ['ENST00000557398', nan, 'ENST00000557410', 'ENST00000300069', 'ENST00000306730'], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': ['ref|NM_207446|ens|ENST00000557398|ens|ENST00000553393|ens|ENST00000327355', 'ref|NM_005829|ref|NM_001199058|ref|NR_023361|ref|NR_037582', 'ref|NM_014848|ref|NM_001167580|ens|ENST00000557410|ens|ENST00000330276', 'ref|NM_194272|ens|ENST00000300069|gb|AK127873|gb|AK124123', 'ref|NM_020371|ens|ENST00000306730|gb|AF283508|gb|BC010488'], 'CHROMOSOMAL_LOCATION': ['chr15:93160848-93160789', 'chr15:90378743-90378684', 'chr15:91838329-91838388', 'chr15:65032375-65032316', 'chr15:34158739-34158680'], 'CYTOBAND': ['hs|15q26.1', 'hs|15q26.1', 'hs|15q26.1', 'hs|15q22.31', 'hs|15q14'], 'DESCRIPTION': ['Homo sapiens family with sequence similarity 174, member B (FAM174B), mRNA [NM_207446]', 'Homo sapiens adaptor-related protein complex 3, sigma 2 subunit (AP3S2), transcript variant 1, mRNA [NM_005829]', 'Homo sapiens synaptic vesicle glycoprotein 2B (SV2B), transcript variant 1, mRNA [NM_014848]', 'Homo sapiens RNA binding protein with multiple splicing 2 (RBPMS2), mRNA [NM_194272]', 'Homo sapiens apoptosis, caspase activation inhibitor (AVEN), mRNA [NM_020371]'], 'GO_ID': ['GO:0016020(membrane)|GO:0016021(integral to membrane)', 'GO:0005794(Golgi apparatus)|GO:0006886(intracellular protein transport)|GO:0008565(protein transporter activity)|GO:0016020(membrane)|GO:0016192(vesicle-mediated transport)|GO:0030117(membrane coat)|GO:0030659(cytoplasmic vesicle membrane)|GO:0031410(cytoplasmic vesicle)', 'GO:0001669(acrosomal vesicle)|GO:0006836(neurotransmitter transport)|GO:0016020(membrane)|GO:0016021(integral to membrane)|GO:0022857(transmembrane transporter activity)|GO:0030054(cell junction)|GO:0030672(synaptic vesicle membrane)|GO:0031410(cytoplasmic vesicle)|GO:0045202(synapse)', 'GO:0000166(nucleotide binding)|GO:0003676(nucleic acid binding)', 'GO:0005515(protein binding)|GO:0005622(intracellular)|GO:0005624(membrane fraction)|GO:0006915(apoptosis)|GO:0006916(anti-apoptosis)|GO:0012505(endomembrane system)|GO:0016020(membrane)'], 'SEQUENCE': ['ATCTCATGGAAAAGCTGGATTCCTCTGCCTTACGCAGAAACACCCGGGCTCCATCTGCCA', 'TCAAGTATTGGCCTGACATAGAGTCCTTAAGACAAGCAAAGACAAGCAAGGCAAGCACGT', 'ATGTCGGCTGTGGAGGGTTAAAGGGATGAGGCTTTCCTTTGTTTAGCAAATCTGTTCACA', 'CCCTGTCAGATAAGTTTAATGTTTAGTTTGAGGCATGAAGAAGAAAAGGGTTTCCATTCT', 'GACCAGCCAGTTTACAAGCATGTCTCAAGCTAGTGTGTTCCATTATGCTCACAGCAGTAA']}\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": "4a136139",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "3dbfd5c0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:02:23.743230Z",
     "iopub.status.busy": "2025-03-25T08:02:23.743110Z",
     "iopub.status.idle": "2025-03-25T08:02:23.882590Z",
     "shell.execute_reply": "2025-03-25T08:02:23.882218Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping preview:\n",
      "{'ID': ['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074'], 'Gene': ['FAM174B', 'AP3S2', 'SV2B', 'RBPMS2', 'AVEN']}\n",
      "Gene expression data shape after mapping: (17678, 36)\n",
      "First few gene symbols after mapping:\n",
      "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT',\n",
      "       'AAAS', 'AACS'],\n",
      "      dtype='object', name='Gene')\n",
      "Gene expression data preview:\n",
      "{'GSM3393491': [-1.3306704, -1.0435967, 1.993511226, 2.275426, 0.53070736], 'GSM3393492': [-1.4305425, -0.54736996, 0.54174758, 0.47634304, 0.3492117], 'GSM3393493': [-1.7391768, -0.5067458, 2.64482165, 0.9172963, -0.19257355], 'GSM3393494': [-0.65010595, 0.27574682, -1.99191613, 1.6102637, 0.24081898], 'GSM3393495': [-0.7661872, -1.1883221, 0.8087396800000001, 2.1443443, 0.3116703], 'GSM3393496': [0.43882227, -0.002605438, -1.50206663, -0.15116894, 0.49943542], 'GSM3393497': [0.25899267, -0.015143395, -2.4413662, -0.30618966, 0.19794655], 'GSM3393498': [0.39300776, 0.77118206, -0.94638018, -0.44590962, 0.24827003], 'GSM3393499': [0.40918016, 0.78752136, 0.5837469200000001, -0.38014424, 0.2881632], 'GSM3393500': [-0.019157887, 0.002605438, -1.46312666, 1.7641228, -0.04834938], 'GSM3393501': [0.21949339, 0.46449852, -1.9212579399999998, -0.15999234, 1.18081], 'GSM3393502': [0.3701806, 0.17487144, 1.37367252, -0.22474778, 0.9151268], 'GSM3393503': [-0.7208419, -0.92774963, 2.0723180599999997, 0.13323009, -0.206316], 'GSM3393504': [0.58674955, 0.53776836, -1.4177436, 0.08122432, 1.2010365], 'GSM3393505': [0.035662174, 0.5369997, -2.5815987600000003, 0.32511508, -0.13713264], 'GSM3393506': [-0.088758945, 0.6998739, -3.4623508, 0.3340863, 0.03494072], 'GSM3393507': [0.12691832, 0.64743805, -4.8875618, 0.29584873, 0.053635597], 'GSM3393508': [0.20600271, 0.60525227, -4.4621973, 0.31017768, 0.1822033], 'GSM3393509': [0.78590536, 0.572505, 1.02886964, -0.15118802, -0.075992584], 'GSM3393510': [0.84085274, 0.32155704, -2.510457, -0.07825482, -0.2025361], 'GSM3393511': [0.80198574, 0.03553486, -0.9755090000000002, -0.30321276, -0.13455915], 'GSM3393512': [0.1604619, -0.19307852, -0.27777509999999994, -0.17000067, 0.08755493], 'GSM3393513': [0.21704626, -0.098829746, -0.21317049999999993, -0.32561076, -0.03494072], 'GSM3393514': [0.33046913, -0.35986662, -2.1921574, -0.50407183, -0.14380455], 'GSM3393515': [0.9540601, 0.13577461, -2.5504317, 0.031509757, -0.17405319], 'GSM3393516': [-0.048018932, -0.2030735, -5.8310852, 1.41897, -0.20944023], 'GSM3393517': [0.019157887, -0.1952858, -6.7030306, 1.2529734, -0.2085123], 'GSM3393518': [-1.2392125, -0.46589327, 4.5362944999999995, -0.76398003, -0.58863544], 'GSM3393519': [-1.1698852, -0.41910315, 3.841381174, -0.86528695, -0.40317822], 'GSM3393520': [-1.0839481, -0.516871, 3.887827826, -0.9265362, -0.4452448], 'GSM3393521': [-1.0274839, -0.3784132, 4.25438308, -0.72910845, -0.50286007], 'GSM3393522': [-0.27486825, 1.7698548, 10.7768375, 1.1431161, 2.1987486], 'GSM3393523': [-1.4494941, 0.5952289, 4.7863519199999995, -0.031509757, -6.070035], 'GSM3393524': [-0.25296688, 1.7917562, 7.17940616, 1.1650175, -2.7111485], 'GSM3393525': [-1.8236032, -1.995471, -2.59862992, 1.7294978, 0.28830147], 'GSM3393526': [-0.32608938, -1.5909972, 12.264716, -2.2177358, 0.13134003]}\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the relevant columns from the gene annotation data\n",
    "# From the preview, we can see that 'ID' contains the probe identifiers (like A_23_P100001) \n",
    "# which match the gene expression data index, and 'GENE_SYMBOL' contains the gene symbols\n",
    "\n",
    "# 2. Get gene mapping dataframe by extracting the ID and GENE_SYMBOL columns\n",
    "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')\n",
    "\n",
    "# Print preview of the mapping dataframe\n",
    "print(\"Gene mapping preview:\")\n",
    "print(preview_df(mapping_df))\n",
    "\n",
    "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n",
    "# This handles the many-to-many relationship between probes and genes\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
    "\n",
    "# Print the shape of the resulting gene expression dataframe\n",
    "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n",
    "print(\"First few gene symbols after mapping:\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# Preview the gene expression data\n",
    "print(\"Gene expression data preview:\")\n",
    "print(preview_df(gene_data))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "90f67ed5",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "b65de96d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:02:23.884147Z",
     "iopub.status.busy": "2025-03-25T08:02:23.884039Z",
     "iopub.status.idle": "2025-03-25T08:02:24.340134Z",
     "shell.execute_reply": "2025-03-25T08:02:24.339788Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Endometriosis/gene_data/GSE120103.csv\n",
      "Reading previously saved clinical data\n",
      "Clinical data preview:\n",
      "     0    1    2    3\n",
      "0  0.0  1.0  0.0  1.0\n",
      "Transposed clinical features shape: (4, 1)\n",
      "Transposed clinical features columns: Index(['Endometriosis'], dtype='object')\n",
      "Linked data shape: (40, 17450)\n",
      "Linked data columns preview: Index(['Endometriosis', 'A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A4GALT',\n",
      "       'A4GNT', 'AAAS', 'AACS'],\n",
      "      dtype='object')\n",
      "Trait column 'Endometriosis' found in linked data\n",
      "Endometriosis\n",
      "0.0    2\n",
      "1.0    2\n",
      "Name: count, dtype: int64\n",
      "Linked data shape after cleaning: (0, 1)\n",
      "Quartiles for 'Endometriosis':\n",
      "  25%: nan\n",
      "  50% (Median): nan\n",
      "  75%: nan\n",
      "Min: nan\n",
      "Max: nan\n",
      "The distribution of the feature 'Endometriosis' in this dataset is fine.\n",
      "\n",
      "Abnormality detected in the cohort: GSE120103. Preprocessing failed.\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",
    "# 2. Read the clinical data that was saved earlier\n",
    "print(\"Reading previously saved clinical data\")\n",
    "# First check if the clinical data file exists\n",
    "if os.path.exists(out_clinical_data_file):\n",
    "    clinical_features_df = pd.read_csv(out_clinical_data_file)\n",
    "    print(\"Clinical data preview:\")\n",
    "    print(clinical_features_df.head())\n",
    "else:\n",
    "    # If file doesn't exist, extract clinical features again\n",
    "    print(\"Clinical data file not found, extracting clinical features again\")\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",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    clinical_features_df.to_csv(out_clinical_data_file)\n",
    "\n",
    "# Transpose the clinical_features_df to have samples as rows and features as columns\n",
    "# This is necessary because the current format has features as rows, which is not what we want for linking\n",
    "clinical_features_df_transposed = clinical_features_df.T\n",
    "clinical_features_df_transposed = clinical_features_df_transposed.rename(columns={0: trait})\n",
    "print(\"Transposed clinical features shape:\", clinical_features_df_transposed.shape)\n",
    "print(\"Transposed clinical features columns:\", clinical_features_df_transposed.columns)\n",
    "\n",
    "# Now link the clinical and genetic data\n",
    "linked_data = normalized_gene_data.T\n",
    "linked_data = pd.concat([clinical_features_df_transposed, linked_data], axis=1)\n",
    "print(\"Linked data shape:\", linked_data.shape)\n",
    "print(\"Linked data columns preview:\", linked_data.columns[:10])\n",
    "\n",
    "# Check if trait column exists in linked data\n",
    "if trait in linked_data.columns:\n",
    "    print(f\"Trait column '{trait}' found in linked data\")\n",
    "    print(linked_data[trait].value_counts())\n",
    "else:\n",
    "    print(f\"Warning: '{trait}' column not found in linked data\")\n",
    "    # If trait column is missing, we have a problem\n",
    "    raise ValueError(f\"The trait column '{trait}' is missing in the linked data\")\n",
    "\n",
    "# Handle missing values in the linked data\n",
    "linked_data_cleaned = handle_missing_values(linked_data, trait)\n",
    "print(\"Linked data shape after cleaning:\", linked_data_cleaned.shape)\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_cleaned, 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 endometrium of women with and without stage IV ovarian endometriosis, including both fertile and infertile subjects.\"\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
}