File size: 28,532 Bytes
d1894e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "9378ba1b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:15:39.949111Z",
     "iopub.status.busy": "2025-03-25T05:15:39.948930Z",
     "iopub.status.idle": "2025-03-25T05:15:40.117210Z",
     "shell.execute_reply": "2025-03-25T05:15:40.116843Z"
    }
   },
   "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 = \"Essential_Thrombocythemia\"\n",
    "cohort = \"GSE55976\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Essential_Thrombocythemia\"\n",
    "in_cohort_dir = \"../../input/GEO/Essential_Thrombocythemia/GSE55976\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Essential_Thrombocythemia/GSE55976.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Essential_Thrombocythemia/gene_data/GSE55976.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Essential_Thrombocythemia/clinical_data/GSE55976.csv\"\n",
    "json_path = \"../../output/preprocess/Essential_Thrombocythemia/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16a8d173",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "984a7b37",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:15:40.118511Z",
     "iopub.status.busy": "2025-03-25T05:15:40.118361Z",
     "iopub.status.idle": "2025-03-25T05:15:40.164008Z",
     "shell.execute_reply": "2025-03-25T05:15:40.163632Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Gene expression profile in myeloproliferative neoplasms\"\n",
      "!Series_summary\t\"Myeloproliferative neoplasms (MPN) are clonal hematopoietic diseases that include essential thrombocytosis (ET), polycythemia vera (PV) and primary myelofibrosis (PMF) as well as BCR-ABL+ chronic myelogenous leukemia (CML). In the past several years, studies with cDNA microarrays have defined patterns of gene expression corresponding to specific molecular abnormalities, oncologic phenotypes, and clinical outcomes in hematologic malignancies. This study was aimed at the description of a gene expression signature in MPN which would eventually present a new pathogenetic approaching and also diagnostic as well as prognostic information. Using cDNA microarray analysis, involving 25,100 unique genes, we studied the gene expression profile of the pluripotent hematopoietic CD34+ stem cells and mature granulocytes obtained from peripheral blood of ET, PV, PMF and CML patients compared with healthy individuals. The average number of CD34+ cells (cells/µl) in peripheral blood was approximately 6 in PV and ET, 111 in PMF and 2880 in CML as measured by flow cytometry. A somatic point mutation JAK2V617F was detected in 93% of PV, 73% of PMF and 55% of ET patients within genetically homogenous population. The homozigosity for JAK2V617F mutation was the highest in PV (60%), less prominent in PMF (42%) and low in ET (11%) patients. The JAK2V617F mutation negative patients were also negative for exon 12 mutations. Approximately 420, 680 and 1130 genes had unique expression among CD34+ cells of ET, PV and PMF patients, respectively. In addition comparing to healthy controls, ET, PV, PMF and CML patients showed difference in 840, 1180, 1160 and 2050 expressed genes, respectively.  Furthermore, we studied EPO and JAK-STAT signaling pathways related genes expression in MPN. The FOS, RAF1 and JAK2 gene expression, related to EPO signaling pathway, was elevated in ET, PV, PMF and reduced in CML comparing to healthy controls. Related to these genes, the JAK2V617F mutation homozygous and heterozygous patients generally displayed more significant differences comparing to patients with no mutation. STAT5 gene expression was decreased in all MPN patients. CSF3R, STAT1 and STAT3 gene expression, related to JAK-STAT signaling pathway, was elevated in ET, PV, PMF and reduced in CML comparing to healthy controls. CREBBP gene expression was reduced in CD34+ cells of ET, PV and PMF patients, but during maturation it enhanced expression in granulocytes.  In conclusion, molecular profiling of CD34+ cells and granulocytes revealed a certain number of genes with changed expression that, beyond their recognized function in disease pathogenesis, can be related to patients’ clinical characteristics and may have an imminent prognostic relevance.\"\n",
      "!Series_overall_design\t\"All study de novo patients were subjects to 30 ml of peripheral blood draw on one occasion, collected in 10% sodium citrate. The maximum time interval between venepuncture and arrival in the laboratory was 2 hours. Each 30 ml of diluted lymphocytes and other mononuclear cells (1:1,2 with Ca2+/Mg2+-free PBS) was then layered gently on top of 15 ml lymphocyte separation medium (LSM, PAA Laboratories GmbH, Pasching, Austria). After centrifugation (400g, 30 min, 20C), the interface of containing mononuclear cells was collected and washed with PBS. The CD34+ progenitor cells were isolated from the collected mononuclear cells using a magnetic separation column (Super Macs II, Miltenyi Biotec, Bergisch Gladbach, Germany) and a mixture of magnetic microbeads conjugated with antibody against CD34 (Miltenyi Biotec) according to the manufacturer's instructions. The pellet which is formed, during centrifugation with LSM, is comprised mostly of erythrocytes and granulocytes that migrated through the gradient. Contaminating erythrocytes were removed by using lysing solution (0.15 M NH4Cl,  0.1 mM Na2EDTA, 12 mM NaHCO3). High quality of purified granulocytes was confirmed by cytospin preparations and Wright–Giemsa staining. The viable CD34+ cell and granulocyte counts were performed with the use of a trypan-blue exclusion technique (BioWhittaker). The purity of recovered cells was determined by flow cytometry using PE–anti-CD34 mAb (BD Biosciences, San Jose, CA, USA) and was over 80% in samples for microarray analysis. Karyotype analysis did not show any chromosome aberrations in samples for microarray analysis.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['subject condition: Polycythemia vera (PV)', 'subject condition: Essential thrombocythemia JAK2+', 'subject condition: Essential thrombocythemia JAK2-', 'subject condition: Primary myelofibrosis JAK2+', 'subject condition: Primary myelofibrosis JAK2-', 'subject condition: Chronic myelogenous leukemia', 'subject condition: Healthy donor'], 1: ['cell type: CD34+ hematopoietic progenitors', 'cell type: Granulocytes']}\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": "baefeee7",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "57be5ab7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:15:40.165586Z",
     "iopub.status.busy": "2025-03-25T05:15:40.165475Z",
     "iopub.status.idle": "2025-03-25T05:15:40.175376Z",
     "shell.execute_reply": "2025-03-25T05:15:40.175063Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of clinical features:\n",
      "{'Sample_1': [0.0], 'Sample_2': [1.0], 'Sample_3': [1.0], 'Sample_4': [0.0], 'Sample_5': [0.0], 'Sample_6': [0.0], 'Sample_7': [0.0]}\n",
      "Clinical features saved to ../../output/preprocess/Essential_Thrombocythemia/clinical_data/GSE55976.csv\n"
     ]
    }
   ],
   "source": [
    "# Import necessary modules\n",
    "import pandas as pd\n",
    "import os\n",
    "import json\n",
    "from typing import Dict, Any, Callable, Optional\n",
    "\n",
    "# From the sample characteristics dictionary, we need to format the data properly\n",
    "# for the geo_select_clinical_features function\n",
    "sample_characteristics = {\n",
    "    0: ['subject condition: Polycythemia vera (PV)', \n",
    "        'subject condition: Essential thrombocythemia JAK2+', \n",
    "        'subject condition: Essential thrombocythemia JAK2-', \n",
    "        'subject condition: Primary myelofibrosis JAK2+', \n",
    "        'subject condition: Primary myelofibrosis JAK2-', \n",
    "        'subject condition: Chronic myelogenous leukemia', \n",
    "        'subject condition: Healthy donor'],\n",
    "    1: ['cell type: CD34+ hematopoietic progenitors', 'cell type: Granulocytes']\n",
    "}\n",
    "\n",
    "# Create a proper DataFrame format for the geo_select_clinical_features function\n",
    "# Each row (index) corresponds to a characteristic type, columns will be samples\n",
    "# Here we're creating a mock structure with sample IDs as columns\n",
    "clinical_data = pd.DataFrame()\n",
    "for key, values in sample_characteristics.items():\n",
    "    for i, value in enumerate(values):\n",
    "        clinical_data.loc[key, f'Sample_{i+1}'] = value\n",
    "\n",
    "# Analyze gene availability\n",
    "# From the background information, this dataset involves gene expression profiling\n",
    "is_gene_available = True\n",
    "\n",
    "# Variable availability and data type conversion\n",
    "# For trait (Essential_Thrombocythemia)\n",
    "trait_row = 0  # The condition information is in row 0\n",
    "\n",
    "def convert_trait(value):\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Check if the value indicates Essential Thrombocythemia\n",
    "    if \"Essential thrombocythemia\" in value:\n",
    "        return 1  # Has the condition\n",
    "    elif value in [\"Healthy donor\", \"Polycythemia vera (PV)\", \"Primary myelofibrosis JAK2+\", \n",
    "                  \"Primary myelofibrosis JAK2-\", \"Chronic myelogenous leukemia\"]:\n",
    "        return 0  # Does not have the condition\n",
    "    else:\n",
    "        return None  # Other conditions or unknown\n",
    "\n",
    "# For age and gender\n",
    "# Based on the provided data, there's no information about age or gender\n",
    "age_row = None\n",
    "gender_row = None\n",
    "\n",
    "def convert_age(value):\n",
    "    return None  # No age data available\n",
    "\n",
    "def convert_gender(value):\n",
    "    return None  # No gender data available\n",
    "\n",
    "# Save metadata - initial filtering on 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",
    "# Clinical feature extraction - if trait data is available\n",
    "if trait_row is not None:\n",
    "    # Extract clinical features\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",
    "    # Preview the extracted clinical features\n",
    "    preview = preview_df(clinical_features)\n",
    "    print(\"Preview of clinical features:\")\n",
    "    print(preview)\n",
    "    \n",
    "    # Create directory if it doesn't exist\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    \n",
    "    # Save clinical features to CSV\n",
    "    clinical_features.to_csv(out_clinical_data_file, index=False)\n",
    "    print(f\"Clinical features saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "00a9df50",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "7b1a77c0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:15:40.176843Z",
     "iopub.status.busy": "2025-03-25T05:15:40.176730Z",
     "iopub.status.idle": "2025-03-25T05:15:40.214005Z",
     "shell.execute_reply": "2025-03-25T05:15:40.213612Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "First 20 gene/probe identifiers:\n",
      "Index(['6590728', '6590730', '6590731', '6590732', '6590733', '6590734',\n",
      "       '6590735', '6590738', '6590740', '6590742', '6590744', '6590745',\n",
      "       '6590746', '6590750', '6590752', '6590753', '6590754', '6590757',\n",
      "       '6590759', '6590764'],\n",
      "      dtype='object', name='ID')\n"
     ]
    }
   ],
   "source": [
    "# 1. First get the file paths again to access the matrix file\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. Use the get_genetic_data function from the library to get the gene_data from the matrix_file\n",
    "gene_data = get_genetic_data(matrix_file)\n",
    "\n",
    "# 3. Print the first 20 row IDs (gene or probe identifiers) for future observation\n",
    "print(\"First 20 gene/probe identifiers:\")\n",
    "print(gene_data.index[:20])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c695a220",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "83f12c26",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:15:40.215231Z",
     "iopub.status.busy": "2025-03-25T05:15:40.215119Z",
     "iopub.status.idle": "2025-03-25T05:15:40.216960Z",
     "shell.execute_reply": "2025-03-25T05:15:40.216670Z"
    }
   },
   "outputs": [],
   "source": [
    "# Examining the gene identifiers\n",
    "# These appear to be probe IDs from a microarray platform (likely Illumina) \n",
    "# rather than standard human gene symbols\n",
    "# Standard human gene symbols would typically be alphanumeric like 'BRCA1', 'TP53', etc.\n",
    "# These identifiers are purely numeric and in a sequential format typical of microarray probes\n",
    "\n",
    "# Therefore, we need to map these probe IDs to human gene symbols\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "19f60f75",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "63ab3071",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:15:40.217826Z",
     "iopub.status.busy": "2025-03-25T05:15:40.217723Z",
     "iopub.status.idle": "2025-03-25T05:15:40.650868Z",
     "shell.execute_reply": "2025-03-25T05:15:40.650480Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['6590728', '6590730', '6590731', '6590732', '6590733'], 'SPOT_ID': ['H200000005', 'H200000006', 'H200000160', 'H200000007', 'H200000161'], 'UniGene_ID': ['Hs.508950', 'Hs.365365', 'Hs.646', 'Hs.584238', 'Hs.592244'], 'GENE SYMBOL': ['TGM1', 'FECH', 'CPA3', 'GLDC', 'CD40LG'], 'DESCRIPTION': ['transglutaminase 1 (K polypeptide epidermal type I, protein-glutamine-gamma-glutamyltransferase) (TGM1), mRNA.', 'ferrochelatase (FECH), nuclear gene encoding mitochondrial protein, transcript variant 2, mRNA.', 'carboxypeptidase A3 (mast cell) (CPA3), mRNA.', 'glycine dehydrogenase (decarboxylating) (GLDC), nuclear gene encoding mitochondrial protein, mRNA.', 'CD40 ligand (CD40LG), mRNA.'], 'GB_ACC': ['NM_000359', 'NM_000140', 'NM_001870', 'NM_000170', 'NM_000074'], 'SEQUENCES': ['GAAGGCTCTGGGTTACAGAGGCCCAAGATCCTCAACGTTGGGGACATTGGAGGCAATGAAACAGTGACA', 'ATGGGTTACAGAATGCTAGGGAGGCAATTTGGTTACCTGCAATGGCTGCTTTTGCCAGCGAGGCCACCA', 'AGATAACTATCGGGGCTCTGCACCAGAGTCCGAGAAAGAGACGAAAGCTGTCACTAATTTCATTAGAAG', 'TATGGAGATCAGCACCTGGTTTGTACCTGCCCACCCATGGAAGTTTATGAGTCTCCATTTTCTGAACAA', 'TATGGTTGACTCTGGGTTCCTATGGCCTTGTTGGAGGGGGCCAGGCTCTAGAACGTCTAACACAGTGGA']}\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": "9a423b24",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "cceb9f97",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:15:40.652723Z",
     "iopub.status.busy": "2025-03-25T05:15:40.652585Z",
     "iopub.status.idle": "2025-03-25T05:15:40.715817Z",
     "shell.execute_reply": "2025-03-25T05:15:40.715490Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping preview:\n",
      "{'ID': ['6590728', '6590730', '6590731', '6590732', '6590733'], 'Gene': ['TGM1', 'FECH', 'CPA3', 'GLDC', 'CD40LG']}\n",
      "\n",
      "Gene expression data preview (after mapping):\n",
      "{'GSM1349677': [0.0, 0.0, -0.4897, 1.9419, 0.0], 'GSM1349678': [0.0, 0.0, -0.7114, 2.1987, 0.0], 'GSM1349679': [0.0, 0.0, -0.0115, 1.6299, 0.0], 'GSM1349680': [0.0, 0.0, -0.9502, 1.1996, 0.0], 'GSM1349681': [0.0, 0.0, -1.1163, 1.6277, 0.0], 'GSM1349682': [0.0, 0.0, 0.0, 2.6987, 0.0], 'GSM1349683': [1.3455, 0.0, 0.2418, -0.9963, 1.6126], 'GSM1349684': [0.0, 0.0, 0.0, -0.5629, 0.0], 'GSM1349685': [0.0, 0.0, 0.0, -0.7859, 0.0], 'GSM1349686': [0.0, 0.0, 0.0, 1.9169, 0.0], 'GSM1349687': [0.0, 0.0, -0.7553, 1.5212, 0.0], 'GSM1349688': [0.0, 0.0, 0.0, 1.2953, 0.0], 'GSM1349689': [0.0, 0.0, -0.6669, 1.9389, 0.0], 'GSM1349690': [0.0, 0.0, 0.0, 1.0202, 0.0], 'GSM1349691': [0.0, 0.0, 0.0, 0.1879, 0.0], 'GSM1349692': [0.0, 0.0, 0.4545, -0.4535, 1.6245], 'GSM1349693': [0.0, 0.0, 0.0, 0.0, 0.0], 'GSM1349694': [0.0, 0.0, 0.6855, -0.636, 0.0], 'GSM1349695': [0.0, 0.0, 0.0443, 0.7282, 1.0155], 'GSM1349696': [0.0, 0.0, 0.0, 2.4772, 0.0], 'GSM1349697': [0.0, 0.0, -0.9218, 0.8344, 0.0], 'GSM1349698': [0.0, 0.0, 0.0, 0.7932, 0.0], 'GSM1349699': [0.0, 0.0, 0.4928, -0.9152, 0.0], 'GSM1349700': [0.0, 0.0, 0.1554, -0.7299, 0.0], 'GSM1349701': [0.0, 0.0, -1.2347, 2.2319, 0.0], 'GSM1349702': [0.0, 0.0, -1.397, 2.7625, 0.0], 'GSM1349703': [0.0, 0.0, -0.0278, 1.8717, 0.0], 'GSM1349704': [0.0, 0.0, -0.531, 0.792, 0.0], 'GSM1349705': [0.0, -0.3693, 0.5572, -0.1196, 0.0], 'GSM1349706': [0.0, 0.0, 0.0145, -0.692, 1.8637], 'GSM1349707': [0.0, 0.0, -1.2471, 2.649, 0.0], 'GSM1349708': [0.0, 0.0, 0.0, 1.6528, 0.0], 'GSM1349709': [0.0, 0.0, 0.7031, 0.4102, 0.0], 'GSM1349710': [0.0, 0.0, 0.2071, 0.4799, 0.0], 'GSM1349711': [0.0, 0.0, 0.0, 0.0132, 0.0], 'GSM1349712': [0.0, 0.0, 0.3387, -0.5852, 2.0678], 'GSM1349713': [0.0, 0.0, 0.5276, -0.6282, 0.0], 'GSM1349714': [0.0, 0.0, 0.0, -0.9663, 0.0], 'GSM1349715': [0.0, 0.0, 0.3578, -0.6868, 0.0]}\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the columns for probe IDs and gene symbols\n",
    "# From the preview, we can see:\n",
    "# - 'ID' column contains the probe identifiers (same format as in gene_data)\n",
    "# - 'GENE SYMBOL' column contains the human gene symbols\n",
    "\n",
    "# 2. Create the gene mapping dataframe using get_gene_mapping function\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE SYMBOL')\n",
    "\n",
    "# Show a preview of the mapping\n",
    "print(\"Gene mapping preview:\")\n",
    "print(preview_df(gene_mapping))\n",
    "\n",
    "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n",
    "# This handles the many-to-many relation as specified\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "\n",
    "# Print the first few rows of the gene expression data\n",
    "print(\"\\nGene expression data preview (after mapping):\")\n",
    "print(preview_df(gene_data))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1a3e1383",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "9a08ca92",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:15:40.717471Z",
     "iopub.status.busy": "2025-03-25T05:15:40.717361Z",
     "iopub.status.idle": "2025-03-25T05:15:43.697686Z",
     "shell.execute_reply": "2025-03-25T05:15:43.697295Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalizing gene symbols...\n",
      "Gene data shape after normalization: (9529, 39)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Essential_Thrombocythemia/gene_data/GSE55976.csv\n",
      "Loading the original clinical data...\n",
      "Extracting clinical features...\n",
      "Clinical data preview:\n",
      "{'GSM1349677': [0.0], 'GSM1349678': [0.0], 'GSM1349679': [0.0], 'GSM1349680': [0.0], 'GSM1349681': [0.0], 'GSM1349682': [0.0], 'GSM1349683': [0.0], 'GSM1349684': [0.0], 'GSM1349685': [0.0], 'GSM1349686': [1.0], 'GSM1349687': [1.0], 'GSM1349688': [1.0], 'GSM1349689': [1.0], 'GSM1349690': [1.0], 'GSM1349691': [1.0], 'GSM1349692': [1.0], 'GSM1349693': [1.0], 'GSM1349694': [1.0], 'GSM1349695': [0.0], 'GSM1349696': [0.0], 'GSM1349697': [0.0], 'GSM1349698': [0.0], 'GSM1349699': [0.0], 'GSM1349700': [0.0], 'GSM1349701': [0.0], 'GSM1349702': [0.0], 'GSM1349703': [0.0], 'GSM1349704': [0.0], 'GSM1349705': [0.0], 'GSM1349706': [0.0], 'GSM1349707': [0.0], 'GSM1349708': [0.0], 'GSM1349709': [0.0], 'GSM1349710': [0.0], 'GSM1349711': [0.0], 'GSM1349712': [0.0], 'GSM1349713': [0.0], 'GSM1349714': [0.0], 'GSM1349715': [0.0]}\n",
      "Clinical data saved to ../../output/preprocess/Essential_Thrombocythemia/clinical_data/GSE55976.csv\n",
      "Linking clinical and genetic data...\n",
      "Linked data shape: (39, 9530)\n",
      "Handling missing values...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data shape after handling missing values: (39, 9530)\n",
      "Checking for bias in trait distribution...\n",
      "For the feature 'Essential_Thrombocythemia', the least common label is '1.0' with 9 occurrences. This represents 23.08% of the dataset.\n",
      "The distribution of the feature 'Essential_Thrombocythemia' in this dataset is fine.\n",
      "\n",
      "Dataset usability: True\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Essential_Thrombocythemia/GSE55976.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "print(\"Normalizing gene symbols...\")\n",
    "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
    "\n",
    "# Save the normalized gene data to a CSV 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",
    "\n",
    "# 2. Link the clinical and genetic data\n",
    "print(\"Loading the original clinical data...\")\n",
    "# Get the matrix file again to ensure we have the proper data\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n",
    "\n",
    "print(\"Extracting clinical features...\")\n",
    "# Use the clinical_data obtained directly from the matrix file\n",
    "selected_clinical_df = geo_select_clinical_features(\n",
    "    clinical_df=clinical_data,\n",
    "    trait=trait,\n",
    "    trait_row=trait_row,\n",
    "    convert_trait=convert_trait,\n",
    "    age_row=age_row,\n",
    "    convert_age=convert_age,\n",
    "    gender_row=gender_row,\n",
    "    convert_gender=convert_gender\n",
    ")\n",
    "\n",
    "print(\"Clinical data preview:\")\n",
    "print(preview_df(selected_clinical_df))\n",
    "\n",
    "# Save the clinical data to a CSV file\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 using the normalized gene data\n",
    "print(\"Linking clinical and genetic data...\")\n",
    "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "\n",
    "# 3. Handle missing values in the linked data\n",
    "print(\"Handling missing values...\")\n",
    "linked_data = handle_missing_values(linked_data, trait)\n",
    "print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
    "\n",
    "# 4. Check if trait is biased\n",
    "print(\"Checking for bias in trait distribution...\")\n",
    "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "\n",
    "# 5. Final validation\n",
    "note = \"Dataset contains gene expression data from patients with Essential Thrombocythemia (ET), Polycythemia Vera (PV), and Primary Myelofibrosis (PMF).\"\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",
    "print(f\"Dataset usability: {is_usable}\")\n",
    "\n",
    "# 6. Save 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 trait-gene association studies due to bias or other issues.\")"
   ]
  }
 ],
 "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
}