File size: 25,127 Bytes
0d7438c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "947e4742",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:50:06.647173Z",
     "iopub.status.busy": "2025-03-25T05:50:06.647069Z",
     "iopub.status.idle": "2025-03-25T05:50:06.812891Z",
     "shell.execute_reply": "2025-03-25T05:50:06.812564Z"
    }
   },
   "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 = \"Hypertrophic_Cardiomyopathy\"\n",
    "cohort = \"GSE36961\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Hypertrophic_Cardiomyopathy\"\n",
    "in_cohort_dir = \"../../input/GEO/Hypertrophic_Cardiomyopathy/GSE36961\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Hypertrophic_Cardiomyopathy/GSE36961.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Hypertrophic_Cardiomyopathy/gene_data/GSE36961.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Hypertrophic_Cardiomyopathy/clinical_data/GSE36961.csv\"\n",
    "json_path = \"../../output/preprocess/Hypertrophic_Cardiomyopathy/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "586a8fe0",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "0cbfa276",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:50:06.814252Z",
     "iopub.status.busy": "2025-03-25T05:50:06.814103Z",
     "iopub.status.idle": "2025-03-25T05:50:07.136772Z",
     "shell.execute_reply": "2025-03-25T05:50:07.136402Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Transcriptome Profiling of Surgical Myectomy Tissue from Patients with Hypertrophic Cardiomyopathy\"\n",
      "!Series_summary\t\"Using a high-throughput gene expression profiling technology, we have been able to develop new hypotheses regarding the molecular pathogenic mechanisms of human hypertrophic cardiomyopathy (HCM). It is hoped that these hypotheses, among others generated by this data, will fuel future research endeavors that will uncover novel biomarkers, prognostic indicators, and therapeutic targets to improve our ability to diagnose, counsel, and treat patients with this highly heterogeneous and potentially life-threatening condition.\"\n",
      "!Series_overall_design\t\"Case-control study comparing the messenger RNA transcriptome of cardiac tissues from patients with hypertrophic cardiomyopathy to the transcriptome of control donor cardiac tissues.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['Sex: male', 'Sex: female'], 1: ['age (yrs): 9', 'age (yrs): 10', 'age (yrs): 11', 'age (yrs): 13', 'age (yrs): 14', 'age (yrs): 15', 'age (yrs): 16', 'age (yrs): 17', 'age (yrs): 19', 'age (yrs): 20', 'age (yrs): 23', 'age (yrs): 26', 'age (yrs): 27', 'age (yrs): 28', 'age (yrs): 30', 'age (yrs): 31', 'age (yrs): 32', 'age (yrs): 33', 'age (yrs): 35', 'age (yrs): 37', 'age (yrs): 38', 'age (yrs): 41', 'age (yrs): 43', 'age (yrs): 44', 'age (yrs): 45', 'age (yrs): 46', 'age (yrs): 47', 'age (yrs): 48', 'age (yrs): 50', 'age (yrs): 51'], 2: ['tissue: cardiac', 'sample type: control'], 3: ['disease state: hypertrophic cardiomyopathy (HCM)', nan, 'sample type: control'], 4: ['sample type: case', nan]}\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": "361dc928",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "e0d7a138",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:50:07.138094Z",
     "iopub.status.busy": "2025-03-25T05:50:07.137976Z",
     "iopub.status.idle": "2025-03-25T05:50:07.158319Z",
     "shell.execute_reply": "2025-03-25T05:50:07.157990Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical Data Preview:\n",
      "{'GSM907203': [1.0, 9.0, 1.0], 'GSM907204': [1.0, 10.0, 1.0], 'GSM907205': [1.0, 10.0, 0.0], 'GSM907206': [1.0, 11.0, 1.0], 'GSM907207': [1.0, 13.0, 0.0], 'GSM907208': [1.0, 14.0, 1.0], 'GSM907209': [1.0, 15.0, 1.0], 'GSM907210': [1.0, 15.0, 0.0], 'GSM907211': [1.0, 15.0, 1.0], 'GSM907212': [1.0, 15.0, 1.0], 'GSM907213': [1.0, 16.0, 0.0], 'GSM907214': [1.0, 16.0, 1.0], 'GSM907215': [1.0, 17.0, 0.0], 'GSM907216': [1.0, 19.0, 1.0], 'GSM907217': [1.0, 19.0, 1.0], 'GSM907218': [1.0, 20.0, 0.0], 'GSM907219': [1.0, 23.0, 1.0], 'GSM907220': [1.0, 23.0, 0.0], 'GSM907221': [1.0, 26.0, 1.0], 'GSM907222': [1.0, 27.0, 1.0], 'GSM907223': [1.0, 28.0, 1.0], 'GSM907224': [1.0, 30.0, 1.0], 'GSM907225': [1.0, 30.0, 0.0], 'GSM907226': [1.0, 30.0, 0.0], 'GSM907227': [1.0, 31.0, 1.0], 'GSM907228': [1.0, 32.0, 0.0], 'GSM907229': [1.0, 32.0, 0.0], 'GSM907230': [1.0, 33.0, 0.0], 'GSM907231': [1.0, 35.0, 0.0], 'GSM907232': [1.0, 35.0, 0.0], 'GSM907233': [1.0, 37.0, 0.0], 'GSM907234': [1.0, 37.0, 1.0], 'GSM907235': [1.0, 38.0, 1.0], 'GSM907236': [1.0, 38.0, 0.0], 'GSM907237': [1.0, 41.0, 1.0], 'GSM907238': [1.0, 43.0, 0.0], 'GSM907239': [1.0, 43.0, 1.0], 'GSM907240': [1.0, 43.0, 1.0], 'GSM907241': [1.0, 43.0, 1.0], 'GSM907242': [1.0, 44.0, 0.0], 'GSM907243': [1.0, 44.0, 0.0], 'GSM907244': [1.0, 44.0, 1.0], 'GSM907245': [1.0, 45.0, 0.0], 'GSM907246': [1.0, 45.0, 1.0], 'GSM907247': [1.0, 45.0, 1.0], 'GSM907248': [1.0, 45.0, 1.0], 'GSM907249': [1.0, 46.0, 1.0], 'GSM907250': [1.0, 46.0, 0.0], 'GSM907251': [1.0, 47.0, 1.0], 'GSM907252': [1.0, 48.0, 1.0], 'GSM907253': [1.0, 48.0, 0.0], 'GSM907254': [1.0, 50.0, 1.0], 'GSM907255': [1.0, 50.0, 0.0], 'GSM907256': [1.0, 51.0, 0.0], 'GSM907257': [1.0, 51.0, 0.0], 'GSM907258': [1.0, 51.0, 0.0], 'GSM907259': [1.0, 52.0, 0.0], 'GSM907260': [1.0, 52.0, 1.0], 'GSM907261': [1.0, 52.0, 0.0], 'GSM907262': [1.0, 52.0, 1.0], 'GSM907263': [1.0, 53.0, 0.0], 'GSM907264': [1.0, 53.0, 1.0], 'GSM907265': [1.0, 54.0, 0.0], 'GSM907266': [1.0, 54.0, 0.0], 'GSM907267': [1.0, 54.0, 1.0], 'GSM907268': [1.0, 55.0, 0.0], 'GSM907269': [1.0, 56.0, 0.0], 'GSM907270': [1.0, 56.0, 1.0], 'GSM907271': [1.0, 56.0, 0.0], 'GSM907272': [1.0, 56.0, 1.0], 'GSM907273': [1.0, 57.0, 1.0], 'GSM907274': [1.0, 58.0, 0.0], 'GSM907275': [1.0, 58.0, 1.0], 'GSM907276': [1.0, 59.0, 1.0], 'GSM907277': [1.0, 59.0, 1.0], 'GSM907278': [1.0, 59.0, 1.0], 'GSM907279': [1.0, 59.0, 0.0], 'GSM907280': [1.0, 59.0, 1.0], 'GSM907281': [1.0, 59.0, 1.0], 'GSM907282': [1.0, 60.0, 0.0], 'GSM907283': [1.0, 60.0, 1.0], 'GSM907284': [1.0, 62.0, 1.0], 'GSM907285': [1.0, 63.0, 1.0], 'GSM907286': [1.0, 64.0, 0.0], 'GSM907287': [1.0, 65.0, 1.0], 'GSM907288': [1.0, 65.0, 1.0], 'GSM907289': [1.0, 66.0, 0.0], 'GSM907290': [1.0, 67.0, 0.0], 'GSM907291': [1.0, 67.0, 0.0], 'GSM907292': [1.0, 67.0, 0.0], 'GSM907293': [1.0, 67.0, 1.0], 'GSM907294': [1.0, 67.0, 1.0], 'GSM907295': [1.0, 67.0, 1.0], 'GSM907296': [1.0, 69.0, 0.0], 'GSM907297': [1.0, 69.0, 0.0], 'GSM907298': [1.0, 70.0, 0.0], 'GSM907299': [1.0, 70.0, 0.0], 'GSM907300': [1.0, 71.0, 0.0], 'GSM907301': [1.0, 71.0, 0.0], 'GSM907302': [1.0, 71.0, 0.0], 'GSM907303': [1.0, 73.0, 0.0], 'GSM907304': [1.0, 73.0, 1.0], 'GSM907305': [1.0, 75.0, 1.0], 'GSM907306': [1.0, 76.0, 1.0], 'GSM907307': [1.0, 77.0, 0.0], 'GSM907308': [1.0, 78.0, 0.0], 'GSM907309': [nan, nan, 0.0], 'GSM907310': [0.0, 49.0, 0.0], 'GSM907311': [0.0, 48.0, 0.0], 'GSM907312': [nan, nan, 0.0], 'GSM907313': [0.0, 42.0, 0.0], 'GSM907314': [0.0, 53.0, 0.0], 'GSM907315': [nan, nan, 0.0], 'GSM907316': [0.0, 31.0, 0.0], 'GSM907317': [0.0, 54.0, 1.0], 'GSM907318': [0.0, 52.0, 1.0], 'GSM907319': [0.0, 47.0, 1.0], 'GSM907320': [0.0, 26.0, 1.0], 'GSM907321': [0.0, 65.0, 0.0], 'GSM907322': [0.0, 21.0, 1.0], 'GSM907323': [0.0, 41.0, 1.0], 'GSM907324': [0.0, 55.0, 1.0], 'GSM907325': [0.0, 61.0, 1.0], 'GSM907326': [0.0, 36.0, 0.0], 'GSM907327': [0.0, 7.0, 1.0], 'GSM907328': [0.0, 23.0, 1.0], 'GSM907329': [0.0, 17.0, 1.0], 'GSM907330': [0.0, 45.0, 0.0], 'GSM907331': [0.0, 40.0, 0.0], 'GSM907332': [0.0, 37.0, 0.0], 'GSM907333': [0.0, 51.0, 0.0], 'GSM907334': [0.0, 39.0, 1.0], 'GSM907335': [0.0, 37.0, 0.0], 'GSM907336': [0.0, 23.0, 1.0], 'GSM907337': [0.0, 19.0, 1.0], 'GSM907338': [0.0, 53.0, 0.0], 'GSM907339': [0.0, 48.0, 0.0], 'GSM907340': [0.0, 47.0, 0.0], 'GSM907341': [0.0, 4.0, 1.0], 'GSM907342': [0.0, 48.0, 0.0], 'GSM907343': [0.0, 25.0, 0.0], 'GSM907344': [0.0, 27.0, 1.0], 'GSM907345': [0.0, 21.0, 1.0], 'GSM907346': [0.0, 27.0, 1.0], 'GSM907347': [0.0, 21.0, 1.0]}\n",
      "Clinical data saved to ../../output/preprocess/Hypertrophic_Cardiomyopathy/clinical_data/GSE36961.csv\n"
     ]
    }
   ],
   "source": [
    "# Check if gene expression data is available\n",
    "# The background information mentions \"messenger RNA transcriptome\" comparing HCM to control samples\n",
    "# This suggests gene expression data is available.\n",
    "is_gene_available = True\n",
    "\n",
    "# Define conversion functions for clinical variables\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait value to binary (0=control, 1=HCM)\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "        \n",
    "    value = value.lower() if isinstance(value, str) else str(value).lower()\n",
    "    \n",
    "    # Extract the value after the colon if present\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    if \"hypertrophic cardiomyopathy\" in value or \"hcm\" in value or \"case\" in value:\n",
    "        return 1\n",
    "    elif \"control\" in value:\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age value to continuous\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "        \n",
    "    value = str(value)\n",
    "    \n",
    "    # Extract the value after the colon if present\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Extract numeric age\n",
    "    match = re.search(r'(\\d+)', value)\n",
    "    if match:\n",
    "        return int(match.group(1))\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender value to binary (0=female, 1=male)\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "        \n",
    "    value = value.lower() if isinstance(value, str) else str(value).lower()\n",
    "    \n",
    "    # Extract the value after the colon if present\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    if \"female\" in value:\n",
    "        return 0\n",
    "    elif \"male\" in value:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# Identify rows with trait, age, and gender information\n",
    "trait_row = None\n",
    "age_row = None\n",
    "gender_row = None\n",
    "\n",
    "# Looking at the sample characteristics dictionary\n",
    "# Row 0 contains gender information (\"Sex: male\", \"Sex: female\")\n",
    "gender_row = 0\n",
    "\n",
    "# Row 1 contains age information with format \"age (yrs): XX\"\n",
    "age_row = 1\n",
    "\n",
    "# Row 3 contains disease state information about HCM vs control\n",
    "trait_row = 3\n",
    "\n",
    "# Determine trait data availability\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Save metadata with initial filtering\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# Extract clinical features if trait data is available\n",
    "if trait_row is not None:\n",
    "    # Use geo_select_clinical_features to 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 to CSV\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    clinical_df.to_csv(out_clinical_data_file, index=False)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2bad2705",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "59ba117c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:50:07.159515Z",
     "iopub.status.busy": "2025-03-25T05:50:07.159407Z",
     "iopub.status.idle": "2025-03-25T05:50:07.730381Z",
     "shell.execute_reply": "2025-03-25T05:50:07.729988Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting gene data from matrix file:\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Successfully extracted gene data with 37846 rows\n",
      "First 20 gene IDs:\n",
      "Index(['7A5', 'A1BG', 'A1CF', 'A26A1', 'A26B1', 'A26C1B', 'A26C3', 'A2BP1',\n",
      "       'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS', 'AACS',\n",
      "       'AACSL', 'AADAC', 'AADACL1', 'AADACL2'],\n",
      "      dtype='object', name='ID')\n",
      "\n",
      "Gene expression data available: True\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. Extract gene expression data from the matrix file\n",
    "try:\n",
    "    print(\"Extracting gene data from matrix file:\")\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    if gene_data.empty:\n",
    "        print(\"Extracted gene expression data is empty\")\n",
    "        is_gene_available = False\n",
    "    else:\n",
    "        print(f\"Successfully extracted gene data with {len(gene_data.index)} rows\")\n",
    "        print(\"First 20 gene IDs:\")\n",
    "        print(gene_data.index[:20])\n",
    "        is_gene_available = True\n",
    "except Exception as e:\n",
    "    print(f\"Error extracting gene data: {e}\")\n",
    "    print(\"This dataset appears to have an empty or malformed gene expression matrix\")\n",
    "    is_gene_available = False\n",
    "\n",
    "print(f\"\\nGene expression data available: {is_gene_available}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3bf8954c",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "972e19e1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:50:07.731762Z",
     "iopub.status.busy": "2025-03-25T05:50:07.731636Z",
     "iopub.status.idle": "2025-03-25T05:50:07.733744Z",
     "shell.execute_reply": "2025-03-25T05:50:07.733419Z"
    }
   },
   "outputs": [],
   "source": [
    "# Review the gene identifiers in the gene expression data\n",
    "\n",
    "# The gene identifiers in the dataset appear to be standard human gene symbols.\n",
    "# Examples like A1BG, AAAS, AACS are recognized human gene symbols.\n",
    "# These are official HUGO Gene Nomenclature Committee (HGNC) symbols\n",
    "# and do not require additional mapping to be used in analysis.\n",
    "\n",
    "requires_gene_mapping = False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "823862bc",
   "metadata": {},
   "source": [
    "### Step 5: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "a658f2b4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:50:07.734915Z",
     "iopub.status.busy": "2025-03-25T05:50:07.734805Z",
     "iopub.status.idle": "2025-03-25T05:50:23.468125Z",
     "shell.execute_reply": "2025-03-25T05:50:23.467237Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape before normalization: (37846, 145)\n",
      "Gene data shape after normalization: (18660, 145)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Hypertrophic_Cardiomyopathy/gene_data/GSE36961.csv\n",
      "Clinical data saved to ../../output/preprocess/Hypertrophic_Cardiomyopathy/clinical_data/GSE36961.csv\n",
      "Linked data shape: (145, 18663)\n",
      "\n",
      "Handling missing values...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "After missing value handling, linked data shape: (142, 18663)\n",
      "\n",
      "Evaluating feature bias...\n",
      "For the feature 'Hypertrophic_Cardiomyopathy', the least common label is '0.0' with 36 occurrences. This represents 25.35% of the dataset.\n",
      "The distribution of the feature 'Hypertrophic_Cardiomyopathy' in this dataset is fine.\n",
      "\n",
      "Quartiles for 'Age':\n",
      "  25%: 30.0\n",
      "  50% (Median): 47.0\n",
      "  75%: 58.0\n",
      "Min: 4.0\n",
      "Max: 78.0\n",
      "The distribution of the feature 'Age' in this dataset is fine.\n",
      "\n",
      "For the feature 'Gender', the least common label is '0.0' with 69 occurrences. This represents 48.59% of the dataset.\n",
      "The distribution of the feature 'Gender' in this dataset is fine.\n",
      "\n",
      "Trait bias evaluation result: False\n",
      "A new JSON file was created at: ../../output/preprocess/Hypertrophic_Cardiomyopathy/cohort_info.json\n",
      "\n",
      "Dataset usability: True\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Hypertrophic_Cardiomyopathy/GSE36961.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols and extract from step 3 and 6\n",
    "# Load the gene expression data (already loaded from Step 6)\n",
    "print(f\"Gene data shape before normalization: {gene_data.shape}\")\n",
    "\n",
    "try:\n",
    "    # Normalize gene symbols using the NCBI Gene database information\n",
    "    normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "    \n",
    "    if normalized_gene_data.empty:\n",
    "        print(\"Normalization resulted in empty dataframe. Using original gene data instead.\")\n",
    "        normalized_gene_data = gene_data\n",
    "    \n",
    "    print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
    "    \n",
    "    # Save the normalized gene data to the output file\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",
    "except Exception as e:\n",
    "    print(f\"Error normalizing gene data: {e}. Using original gene data instead.\")\n",
    "    normalized_gene_data = gene_data\n",
    "    # Save the original gene data if normalization fails\n",
    "    os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "    normalized_gene_data.to_csv(out_gene_data_file)\n",
    "\n",
    "# 2. Link clinical and genetic data\n",
    "# Use the trait_row identified in Step 2 (trait_row = 1) to extract trait data\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "if is_trait_available:\n",
    "    # Extract clinical features using the function and conversion methods from Step 2\n",
    "    clinical_features = 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",
    "    # Save clinical features\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    clinical_features.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(clinical_features, normalized_gene_data)\n",
    "    print(f\"Linked data shape: {linked_data.shape}\")\n",
    "else:\n",
    "    # Create a minimal dataframe with just the trait column\n",
    "    linked_data = pd.DataFrame({trait: [np.nan]})\n",
    "    print(\"No trait data available, creating minimal dataframe for validation.\")\n",
    "\n",
    "# 3. Handle missing values in the linked data\n",
    "if is_trait_available:\n",
    "    print(\"\\nHandling missing values...\")\n",
    "    linked_data = handle_missing_values(linked_data, trait)\n",
    "    print(f\"After missing value handling, linked data shape: {linked_data.shape}\")\n",
    "\n",
    "# 4. Determine whether trait and demographic features are biased\n",
    "if is_trait_available and not linked_data.empty and len(linked_data.columns) > 1:\n",
    "    print(\"\\nEvaluating feature bias...\")\n",
    "    is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "    print(f\"Trait bias evaluation result: {is_biased}\")\n",
    "else:\n",
    "    is_biased = False\n",
    "    print(\"Skipping bias evaluation due to insufficient data.\")\n",
    "\n",
    "# 5. Final validation and save metadata\n",
    "note = \"\"\n",
    "if not is_trait_available:\n",
    "    note = f\"Dataset contains gene expression data but no {trait} measurements.\"\n",
    "elif is_biased:\n",
    "    note = f\"Dataset contains {trait} data but its distribution is severely biased.\"\n",
    "\n",
    "# Validate and save cohort info\n",
    "is_usable = validate_and_save_cohort_info(\n",
    "    is_final=True, \n",
    "    cohort=cohort, \n",
    "    info_path=json_path, \n",
    "    is_gene_available=is_gene_available, \n",
    "    is_trait_available=is_trait_available, \n",
    "    is_biased=is_biased,\n",
    "    df=linked_data,\n",
    "    note=note\n",
    ")\n",
    "\n",
    "# 6. Save the linked data if usable\n",
    "print(f\"\\nDataset usability: {is_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(f\"Dataset is not usable for {trait} association studies. Data 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
}