File size: 31,658 Bytes
32677ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "4b434cfc",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:37:51.995139Z",
     "iopub.status.busy": "2025-03-25T08:37:51.995040Z",
     "iopub.status.idle": "2025-03-25T08:37:52.157665Z",
     "shell.execute_reply": "2025-03-25T08:37:52.157332Z"
    }
   },
   "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 = \"Depression\"\n",
    "cohort = \"GSE149980\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Depression\"\n",
    "in_cohort_dir = \"../../input/GEO/Depression/GSE149980\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Depression/GSE149980.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Depression/gene_data/GSE149980.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Depression/clinical_data/GSE149980.csv\"\n",
    "json_path = \"../../output/preprocess/Depression/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bbcda955",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "bcfc6570",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:37:52.159011Z",
     "iopub.status.busy": "2025-03-25T08:37:52.158877Z",
     "iopub.status.idle": "2025-03-25T08:37:53.110834Z",
     "shell.execute_reply": "2025-03-25T08:37:53.110423Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Gene expression of Lymphoblastoid Cell Lines–LCLs from Depressed Patients after in-vitro treatment with citalopram–CTP\"\n",
      "!Series_summary\t\"We used whole gene gene expression profiling to identify potential gene expression biomarkers associated for the treatment individualization of unipolar depression.\"\n",
      "!Series_overall_design\t\"Gene expression was measured after 24 and 48 hours of in-vitro treatment with 3 µM CTP in n=17 LCLs derived from depressed patients with documented clinical treatment outcome to SSRIs.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['response status: responder', 'response status: non-responder'], 1: ['tissue: Lymphoblastoid Cell Lines (LCLs)']}\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": "cb1f51b5",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "eb7e8699",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:37:53.112366Z",
     "iopub.status.busy": "2025-03-25T08:37:53.112260Z",
     "iopub.status.idle": "2025-03-25T08:37:53.120791Z",
     "shell.execute_reply": "2025-03-25T08:37:53.120517Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of extracted clinical data:\n",
      "{'GSM4519184': [1.0], 'GSM4519185': [1.0], 'GSM4519186': [1.0], 'GSM4519187': [1.0], 'GSM4519188': [1.0], 'GSM4519189': [1.0], 'GSM4519190': [1.0], 'GSM4519191': [1.0], 'GSM4519192': [1.0], 'GSM4519193': [1.0], 'GSM4519194': [1.0], 'GSM4519195': [1.0], 'GSM4519196': [1.0], 'GSM4519197': [1.0], 'GSM4519198': [1.0], 'GSM4519199': [1.0], 'GSM4519200': [1.0], 'GSM4519201': [1.0], 'GSM4519202': [0.0], 'GSM4519203': [0.0], 'GSM4519204': [0.0], 'GSM4519205': [0.0], 'GSM4519206': [0.0], 'GSM4519207': [0.0], 'GSM4519208': [0.0], 'GSM4519209': [0.0], 'GSM4519210': [0.0], 'GSM4519211': [0.0], 'GSM4519212': [0.0], 'GSM4519213': [0.0], 'GSM4519214': [0.0], 'GSM4519215': [0.0], 'GSM4519216': [0.0], 'GSM4519217': [0.0], 'GSM4519218': [1.0], 'GSM4519219': [1.0], 'GSM4519220': [1.0], 'GSM4519221': [1.0], 'GSM4519222': [1.0], 'GSM4519223': [1.0], 'GSM4519224': [1.0], 'GSM4519225': [1.0], 'GSM4519226': [1.0], 'GSM4519227': [1.0], 'GSM4519228': [1.0], 'GSM4519229': [1.0], 'GSM4519230': [1.0], 'GSM4519231': [1.0], 'GSM4519232': [1.0], 'GSM4519233': [1.0], 'GSM4519234': [1.0], 'GSM4519235': [1.0], 'GSM4519236': [0.0], 'GSM4519237': [0.0], 'GSM4519238': [0.0], 'GSM4519239': [0.0], 'GSM4519240': [0.0], 'GSM4519241': [0.0], 'GSM4519242': [0.0], 'GSM4519243': [0.0], 'GSM4519244': [0.0], 'GSM4519245': [0.0], 'GSM4519246': [0.0], 'GSM4519247': [0.0], 'GSM4519248': [0.0], 'GSM4519249': [0.0], 'GSM4519250': [0.0], 'GSM4519251': [0.0]}\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "from typing import Optional, Dict, Any, Callable\n",
    "import json\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information, this dataset contains gene expression data of Lymphoblastoid Cell Lines\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# Looking at the Sample Characteristics Dictionary:\n",
    "# Key 0 contains 'response status' which can be used as our trait (depression treatment response)\n",
    "# There's no age or gender information\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: str) -> int:\n",
    "    \"\"\"Convert depression treatment response to binary value.\"\"\"\n",
    "    if isinstance(value, str):\n",
    "        # Extract the part after the colon if present\n",
    "        if \":\" in value:\n",
    "            value = value.split(\":\", 1)[1].strip()\n",
    "        \n",
    "        # Convert to binary\n",
    "        if \"responder\" in value.lower() and \"non\" not in value.lower():\n",
    "            return 1  # Responder\n",
    "        elif \"non-responder\" in value.lower():\n",
    "            return 0  # Non-responder\n",
    "    \n",
    "    return None  # For any other or unknown values\n",
    "\n",
    "def convert_age(value: str) -> Optional[float]:\n",
    "    \"\"\"Convert age to float. Not used in this dataset.\"\"\"\n",
    "    return None\n",
    "\n",
    "def convert_gender(value: str) -> Optional[int]:\n",
    "    \"\"\"Convert gender to binary. Not used in this dataset.\"\"\"\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Conduct initial filtering on dataset usability\n",
    "is_trait_available = trait_row is not None\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. Clinical Feature Extraction\n",
    "if trait_row is not None:\n",
    "    # We should use the clinical_data that was loaded in a previous step\n",
    "    # Since the actual clinical_data should be available in the environment\n",
    "    # We'll use geo_select_clinical_features with the existing clinical_data\n",
    "    \n",
    "    try:\n",
    "        # Extract clinical features using the provided function\n",
    "        selected_clinical_df = geo_select_clinical_features(\n",
    "            clinical_df=clinical_data,  # Assuming clinical_data is already loaded\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 data\n",
    "        preview = preview_df(selected_clinical_df)\n",
    "        print(\"Preview of extracted clinical data:\")\n",
    "        print(preview)\n",
    "        \n",
    "        # Save to CSV\n",
    "        os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "        selected_clinical_df.to_csv(out_clinical_data_file)\n",
    "    except NameError:\n",
    "        print(\"Warning: clinical_data not found. The clinical data extraction step cannot be completed.\")\n",
    "        print(\"Please ensure the clinical_data DataFrame is available from a previous step.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4c444503",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c7ffc2a4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:37:53.121914Z",
     "iopub.status.busy": "2025-03-25T08:37:53.121813Z",
     "iopub.status.idle": "2025-03-25T08:37:53.489631Z",
     "shell.execute_reply": "2025-03-25T08:37:53.489317Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Matrix file found: ../../input/GEO/Depression/GSE149980/GSE149980_series_matrix.txt.gz\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape: (50739, 68)\n",
      "First 20 gene/probe identifiers:\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', '3xSLv1', 'A_19_P00315452',\n",
      "       'A_19_P00315459', 'A_19_P00315482', 'A_19_P00315492', 'A_19_P00315493',\n",
      "       'A_19_P00315502', 'A_19_P00315506', 'A_19_P00315518', 'A_19_P00315519'],\n",
      "      dtype='object', name='ID')\n"
     ]
    }
   ],
   "source": [
    "# 1. Get the SOFT and matrix file paths again \n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "print(f\"Matrix file found: {matrix_file}\")\n",
    "\n",
    "# 2. Use the get_genetic_data function from the library to get the gene_data\n",
    "try:\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    print(f\"Gene data shape: {gene_data.shape}\")\n",
    "    \n",
    "    # 3. Print the first 20 row IDs (gene or probe identifiers)\n",
    "    print(\"First 20 gene/probe identifiers:\")\n",
    "    print(gene_data.index[:20])\n",
    "except Exception as e:\n",
    "    print(f\"Error extracting gene data: {e}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc2f2dcf",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "35651d57",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:37:53.490749Z",
     "iopub.status.busy": "2025-03-25T08:37:53.490630Z",
     "iopub.status.idle": "2025-03-25T08:37:53.492478Z",
     "shell.execute_reply": "2025-03-25T08:37:53.492205Z"
    }
   },
   "outputs": [],
   "source": [
    "# Analyze the gene identifiers\n",
    "# These identifiers (like '(+)E1A_r60_1', 'A_19_P00315452') are not standard human gene symbols\n",
    "# They appear to be probe IDs from a microarray platform that need to be mapped to gene symbols\n",
    "\n",
    "# Human gene symbols would typically be like BRCA1, TP53, IL6, etc.\n",
    "# The identifiers we see are platform-specific probe IDs that need mapping\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d23cfbbc",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "64856b18",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:37:53.493365Z",
     "iopub.status.busy": "2025-03-25T08:37:53.493266Z",
     "iopub.status.idle": "2025-03-25T08:38:01.970519Z",
     "shell.execute_reply": "2025-03-25T08:38:01.970158Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Platform title found: Agilent-039494 SurePrint G3 Human GE v2 8x60K Microarray 039381 (Probe Name version)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "{'ID': ['GE_BrightCorner', 'DarkCorner', 'A_23_P117082', 'A_33_P3246448', 'A_33_P3318220', 'A_33_P3236322', 'A_33_P3319925', 'A_21_P0000509', 'A_21_P0000744', 'A_24_P215804'], 'SPOT_ID': ['CONTROL', 'CONTROL', 'A_23_P117082', 'A_33_P3246448', 'A_33_P3318220', 'A_33_P3236322', 'A_33_P3319925', 'A_21_P0000509', 'A_21_P0000744', 'A_24_P215804'], 'CONTROL_TYPE': ['pos', 'pos', 'FALSE', 'FALSE', 'FALSE', 'FALSE', 'FALSE', 'FALSE', 'FALSE', 'FALSE'], 'REFSEQ': [nan, nan, 'NM_015987', 'NM_080671', 'NM_178466', nan, 'XM_001133269', 'NR_024244', 'NR_038269', 'NM_016951'], 'GB_ACC': [nan, nan, 'NM_015987', 'NM_080671', 'NM_178466', 'AK128005', 'XM_001133269', 'NR_024244', 'NR_038269', 'NM_016951'], 'LOCUSLINK_ID': [nan, nan, 50865.0, 23704.0, 128861.0, 100129869.0, 730249.0, nan, nan, 51192.0], 'GENE_SYMBOL': [nan, nan, 'HEBP1', 'KCNE4', 'BPIFA3', 'LOC100129869', 'IRG1', 'SNAR-G2', 'LOC100506844', 'CKLF'], 'GENE_NAME': [nan, nan, 'heme binding protein 1', 'potassium voltage-gated channel, Isk-related family, member 4', 'BPI fold containing family A, member 3', 'uncharacterized LOC100129869', 'immunoresponsive 1 homolog (mouse)', 'small ILF3/NF90-associated RNA G2', 'uncharacterized LOC100506844', 'chemokine-like factor'], 'UNIGENE_ID': [nan, nan, 'Hs.642618', 'Hs.348522', 'Hs.360989', nan, 'Hs.160789', 'Hs.717308', 'Hs.90286', 'Hs.15159'], 'ENSEMBL_ID': [nan, nan, 'ENST00000014930', 'ENST00000281830', 'ENST00000375454', nan, 'ENST00000449753', nan, 'ENST00000551421', nan], 'ACCESSION_STRING': [nan, nan, 'ref|NM_015987|ens|ENST00000014930|gb|AF117615|gb|BC016277', 'ref|NM_080671|ens|ENST00000281830|tc|THC2655788', 'ref|NM_178466|ens|ENST00000375454|ens|ENST00000471233|tc|THC2478474', 'gb|AK128005|tc|THC2484382', 'ens|ENST00000449753|ens|ENST00000377462|ref|XM_001133269|ref|XM_003403661', 'ref|NR_024244', 'ref|NR_038269|ens|ENST00000551421|ens|ENST00000546580|ens|ENST00000553102', 'ref|NM_016951|ref|NM_181641|ref|NM_181640|ref|NM_016326'], 'CHROMOSOMAL_LOCATION': [nan, nan, 'chr12:13127906-13127847', 'chr2:223920197-223920256', 'chr20:31812208-31812267', 'chr20:56533874-56533815', 'chr13:77532009-77532068', 'chr19:49534993-49534934', 'chr12:58329728-58329669', 'chr16:66599900-66599959'], 'CYTOBAND': [nan, nan, 'hs|12p13.1', 'hs|2q36.1', 'hs|20q11.21', 'hs|20q13.32', 'hs|13q22.3', 'hs|19q13.33', 'hs|12q14.1', 'hs|16q21'], 'DESCRIPTION': [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]', 'Homo sapiens BPI fold containing family A, member 3 (BPIFA3), transcript variant 1, mRNA [NM_178466]', 'Homo sapiens cDNA FLJ46124 fis, clone TESTI2040372. [AK128005]', 'immunoresponsive 1 homolog (mouse) [Source:HGNC Symbol;Acc:33904] [ENST00000449753]', 'Homo sapiens small ILF3/NF90-associated RNA G2 (SNAR-G2), small nuclear RNA [NR_024244]', 'Homo sapiens uncharacterized LOC100506844 (LOC100506844), non-coding RNA [NR_038269]', 'Homo sapiens chemokine-like factor (CKLF), transcript variant 1, mRNA [NM_016951]'], 'GO_ID': [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)', 'GO:0005576(extracellular region)|GO:0008289(lipid binding)', nan, 'GO:0019543(propionate catabolic process)|GO:0032496(response to lipopolysaccharide)|GO:0047547(2-methylcitrate dehydratase activity)', nan, nan, 'GO:0005576(extracellular region)|GO:0005615(extracellular space)|GO:0006935(chemotaxis)|GO:0008009(chemokine activity)|GO:0008283(cell proliferation)|GO:0016020(membrane)|GO:0016021(integral to membrane)|GO:0030593(neutrophil chemotaxis)|GO:0032940(secretion by cell)|GO:0048246(macrophage chemotaxis)|GO:0048247(lymphocyte chemotaxis)'], 'SEQUENCE': [nan, nan, 'AAGGGGGAAAATGTGATTTGTGCCTGATCTTTCATCTGTGATTCTTATAAGAGCTTTGTC', 'GCAAGTCTCTCTGCACCTATTAAAAAGTGATGTATATACTTCCTTCTTATTCTGTTGAGT', 'CATTCCATAAGGAGTGGTTCTCGGCAAATATCTCACTTGAATTTGACCTTGAATTGAGAC', 'ATTTATTTTCACAAGTGCATAGCGGCCAACACCACCAGCACTAACCAGAGTGGATTCTTG', 'AGAAGACCTAGAAGACTGTTCTGTGTTAACTACACTTCTCAAAGGACCCTCTCCACCAGA', 'AGGGGAGGGTTCGAGGGTACGAGTTCGAGGCCAACCGGGTCCACATTGGTTGAGAAAAAA', 'AGTCGTACCCTCTTGTTTTTCTCTGAGTCAGTCTTAAGGTGAAATGAAGTGTGGCCCAGT', 'AAAGAAGTTTTGTAATTTTATATTACTTTTTAGTTTGATACTAAGTATTAAACATATTTC']}\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",
    "# Check if there are any platforms defined in the SOFT file that might contain annotation data\n",
    "with gzip.open(soft_file, 'rt') as f:\n",
    "    soft_content = f.read()\n",
    "\n",
    "# Look for platform sections in the SOFT file\n",
    "platform_sections = re.findall(r'^!Platform_title\\s*=\\s*(.+)$', soft_content, re.MULTILINE)\n",
    "if platform_sections:\n",
    "    print(f\"Platform title found: {platform_sections[0]}\")\n",
    "\n",
    "# Try to extract more annotation data by reading directly from the SOFT file\n",
    "# Look for lines that might contain gene symbol mappings\n",
    "symbol_pattern = re.compile(r'ID_REF\\s+Symbol|ID\\s+Gene Symbol', re.IGNORECASE)\n",
    "annotation_lines = []\n",
    "with gzip.open(soft_file, 'rt') as f:\n",
    "    for line in f:\n",
    "        if symbol_pattern.search(line):\n",
    "            annotation_lines.append(line)\n",
    "            # Collect the next few lines to see the annotation structure\n",
    "            for _ in range(10):\n",
    "                annotation_lines.append(next(f, ''))\n",
    "\n",
    "if annotation_lines:\n",
    "    print(\"Found potential gene symbol mappings:\")\n",
    "    for line in annotation_lines:\n",
    "        print(line.strip())\n",
    "\n",
    "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
    "print(\"\\nGene annotation preview:\")\n",
    "print(preview_df(gene_annotation, n=10))\n",
    "\n",
    "# If we need an alternative source of mapping, check if there are any other annotation files in the cohort directory\n",
    "cohort_files = os.listdir(in_cohort_dir)\n",
    "annotation_files = [f for f in cohort_files if 'annotation' in f.lower() or 'platform' in f.lower()]\n",
    "if annotation_files:\n",
    "    print(\"\\nAdditional annotation files found in the cohort directory:\")\n",
    "    for file in annotation_files:\n",
    "        print(file)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ebfdd05c",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "5ae708c1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:38:01.971871Z",
     "iopub.status.busy": "2025-03-25T08:38:01.971756Z",
     "iopub.status.idle": "2025-03-25T08:38:03.101993Z",
     "shell.execute_reply": "2025-03-25T08:38:03.101665Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping dataframe shape: (46204, 2)\n",
      "First few rows of the gene mapping dataframe:\n",
      "              ID          Gene\n",
      "2   A_23_P117082         HEBP1\n",
      "3  A_33_P3246448         KCNE4\n",
      "4  A_33_P3318220        BPIFA3\n",
      "5  A_33_P3236322  LOC100129869\n",
      "6  A_33_P3319925          IRG1\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Transformed gene expression data shape: (20353, 68)\n",
      "First few gene symbols:\n",
      "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M', 'A2ML1', 'A2MP1', 'A4GALT',\n",
      "       'A4GNT', 'AA06'],\n",
      "      dtype='object', name='Gene')\n",
      "After normalizing gene symbols, shape: (19847, 68)\n",
      "Preview of normalized gene expression data (first 5 genes, first 5 samples):\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "          GSM4519184  GSM4519185  GSM4519186  GSM4519187  GSM4519188\n",
      "Gene                                                                \n",
      "A1BG        0.857412    0.183019   -1.851454   -1.841433    0.033260\n",
      "A1BG-AS1    0.193574    0.635310   -0.273058    0.066432    0.151078\n",
      "A1CF        0.951021   -0.351138   -0.663651   -0.789045    0.338096\n",
      "A2M        -0.620814   -0.329174   -0.151582   -0.199618   -1.207462\n",
      "A2ML1       0.823854   -0.336316   -0.476297   -0.466115    0.673593\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to ../../output/preprocess/Depression/gene_data/GSE149980.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the columns in gene_annotation that map to gene identifiers and gene symbols\n",
    "# Based on the preview of gene_annotation, 'ID' appears to be the gene identifier column, matching the identifiers seen in gene_data\n",
    "# 'GENE_SYMBOL' contains the gene symbols we want to map to\n",
    "\n",
    "# 2. Create the gene mapping dataframe using the get_gene_mapping function\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')\n",
    "print(f\"Gene mapping dataframe shape: {gene_mapping.shape}\")\n",
    "print(\"First few rows of the gene mapping dataframe:\")\n",
    "print(gene_mapping.head())\n",
    "\n",
    "# 3. Convert probe-level measurements to gene-level expression data\n",
    "# Use the apply_gene_mapping function to perform the conversion\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "print(f\"Transformed gene expression data shape: {gene_data.shape}\")\n",
    "print(\"First few gene symbols:\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# 4. Further normalize gene symbols to handle synonyms\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"After normalizing gene symbols, shape: {gene_data.shape}\")\n",
    "print(\"Preview of normalized gene expression data (first 5 genes, first 5 samples):\")\n",
    "print(gene_data.iloc[:5, :5])\n",
    "\n",
    "# 5. Save the gene expression data to the output 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": "1d8d39b1",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "49440fa8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:38:03.103387Z",
     "iopub.status.busy": "2025-03-25T08:38:03.103272Z",
     "iopub.status.idle": "2025-03-25T08:38:13.163245Z",
     "shell.execute_reply": "2025-03-25T08:38:13.162799Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Selected clinical data shape: (1, 68)\n",
      "Clinical data preview:\n",
      "{'GSM4519184': [1.0], 'GSM4519185': [1.0], 'GSM4519186': [1.0], 'GSM4519187': [1.0], 'GSM4519188': [1.0], 'GSM4519189': [1.0], 'GSM4519190': [1.0], 'GSM4519191': [1.0], 'GSM4519192': [1.0], 'GSM4519193': [1.0], 'GSM4519194': [1.0], 'GSM4519195': [1.0], 'GSM4519196': [1.0], 'GSM4519197': [1.0], 'GSM4519198': [1.0], 'GSM4519199': [1.0], 'GSM4519200': [1.0], 'GSM4519201': [1.0], 'GSM4519202': [0.0], 'GSM4519203': [0.0], 'GSM4519204': [0.0], 'GSM4519205': [0.0], 'GSM4519206': [0.0], 'GSM4519207': [0.0], 'GSM4519208': [0.0], 'GSM4519209': [0.0], 'GSM4519210': [0.0], 'GSM4519211': [0.0], 'GSM4519212': [0.0], 'GSM4519213': [0.0], 'GSM4519214': [0.0], 'GSM4519215': [0.0], 'GSM4519216': [0.0], 'GSM4519217': [0.0], 'GSM4519218': [1.0], 'GSM4519219': [1.0], 'GSM4519220': [1.0], 'GSM4519221': [1.0], 'GSM4519222': [1.0], 'GSM4519223': [1.0], 'GSM4519224': [1.0], 'GSM4519225': [1.0], 'GSM4519226': [1.0], 'GSM4519227': [1.0], 'GSM4519228': [1.0], 'GSM4519229': [1.0], 'GSM4519230': [1.0], 'GSM4519231': [1.0], 'GSM4519232': [1.0], 'GSM4519233': [1.0], 'GSM4519234': [1.0], 'GSM4519235': [1.0], 'GSM4519236': [0.0], 'GSM4519237': [0.0], 'GSM4519238': [0.0], 'GSM4519239': [0.0], 'GSM4519240': [0.0], 'GSM4519241': [0.0], 'GSM4519242': [0.0], 'GSM4519243': [0.0], 'GSM4519244': [0.0], 'GSM4519245': [0.0], 'GSM4519246': [0.0], 'GSM4519247': [0.0], 'GSM4519248': [0.0], 'GSM4519249': [0.0], 'GSM4519250': [0.0], 'GSM4519251': [0.0]}\n",
      "Clinical data saved to ../../output/preprocess/Depression/clinical_data/GSE149980.csv\n",
      "Linked data shape: (68, 19848)\n",
      "Linked data preview (first 5 rows, 5 columns):\n",
      "            Depression      A1BG  A1BG-AS1      A1CF       A2M\n",
      "GSM4519184         1.0  0.857412  0.193574  0.951021 -0.620814\n",
      "GSM4519185         1.0  0.183019  0.635310 -0.351138 -0.329174\n",
      "GSM4519186         1.0 -1.851454 -0.273058 -0.663651 -0.151582\n",
      "GSM4519187         1.0 -1.841433  0.066432 -0.789045 -0.199618\n",
      "GSM4519188         1.0  0.033260  0.151078  0.338096 -1.207462\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Data shape after handling missing values: (68, 19848)\n",
      "For the feature 'Depression', the least common label is '0.0' with 32 occurrences. This represents 47.06% of the dataset.\n",
      "The distribution of the feature 'Depression' in this dataset is fine.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Depression/GSE149980.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. We'll normalize gene symbols in the gene expression data\n",
    "# Note: We've already done this in step 6, so we can skip this part\n",
    "\n",
    "# 2. Link the clinical and genetic data\n",
    "# First, let's make sure we have the correct clinical data from step 2\n",
    "# Review the clinical data attributes from step 2\n",
    "def convert_trait(value: str) -> int:\n",
    "    \"\"\"Convert depression treatment response to binary value.\"\"\"\n",
    "    if isinstance(value, str):\n",
    "        # Extract the part after the colon if present\n",
    "        if \":\" in value:\n",
    "            value = value.split(\":\", 1)[1].strip()\n",
    "        \n",
    "        # Convert to binary\n",
    "        if \"responder\" in value.lower() and \"non\" not in value.lower():\n",
    "            return 1  # Responder\n",
    "        elif \"non-responder\" in value.lower():\n",
    "            return 0  # Non-responder\n",
    "    \n",
    "    return None  # For any other or unknown values\n",
    "\n",
    "# Get clinical data using the correct row index identified in step 2\n",
    "selected_clinical_df = geo_select_clinical_features(\n",
    "    clinical_df=clinical_data,\n",
    "    trait=trait,\n",
    "    trait_row=0,  # Using row 0 for response status as identified in step 2\n",
    "    convert_trait=convert_trait,\n",
    "    age_row=None,  # No age data available\n",
    "    convert_age=None,\n",
    "    gender_row=None,  # No gender data available\n",
    "    convert_gender=None\n",
    ")\n",
    "\n",
    "print(f\"Selected clinical data shape: {selected_clinical_df.shape}\")\n",
    "print(\"Clinical data preview:\")\n",
    "print(preview_df(selected_clinical_df))\n",
    "\n",
    "# Save clinical data for future reference\n",
    "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "selected_clinical_df.to_csv(out_clinical_data_file)\n",
    "print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "\n",
    "# Link clinical and genetic data\n",
    "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data)\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "print(\"Linked data preview (first 5 rows, 5 columns):\")\n",
    "print(linked_data.iloc[:5, :5] if not linked_data.empty else \"Linked data is empty\")\n",
    "\n",
    "# 3. Handle missing values\n",
    "linked_data = handle_missing_values(linked_data, trait)\n",
    "print(f\"Data shape after handling missing values: {linked_data.shape}\")\n",
    "\n",
    "# 4. Check for bias in features\n",
    "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "\n",
    "# 5. Validate and save 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_biased,\n",
    "    df=linked_data,\n",
    "    note=\"Dataset contains gene expression data from Lymphoblastoid Cell Lines of depressed patients with SSRI treatment outcomes (responders/non-responders).\"\n",
    ")\n",
    "\n",
    "# 6. Save the linked data if usable\n",
    "if is_usable:\n",
    "    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "    linked_data.to_csv(out_data_file)\n",
    "    print(f\"Linked data saved to {out_data_file}\")\n",
    "else:\n",
    "    print(\"Dataset is not usable for analysis. No linked data file 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
}