File size: 27,797 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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "83af420c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:03:11.436632Z",
     "iopub.status.busy": "2025-03-25T08:03:11.436153Z",
     "iopub.status.idle": "2025-03-25T08:03:11.604172Z",
     "shell.execute_reply": "2025-03-25T08:03:11.603683Z"
    }
   },
   "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 = \"GSE165004\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Endometriosis\"\n",
    "in_cohort_dir = \"../../input/GEO/Endometriosis/GSE165004\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Endometriosis/GSE165004.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Endometriosis/gene_data/GSE165004.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Endometriosis/clinical_data/GSE165004.csv\"\n",
    "json_path = \"../../output/preprocess/Endometriosis/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5470cb1d",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "ec72f808",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:03:11.605961Z",
     "iopub.status.busy": "2025-03-25T08:03:11.605773Z",
     "iopub.status.idle": "2025-03-25T08:03:11.896750Z",
     "shell.execute_reply": "2025-03-25T08:03:11.896162Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Endometrial Tissue RNA expression in recurrent pregnancy losses and unexplained infertility vs. conrol\"\n",
      "!Series_summary\t\"Recent studies are directed to decode the genetic signature of endometrial receptivity for better outcomes in assisted reproductive technologies. In this study, we aimed to understand the transcriptomic profile of midsecretory phase endometria of patients with recurrent pregnancy losses (RPL) and unexplained infertility (UI) by comparing with the endometria of healthy fertile women (Controls).\"\n",
      "!Series_summary\t\"In this prospective cohort study, we took endometrial samples from 24 patients with RPL, 24 patients with UI and 24 Controls at day 19-21 of the menstrual cycle. By performing genomic analysis, we assessed for differentially expressed genes (DEGs) and pathway analysis.\"\n",
      "!Series_overall_design\t\"All patients involved in this prospective cohort study were recruited from Istanbul University School of Medicine between August 2014 and August 2015. Three cohorts (fertile controls, patients with RPL and UI) were studied and 24 patients were included in each cohort. None of the patients has received a prior infertility treatment and were not under a current treatment. The first cohort comprised fertile control patients who presented to our gynecology department for well woman examinations. The inclusion criteria were regularly cycling women aged under 35 years with at least one live birth, no history of infertility/treatment, no previous miscarriages and no associated gynecologic (endometriosis, fibroids, active or history of pelvic inflammatory disease) or other medical comorbidities (hyperprolactinemia, thyroid disease etc). The remaining cohorts constituted patients who presented to our in vitro fertilization (IVF) unit. The second cohort included patients with RPL with no history of successful pregnancies. The inclusion criteria for this group were regularly cycling women aged under 35 years with at least two consecutive pregnancy losses of 20 weeks or less, normal follicle-stimulating hormone (FSH), luteinizing hormone (LH), estradiol (E2), prolactin (PRL), and thyroid-stimulating hormone (TSH) levels at day 2-3, normal uterine cavity shape and size, and bilateral tubal patency observed on hysterosalpingogram, no mutations detected in Factor V (Leiden) and prothrombin gene analysis, normal antithrombin III, protein C and S activity, negative results for lupus anticoagulant evaluation, cardiolipin antibody (IgM and IgG), and beta2-glycoprotein antibody (IgM and IgG) and normal karyotype. Their partners have normal spermiogram results and normal karyotype. The third cohort was formed by women with UI at least of 18 months of duration. The inclusion criteria for this group were regularly cycling women aged under 35 years with normal FSH, LH, E2, PRL, and TSH levels at day 2-3, normal uterine cavity shape and size, and bilateral tubal patency observed on a hysterosalpingogram. Their partners have normal spermiogram results.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['subject status/group: Control', 'subject status/group: patient with RPL', 'subject status/group: patient with UIF'], 1: ['tissue: Endometrial tissue']}\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": "b311c241",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "6537167d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:03:11.898611Z",
     "iopub.status.busy": "2025-03-25T08:03:11.898450Z",
     "iopub.status.idle": "2025-03-25T08:03:11.908261Z",
     "shell.execute_reply": "2025-03-25T08:03:11.907794Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical Data Preview:\n",
      "{'GSM5024320': [0.0], 'GSM5024321': [0.0], 'GSM5024322': [0.0], 'GSM5024323': [0.0], 'GSM5024324': [0.0], 'GSM5024325': [0.0], 'GSM5024326': [0.0], 'GSM5024327': [0.0], 'GSM5024328': [0.0], 'GSM5024329': [0.0], 'GSM5024330': [0.0], 'GSM5024331': [0.0], 'GSM5024332': [0.0], 'GSM5024333': [0.0], 'GSM5024334': [0.0], 'GSM5024335': [0.0], 'GSM5024336': [0.0], 'GSM5024337': [0.0], 'GSM5024338': [0.0], 'GSM5024339': [0.0], 'GSM5024340': [0.0], 'GSM5024341': [0.0], 'GSM5024342': [0.0], 'GSM5024343': [0.0], 'GSM5024344': [1.0], 'GSM5024345': [1.0], 'GSM5024346': [1.0], 'GSM5024347': [1.0], 'GSM5024348': [1.0], 'GSM5024349': [1.0], 'GSM5024350': [1.0], 'GSM5024351': [1.0], 'GSM5024352': [1.0], 'GSM5024353': [1.0], 'GSM5024354': [1.0], 'GSM5024355': [1.0], 'GSM5024356': [1.0], 'GSM5024357': [1.0], 'GSM5024358': [1.0], 'GSM5024359': [1.0], 'GSM5024360': [1.0], 'GSM5024361': [1.0], 'GSM5024362': [1.0], 'GSM5024363': [1.0], 'GSM5024364': [1.0], 'GSM5024365': [1.0], 'GSM5024366': [1.0], 'GSM5024367': [1.0], 'GSM5024368': [1.0], 'GSM5024369': [1.0], 'GSM5024370': [1.0], 'GSM5024371': [1.0], 'GSM5024372': [1.0], 'GSM5024373': [1.0], 'GSM5024374': [1.0], 'GSM5024375': [1.0], 'GSM5024376': [1.0], 'GSM5024377': [1.0], 'GSM5024378': [1.0], 'GSM5024379': [1.0], 'GSM5024380': [1.0], 'GSM5024381': [1.0], 'GSM5024382': [1.0], 'GSM5024383': [1.0], 'GSM5024384': [1.0], 'GSM5024385': [1.0], 'GSM5024386': [1.0], 'GSM5024387': [1.0], 'GSM5024388': [1.0], 'GSM5024389': [1.0], 'GSM5024390': [1.0], 'GSM5024391': [1.0]}\n",
      "Clinical data saved to ../../output/preprocess/Endometriosis/clinical_data/GSE165004.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Based on the Series title and summary, this dataset appears to contain RNA expression data\n",
    "# from endometrial tissue, which indicates gene expression data should be available\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# Checking the sample characteristics dictionary for trait, age, and gender information\n",
    "# For trait (endometriosis), we can use row 0 which contains \"subject status/group\"\n",
    "# Age and gender information are not explicitly available in the sample characteristics\n",
    "trait_row = 0\n",
    "age_row = None\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "def convert_trait(value):\n",
    "    \"\"\"\n",
    "    Convert trait values to binary (0 for control, 1 for disease).\n",
    "    In this dataset, endometriosis status is inferred from the study group.\n",
    "    \"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Convert based on subject status\n",
    "    if 'Control' in value:\n",
    "        return 0  # Control group\n",
    "    elif 'patient with RPL' in value or 'patient with UIF' in value:\n",
    "        return 1  # Patient with condition (RPL or UIF)\n",
    "    return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"\n",
    "    Convert age values to continuous.\n",
    "    Not applicable for this dataset as age information is not available.\n",
    "    \"\"\"\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"\n",
    "    Convert gender values to binary (0 for female, 1 for male).\n",
    "    Not applicable for this dataset as gender information is not available.\n",
    "    \"\"\"\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait data availability\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Save initial filtering results\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",
    "# Only do this if trait data is available\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 clinical dataframe\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)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "20553e77",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "5dacd991",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:03:11.909862Z",
     "iopub.status.busy": "2025-03-25T08:03:11.909749Z",
     "iopub.status.idle": "2025-03-25T08:03:12.386916Z",
     "shell.execute_reply": "2025-03-25T08:03:12.386282Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found data marker at line 61\n",
      "Header line: \"ID_REF\"\t\"GSM5024320\"\t\"GSM5024321\"\t\"GSM5024322\"\t\"GSM5024323\"\t\"GSM5024324\"\t\"GSM5024325\"\t\"GSM5024326\"\t\"GSM5024327\"\t\"GSM5024328\"\t\"GSM5024329\"\t\"GSM5024330\"\t\"GSM5024331\"\t\"GSM5024332\"\t\"GSM5024333\"\t\"GSM5024334\"\t\"GSM5024335\"\t\"GSM5024336\"\t\"GSM5024337\"\t\"GSM5024338\"\t\"GSM5024339\"\t\"GSM5024340\"\t\"GSM5024341\"\t\"GSM5024342\"\t\"GSM5024343\"\t\"GSM5024344\"\t\"GSM5024345\"\t\"GSM5024346\"\t\"GSM5024347\"\t\"GSM5024348\"\t\"GSM5024349\"\t\"GSM5024350\"\t\"GSM5024351\"\t\"GSM5024352\"\t\"GSM5024353\"\t\"GSM5024354\"\t\"GSM5024355\"\t\"GSM5024356\"\t\"GSM5024357\"\t\"GSM5024358\"\t\"GSM5024359\"\t\"GSM5024360\"\t\"GSM5024361\"\t\"GSM5024362\"\t\"GSM5024363\"\t\"GSM5024364\"\t\"GSM5024365\"\t\"GSM5024366\"\t\"GSM5024367\"\t\"GSM5024368\"\t\"GSM5024369\"\t\"GSM5024370\"\t\"GSM5024371\"\t\"GSM5024372\"\t\"GSM5024373\"\t\"GSM5024374\"\t\"GSM5024375\"\t\"GSM5024376\"\t\"GSM5024377\"\t\"GSM5024378\"\t\"GSM5024379\"\t\"GSM5024380\"\t\"GSM5024381\"\t\"GSM5024382\"\t\"GSM5024383\"\t\"GSM5024384\"\t\"GSM5024385\"\t\"GSM5024386\"\t\"GSM5024387\"\t\"GSM5024388\"\t\"GSM5024389\"\t\"GSM5024390\"\t\"GSM5024391\"\n",
      "First data line: 1\t16.04322867\t15.40347287\t15.4669395\t14.72857244\t15.80882129\t15.53067649\t15.15167927\t14.55337277\t16.14055719\t15.40623646\t15.25467351\t15.17349668\t16.19113465\t15.47562577\t15.66208174\t14.70747347\t16.10486139\t15.37035048\t15.42876325\t15.42377233\t16.26538617\t15.76140574\t15.85484054\t15.59550261\t16.17910312\t15.50683019\t15.66544664\t15.54171558\t16.33857092\t15.73089139\t15.1576132\t15.55087271\t16.66945828\t15.9297943\t15.49696781\t15.37587985\t15.9083873\t15.19697888\t15.74939633\t14.44660649\t16.0086273\t15.56902617\t15.44531854\t15.89476832\t16.0964873\t15.52716969\t15.15616768\t15.62068029\t16.10239643\t15.90090485\t15.45353263\t15.57225537\t16.05242939\t15.991455\t15.83430272\t15.77449902\t15.78989786\t15.76344479\t15.44852936\t15.51384994\t15.65476078\t15.44531854\t15.28702702\t15.20405136\t15.73616945\t15.73256997\t15.53243337\t15.70189609\t15.20122584\t15.6582036\t15.31632188\t15.79204539\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13',\n",
      "       '14', '15', '16', '17', '18', '19', '20'],\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": "8810fa5e",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "df19150b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:03:12.388631Z",
     "iopub.status.busy": "2025-03-25T08:03:12.388500Z",
     "iopub.status.idle": "2025-03-25T08:03:12.390828Z",
     "shell.execute_reply": "2025-03-25T08:03:12.390393Z"
    }
   },
   "outputs": [],
   "source": [
    "# Based on the gene identifiers shown, I can see the expression data uses numeric probe IDs (1, 2, 3, etc.) \n",
    "# rather than standard human gene symbols like BRCA1, TP53, etc.\n",
    "# These appear to be microarray probe IDs that need to be mapped to actual gene symbols.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "288cd6c5",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "0bfa989c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:03:12.392853Z",
     "iopub.status.busy": "2025-03-25T08:03:12.392512Z",
     "iopub.status.idle": "2025-03-25T08:03:19.105566Z",
     "shell.execute_reply": "2025-03-25T08:03:19.104906Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['1', '2', '3', '4', '5'], 'COL': ['192', '192', '192', '192', '192'], 'ROW': [328.0, 326.0, 324.0, 322.0, 320.0], 'NAME': ['GE_BrightCorner', 'DarkCorner', 'DarkCorner', 'A_23_P117082', 'A_33_P3246448'], 'SPOT_ID': ['CONTROL', 'CONTROL', 'CONTROL', 'A_23_P117082', 'A_33_P3246448'], 'CONTROL_TYPE': ['pos', 'pos', 'pos', 'FALSE', 'FALSE'], 'REFSEQ': [nan, nan, nan, 'NM_015987', 'NM_080671'], 'GB_ACC': [nan, nan, nan, 'NM_015987', 'NM_080671'], 'LOCUSLINK_ID': [nan, nan, nan, 50865.0, 23704.0], 'GENE_SYMBOL': [nan, nan, nan, 'HEBP1', 'KCNE4'], 'GENE_NAME': [nan, nan, nan, 'heme binding protein 1', 'potassium voltage-gated channel, Isk-related family, member 4'], 'UNIGENE_ID': [nan, nan, nan, 'Hs.642618', 'Hs.348522'], 'ENSEMBL_ID': [nan, nan, nan, 'ENST00000014930', 'ENST00000281830'], 'ACCESSION_STRING': [nan, nan, nan, 'ref|NM_015987|ens|ENST00000014930|gb|AF117615|gb|BC016277', 'ref|NM_080671|ens|ENST00000281830|tc|THC2655788'], 'CHROMOSOMAL_LOCATION': [nan, nan, nan, 'chr12:13127906-13127847', 'chr2:223920197-223920256'], 'CYTOBAND': [nan, nan, nan, 'hs|12p13.1', 'hs|2q36.1'], 'DESCRIPTION': [nan, nan, nan, 'Homo sapiens heme binding protein 1 (HEBP1), mRNA [NM_015987]', 'Homo sapiens potassium voltage-gated channel, Isk-related family, member 4 (KCNE4), mRNA [NM_080671]'], 'GO_ID': [nan, nan, nan, 'GO:0005488(binding)|GO:0005576(extracellular region)|GO:0005737(cytoplasm)|GO:0005739(mitochondrion)|GO:0005829(cytosol)|GO:0007623(circadian rhythm)|GO:0020037(heme binding)', 'GO:0005244(voltage-gated ion channel activity)|GO:0005249(voltage-gated potassium channel activity)|GO:0006811(ion transport)|GO:0006813(potassium ion transport)|GO:0016020(membrane)|GO:0016021(integral to membrane)|GO:0016324(apical plasma membrane)'], 'SEQUENCE': [nan, nan, nan, 'AAGGGGGAAAATGTGATTTGTGCCTGATCTTTCATCTGTGATTCTTATAAGAGCTTTGTC', 'GCAAGTCTCTCTGCACCTATTAAAAAGTGATGTATATACTTCCTTCTTATTCTGTTGAGT']}\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": "a410a020",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "90b06d5f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:03:19.107478Z",
     "iopub.status.busy": "2025-03-25T08:03:19.107322Z",
     "iopub.status.idle": "2025-03-25T08:03:20.430788Z",
     "shell.execute_reply": "2025-03-25T08:03:20.430152Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data after mapping:\n",
      "Shape: (20353, 72)\n",
      "First few genes: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M']\n",
      "First few samples: ['GSM5024320', 'GSM5024321', 'GSM5024322', 'GSM5024323', 'GSM5024324']\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to ../../output/preprocess/Endometriosis/gene_data/GSE165004.csv\n"
     ]
    }
   ],
   "source": [
    "# Identify the appropriate columns for mapping\n",
    "# From the preview, I can see:\n",
    "# - 'ID' column contains numeric identifiers that match the gene expression data index\n",
    "# - 'GENE_SYMBOL' column contains the human gene symbols we need\n",
    "\n",
    "# 1. Get the gene mapping dataframe\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')\n",
    "\n",
    "# 2. Apply the gene mapping to convert probe-level measurements to gene expression data\n",
    "# Using the library function to handle the many-to-many mapping logic\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "\n",
    "# 3. Preview the result to verify\n",
    "print(\"Gene expression data after mapping:\")\n",
    "print(f\"Shape: {gene_data.shape}\")\n",
    "print(f\"First few genes: {list(gene_data.index[:5])}\")\n",
    "print(f\"First few samples: {list(gene_data.columns[:5])}\")\n",
    "\n",
    "# Save the gene expression data\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Gene expression data saved to {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "42ebed83",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "72e03311",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:03:20.432594Z",
     "iopub.status.busy": "2025-03-25T08:03:20.432445Z",
     "iopub.status.idle": "2025-03-25T08:03:32.280747Z",
     "shell.execute_reply": "2025-03-25T08:03:32.280108Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Endometriosis/gene_data/GSE165004.csv\n",
      "Clinical data saved to ../../output/preprocess/Endometriosis/clinical_data/GSE165004.csv\n",
      "Linked data shape: (72, 19848)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "For the feature 'Endometriosis', the least common label is '0.0' with 24 occurrences. This represents 33.33% of the dataset.\n",
      "The distribution of the feature 'Endometriosis' in this dataset is fine.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Endometriosis/GSE165004.csv\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
}