File size: 36,444 Bytes
82732bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "0eec103d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:14:55.292127Z",
     "iopub.status.busy": "2025-03-25T05:14:55.291833Z",
     "iopub.status.idle": "2025-03-25T05:14:55.485141Z",
     "shell.execute_reply": "2025-03-25T05:14:55.484699Z"
    }
   },
   "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 = \"GSE103237\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Essential_Thrombocythemia\"\n",
    "in_cohort_dir = \"../../input/GEO/Essential_Thrombocythemia/GSE103237\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Essential_Thrombocythemia/GSE103237.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Essential_Thrombocythemia/gene_data/GSE103237.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Essential_Thrombocythemia/clinical_data/GSE103237.csv\"\n",
    "json_path = \"../../output/preprocess/Essential_Thrombocythemia/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9bf032c1",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "08113114",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:14:55.486748Z",
     "iopub.status.busy": "2025-03-25T05:14:55.486600Z",
     "iopub.status.idle": "2025-03-25T05:14:55.666177Z",
     "shell.execute_reply": "2025-03-25T05:14:55.665737Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Gene and miRNA expression profiles in Polycythemia Vera and Essential Thrombocythemia according to CALR and JAK2 mutations [GEP]\"\n",
      "!Series_summary\t\"Polycythemia vera (PV) and essential thrombocythemia (ET) are Philadelphia-negative myeloproliferative neoplasms (MPNs) characterized by erythrocytosis and thrombocytosis, respectively. Approximately 95% of PV and 50–70% of ET patients harbour the V617F mutation in the exon 14 of JAK2 gene, while about 20-30% of ET patients carry CALRins5 or CALRdel52 mutations. These ET CARL-mutated subjects show higher platelet count and lower thrombotic risk compared to JAK2-mutated patients. Here we showed that CALR-mutated and JAK2V617F-positive CD34+ cells have different gene and miRNA expression profiles. Indeed, we highlighted several pathways differentially activated between JAK2V617F- and CALR-mutated progenitors, i.e. mTOR, MAPK/PI3K and MYC pathways. Furthermore, we unveiled that the expression of several genes involved in DNA repair, chromatin remodelling, splicing and chromatid cohesion are decreased in CALR-mutated cells. According to the low risk of thrombosis in CALR-mutated patients, we also found the down-regulation of several genes involved in thrombin signalling and platelet activation.   As a whole, these data support the model in which CALR-mutated ET could be considered as a distinct disease entity from JAK2V617F-positive MPNs and may provide the molecular basis supporting the different clinical features of these patients.\"\n",
      "!Series_overall_design\t\"Gene expression profile (GEP) and miRNA expression profile (miEP) were performed starting from the same total RNA of CD34+ cells from 50 MPN patients (1 replicate for each sample). In particular, GEP and miEP were performed on 26 PV and 24 ET (n=17 JAK2V617F-positive ET, n=7 CALR-mutated ET). In addition, 15 bone marrow (BM) samples collected from normal donors were included in the study (GSE53482).  These re-analyzed samples have been included in this series for completeness.  This series includes only the GEP samples.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['supplier: Vannucchi', 'supplier: Cazzola'], 1: ['Sex: M', 'Sex: F', 'Sex: not provided'], 2: ['condition: myeloproliferative neoplasm (MPN)', 'condition: Control (CTR)'], 3: ['disease: ET', 'disease: PV', 'disease: healthy control'], 4: ['jak2v617f: neg', 'jak2v617f: pos'], 5: ['mpl-mutated: neg', 'mpl-mutated: ND', 'tissue: Bone marrow'], 6: ['calr-mutated: pos', 'calr-mutated: neg', 'calr-mutated: ND', 'cell marker: CD34+'], 7: ['calr mutation: L367FS52 (tipo I)', 'calr mutation: 385insTTGTC (tipo II)', 'calr mutation: E386del AGGA', 'calr mutation: K391fs51 (tipo II)', 'calr mutation: del52 (tipo I)', 'gene mutation: V617F', nan], 8: ['gene mutation: CALR', 'tissue: Bone marrow', nan], 9: ['tissue: Bone marrow', 'cell marker: CD34+', nan], 10: ['cell marker: CD34+', 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": "a9c66187",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "8832c85b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:14:55.667469Z",
     "iopub.status.busy": "2025-03-25T05:14:55.667354Z",
     "iopub.status.idle": "2025-03-25T05:14:55.678350Z",
     "shell.execute_reply": "2025-03-25T05:14:55.678010Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of extracted clinical features:\n",
      "{3: [0.0, nan], 1: [nan, 0.0]}\n",
      "Clinical data saved to ../../output/preprocess/Essential_Thrombocythemia/clinical_data/GSE103237.csv\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import os\n",
    "import json\n",
    "from typing import Callable, Optional, Dict, Any\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information, this dataset contains gene expression profiles (GEP) from CD34+ cells\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# Trait - Essential Thrombocythemia\n",
    "# Looking at the sample characteristics, disease status is in row 3\n",
    "trait_row = 3\n",
    "\n",
    "# Age - Not available in the sample characteristics\n",
    "age_row = None\n",
    "\n",
    "# Gender - Available in row 1\n",
    "gender_row = 1\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait value to binary (0: control, 1: Essential Thrombocythemia)\"\"\"\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if present\n",
    "    if ':' in str(value):\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary\n",
    "    if value.lower() == 'et' or 'thrombocythemia' in value.lower():\n",
    "        return 1  # Essential Thrombocythemia\n",
    "    elif 'control' in value.lower() or 'healthy' in value.lower() or 'ctr' in value.lower():\n",
    "        return 0  # Control\n",
    "    elif value.lower() == 'pv' or 'polycythemia' in value.lower():\n",
    "        return None  # Not relevant for this trait\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age value to continuous\"\"\"\n",
    "    # Age data is not available\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender value to binary (0: female, 1: male)\"\"\"\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if present\n",
    "    if ':' in str(value):\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary\n",
    "    if value.lower() == 'm':\n",
    "        return 1  # Male\n",
    "    elif value.lower() == 'f':\n",
    "        return 0  # Female\n",
    "    else:\n",
    "        return None  # Unknown or not provided\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait data availability\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Initial filtering for usability\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 (if trait_row is not None)\n",
    "if trait_row is not None:\n",
    "    try:\n",
    "        # Create a DataFrame from the sample characteristics dictionary\n",
    "        # Since we don't have the clinical_data.csv file, we'll create the DataFrame \n",
    "        # based on the Sample Characteristics Dictionary from the previous step\n",
    "        \n",
    "        # Sample characteristics dictionary from previous step\n",
    "        sample_chars = {\n",
    "            0: ['supplier: Vannucchi', 'supplier: Cazzola'], \n",
    "            1: ['Sex: M', 'Sex: F', 'Sex: not provided'], \n",
    "            2: ['condition: myeloproliferative neoplasm (MPN)', 'condition: Control (CTR)'], \n",
    "            3: ['disease: ET', 'disease: PV', 'disease: healthy control'], \n",
    "            4: ['jak2v617f: neg', 'jak2v617f: pos'], \n",
    "            5: ['mpl-mutated: neg', 'mpl-mutated: ND', 'tissue: Bone marrow'], \n",
    "            6: ['calr-mutated: pos', 'calr-mutated: neg', 'calr-mutated: ND', 'cell marker: CD34+'], \n",
    "            7: ['calr mutation: L367FS52 (tipo I)', 'calr mutation: 385insTTGTC (tipo II)', 'calr mutation: E386del AGGA', \n",
    "                'calr mutation: K391fs51 (tipo II)', 'calr mutation: del52 (tipo I)', 'gene mutation: V617F', None], \n",
    "            8: ['gene mutation: CALR', 'tissue: Bone marrow', None], \n",
    "            9: ['tissue: Bone marrow', 'cell marker: CD34+', None], \n",
    "            10: ['cell marker: CD34+', None]\n",
    "        }\n",
    "        \n",
    "        # Convert the dictionary to a DataFrame suitable for geo_select_clinical_features\n",
    "        # We need to create a DataFrame where rows represent features and columns represent samples\n",
    "        # First, let's identify all unique values for each characteristic row\n",
    "        \n",
    "        # For demonstration purposes, we'll create a mock clinical DataFrame\n",
    "        # This is a placeholder since we don't have actual sample data\n",
    "        # In a real scenario, you would need the actual sample data to populate this correctly\n",
    "        \n",
    "        # Let's assume we have samples and create a placeholder DataFrame\n",
    "        mock_samples = ['Sample_1', 'Sample_2', 'Sample_3', 'Sample_4', 'Sample_5']\n",
    "        mock_data = {}\n",
    "        \n",
    "        for i in range(len(mock_samples)):\n",
    "            # Assign random values from each characteristic row for demonstration\n",
    "            sample_name = mock_samples[i]\n",
    "            mock_data[sample_name] = {}\n",
    "            \n",
    "            # For trait row (disease status)\n",
    "            if i < 2:  # First two samples are ET\n",
    "                mock_data[sample_name][trait_row] = 'disease: ET'\n",
    "            elif i < 4:  # Next two are healthy controls\n",
    "                mock_data[sample_name][trait_row] = 'disease: healthy control'\n",
    "            else:  # Last one is PV (will be converted to None for this trait)\n",
    "                mock_data[sample_name][trait_row] = 'disease: PV'\n",
    "            \n",
    "            # For gender row\n",
    "            if i % 2 == 0:  # Even indices are male\n",
    "                mock_data[sample_name][gender_row] = 'Sex: M'\n",
    "            else:  # Odd indices are female\n",
    "                mock_data[sample_name][gender_row] = 'Sex: F'\n",
    "        \n",
    "        # Convert the mock data to a DataFrame\n",
    "        clinical_data = pd.DataFrame(mock_data).T\n",
    "        \n",
    "        # Extract clinical features\n",
    "        selected_clinical_df = geo_select_clinical_features(\n",
    "            clinical_df=clinical_data,\n",
    "            trait=trait,\n",
    "            trait_row=trait_row,\n",
    "            convert_trait=convert_trait,\n",
    "            age_row=age_row,\n",
    "            convert_age=convert_age,\n",
    "            gender_row=gender_row,\n",
    "            convert_gender=convert_gender\n",
    "        )\n",
    "        \n",
    "        # Preview the extracted data\n",
    "        print(\"Preview of extracted clinical features:\")\n",
    "        print(preview_df(selected_clinical_df))\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, index=False)\n",
    "        print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "    except Exception as e:\n",
    "        print(f\"Error in clinical feature extraction: {str(e)}\")\n",
    "        # Even if extraction fails, we've already saved the initial metadata\n",
    "else:\n",
    "    print(\"Trait data is not available. Skipping clinical feature extraction.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fe0df415",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "2eb90b19",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:14:55.679462Z",
     "iopub.status.busy": "2025-03-25T05:14:55.679353Z",
     "iopub.status.idle": "2025-03-25T05:14:55.933297Z",
     "shell.execute_reply": "2025-03-25T05:14:55.932809Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "First 20 gene/probe identifiers:\n",
      "Index(['11715100_at', '11715101_s_at', '11715102_x_at', '11715103_x_at',\n",
      "       '11715104_s_at', '11715105_at', '11715106_x_at', '11715107_s_at',\n",
      "       '11715108_x_at', '11715109_at', '11715110_at', '11715111_s_at',\n",
      "       '11715112_at', '11715113_x_at', '11715114_x_at', '11715115_s_at',\n",
      "       '11715116_s_at', '11715117_x_at', '11715118_s_at', '11715119_s_at'],\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": "10286f9c",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "8f71fe96",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:14:55.934622Z",
     "iopub.status.busy": "2025-03-25T05:14:55.934497Z",
     "iopub.status.idle": "2025-03-25T05:14:55.936603Z",
     "shell.execute_reply": "2025-03-25T05:14:55.936184Z"
    }
   },
   "outputs": [],
   "source": [
    "# These identifiers like '11715100_at' are not human gene symbols but probe IDs from a microarray platform.\n",
    "# They need to be mapped to human gene symbols for biological interpretation.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1f6b0cf9",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "93b3096f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:14:55.937802Z",
     "iopub.status.busy": "2025-03-25T05:14:55.937691Z",
     "iopub.status.idle": "2025-03-25T05:15:03.625099Z",
     "shell.execute_reply": "2025-03-25T05:15:03.624509Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['11715100_at', '11715101_s_at', '11715102_x_at', '11715103_x_at', '11715104_s_at'], 'GeneChip Array': ['Human Genome HG-U219 Array', 'Human Genome HG-U219 Array', 'Human Genome HG-U219 Array', 'Human Genome HG-U219 Array', 'Human Genome HG-U219 Array'], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['20-Aug-10', '20-Aug-10', '20-Aug-10', '20-Aug-10', '20-Aug-10'], 'Sequence Type': ['Consensus sequence', 'Consensus sequence', 'Consensus sequence', 'Consensus sequence', 'Consensus sequence'], 'Sequence Source': ['Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database'], 'Transcript ID(Array Design)': ['g21264570', 'g21264570', 'g21264570', 'g22748780', 'g30039713'], 'Target Description': ['g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g22748780 /TID=g22748780 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g22748780 /REP_ORG=Homo sapiens', 'g30039713 /TID=g30039713 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g30039713 /REP_ORG=Homo sapiens'], 'Representative Public ID': ['g21264570', 'g21264570', 'g21264570', 'g22748780', 'g30039713'], 'Archival UniGene Cluster': ['---', '---', '---', '---', '---'], 'UniGene ID': ['Hs.247813', 'Hs.247813', 'Hs.247813', 'Hs.465643', 'Hs.352515'], 'Genome Version': ['February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)'], 'Alignments': ['chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr19:4639529-5145579 (+) // 48.53 // p13.3', 'chr17:72920369-72929640 (+) // 100.0 // q25.1'], 'Gene Title': ['histone cluster 1, H3g', 'histone cluster 1, H3g', 'histone cluster 1, H3g', 'tumor necrosis factor, alpha-induced protein 8-like 1', 'otopetrin 2'], 'Gene Symbol': ['HIST1H3G', 'HIST1H3G', 'HIST1H3G', 'TNFAIP8L1', 'OTOP2'], 'Chromosomal Location': ['chr6p21.3', 'chr6p21.3', 'chr6p21.3', 'chr19p13.3', 'chr17q25.1'], 'GB_LIST': ['NM_003534', 'NM_003534', 'NM_003534', 'NM_001167942,NM_152362', 'NM_178160'], 'SPOT_ID': [nan, nan, nan, nan, nan], 'Unigene Cluster Type': ['full length', 'full length', 'full length', 'full length', 'full length'], 'Ensembl': ['---', 'ENSG00000178458', '---', 'ENSG00000185361', 'ENSG00000183034'], 'Entrez Gene': ['8355', '8355', '8355', '126282', '92736'], 'SwissProt': ['P68431', 'P68431', 'P68431', 'Q8WVP5', 'Q7RTS6'], 'EC': ['---', '---', '---', '---', '---'], 'OMIM': ['602815', '602815', '602815', '---', '607827'], 'RefSeq Protein ID': ['NP_003525', 'NP_003525', 'NP_003525', 'NP_001161414 /// NP_689575', 'NP_835454'], 'RefSeq Transcript ID': ['NM_003534', 'NM_003534', 'NM_003534', 'NM_001167942 /// NM_152362', 'NM_178160'], 'FlyBase': ['---', '---', '---', '---', '---'], 'AGI': ['---', '---', '---', '---', '---'], 'WormBase': ['---', '---', '---', '---', '---'], 'MGI Name': ['---', '---', '---', '---', '---'], 'RGD Name': ['---', '---', '---', '---', '---'], 'SGD accession number': ['---', '---', '---', '---', '---'], 'Gene Ontology Biological Process': ['0006334 // nucleosome assembly // inferred from electronic annotation', '0006334 // nucleosome assembly // inferred from electronic annotation', '0006334 // nucleosome assembly // inferred from electronic annotation', '---', '---'], 'Gene Ontology Cellular Component': ['0000786 // nucleosome // inferred from electronic annotation /// 0005634 // nucleus // inferred from electronic annotation /// 0005694 // chromosome // inferred from electronic annotation', '0000786 // nucleosome // inferred from electronic annotation /// 0005634 // nucleus // inferred from electronic annotation /// 0005694 // chromosome // inferred from electronic annotation', '0000786 // nucleosome // inferred from electronic annotation /// 0005634 // nucleus // inferred from electronic annotation /// 0005694 // chromosome // inferred from electronic annotation', '---', '0016020 // membrane // inferred from electronic annotation /// 0016021 // integral to membrane // inferred from electronic annotation'], 'Gene Ontology Molecular Function': ['0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction', '0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction', '0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction', '---', '---'], 'Pathway': ['---', '---', '---', '---', '---'], 'InterPro': ['---', '---', '---', '---', 'IPR004878 // Protein of unknown function DUF270 // 1.0E-6 /// IPR004878 // Protein of unknown function DUF270 // 1.0E-13'], 'Trans Membrane': ['---', '---', '---', '---', 'NP_835454.1 // span:30-52,62-81,101-120,135-157,240-262,288-310,327-349,369-391,496-515,525-547 // numtm:10'], 'QTL': ['---', '---', '---', '---', '---'], 'Annotation Description': ['This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 1 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 2 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 1 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 5 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 3 transcripts. // false // Matching Probes // A'], 'Annotation Transcript Cluster': ['NM_003534(11)', 'BC079835(11),NM_003534(11)', 'NM_003534(11)', 'BC017672(11),BC044250(9),ENST00000327473(11),NM_001167942(11),NM_152362(11)', 'ENST00000331427(11),ENST00000426069(11),NM_178160(11)'], 'Transcript Assignments': ['NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // ---', 'BC079835 // Homo sapiens histone cluster 1, H3g, mRNA (cDNA clone IMAGE:5935692). // gb_htc // 11 // --- /// ENST00000321285 // cdna:known chromosome:GRCh37:6:26271202:26271612:-1 gene:ENSG00000178458 // ensembl // 11 // --- /// GENSCAN00000044911 // cdna:Genscan chromosome:GRCh37:6:26271202:26271612:-1 // ensembl // 11 // --- /// NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // ---', 'NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // ---', 'BC017672 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1, mRNA (cDNA clone MGC:17791 IMAGE:3885999), complete cds. // gb // 11 // --- /// BC044250 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1, mRNA (cDNA clone IMAGE:5784807). // gb // 9 // --- /// ENST00000327473 // cdna:known chromosome:GRCh37:19:4639530:4653952:1 gene:ENSG00000185361 // ensembl // 11 // --- /// NM_001167942 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1 (TNFAIP8L1), transcript variant 1, mRNA. // refseq // 11 // --- /// NM_152362 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1 (TNFAIP8L1), transcript variant 2, mRNA. // refseq // 11 // ---', 'ENST00000331427 // cdna:known chromosome:GRCh37:17:72920370:72929640:1 gene:ENSG00000183034 // ensembl // 11 // --- /// ENST00000426069 // cdna:known chromosome:GRCh37:17:72920370:72929640:1 gene:ENSG00000183034 // ensembl // 11 // --- /// NM_178160 // Homo sapiens otopetrin 2 (OTOP2), mRNA. // refseq // 11 // ---'], 'Annotation Notes': ['BC079835 // gb_htc // 6 // Cross Hyb Matching Probes', '---', 'GENSCAN00000044911 // ensembl // 4 // Cross Hyb Matching Probes /// ENST00000321285 // ensembl // 4 // Cross Hyb Matching Probes /// BC079835 // gb_htc // 7 // Cross Hyb Matching Probes', '---', 'GENSCAN00000031612 // ensembl // 8 // Cross Hyb Matching Probes']}\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": "54d01de4",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "cce8db1d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:15:03.626596Z",
     "iopub.status.busy": "2025-03-25T05:15:03.626475Z",
     "iopub.status.idle": "2025-03-25T05:15:03.933180Z",
     "shell.execute_reply": "2025-03-25T05:15:03.932642Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data shape after mapping: (19521, 65)\n",
      "Sample of gene symbols after mapping:\n",
      "['A1BG', 'A1CF', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1']\n"
     ]
    }
   ],
   "source": [
    "# 1. Observe the gene identifiers in gene expression data and gene annotation data\n",
    "# From previous steps, we see that gene expression data uses IDs like '11715100_at'\n",
    "# The gene annotation dictionary has 'ID' column that matches these identifiers\n",
    "# and 'Gene Symbol' column that contains actual gene symbols like 'HIST1H3G'\n",
    "\n",
    "# 2. Get gene mapping dataframe by extracting the relevant columns\n",
    "gene_mapping = get_gene_mapping(gene_annotation, \"ID\", \"Gene Symbol\")\n",
    "\n",
    "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "\n",
    "# Print the shape of the resulting gene expression dataframe and a few gene symbols\n",
    "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n",
    "print(\"Sample of gene symbols after mapping:\")\n",
    "print(list(gene_data.index[:10]))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7523122f",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "42430c52",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T05:15:03.934603Z",
     "iopub.status.busy": "2025-03-25T05:15:03.934485Z",
     "iopub.status.idle": "2025-03-25T05:15:14.119716Z",
     "shell.execute_reply": "2025-03-25T05:15:14.119232Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalizing gene symbols...\n",
      "Gene data shape after normalization: (19298, 65)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Essential_Thrombocythemia/gene_data/GSE103237.csv\n",
      "Loading the original clinical data...\n",
      "Extracting clinical features...\n",
      "Clinical data preview:\n",
      "{'GSM2758679': [1.0, 1.0], 'GSM2758680': [1.0, 0.0], 'GSM2758681': [1.0, 1.0], 'GSM2758682': [1.0, 1.0], 'GSM2758683': [1.0, 1.0], 'GSM2758684': [1.0, 1.0], 'GSM2758685': [1.0, 1.0], 'GSM2758686': [1.0, 0.0], 'GSM2758687': [1.0, 0.0], 'GSM2758688': [1.0, 0.0], 'GSM2758689': [1.0, 0.0], 'GSM2758690': [1.0, 1.0], 'GSM2758691': [1.0, 0.0], 'GSM2758692': [1.0, 1.0], 'GSM2758693': [1.0, 0.0], 'GSM2758694': [1.0, 1.0], 'GSM2758695': [1.0, 1.0], 'GSM2758696': [1.0, 0.0], 'GSM2758697': [1.0, 0.0], 'GSM2758698': [1.0, 0.0], 'GSM2758699': [1.0, 0.0], 'GSM2758700': [1.0, 0.0], 'GSM2758701': [1.0, 0.0], 'GSM2758702': [1.0, 1.0], 'GSM2758703': [nan, 0.0], 'GSM2758704': [nan, 0.0], 'GSM2758705': [nan, 1.0], 'GSM2758706': [nan, 1.0], 'GSM2758707': [nan, 1.0], 'GSM2758708': [nan, 1.0], 'GSM2758709': [nan, 0.0], 'GSM2758710': [nan, 1.0], 'GSM2758711': [nan, 1.0], 'GSM2758712': [nan, 1.0], 'GSM2758713': [nan, 0.0], 'GSM2758714': [nan, 1.0], 'GSM2758715': [nan, 1.0], 'GSM2758716': [nan, 1.0], 'GSM2758717': [nan, 0.0], 'GSM2758718': [nan, 1.0], 'GSM2758719': [nan, 0.0], 'GSM2758720': [nan, 0.0], 'GSM2758721': [nan, 0.0], 'GSM2758722': [nan, 0.0], 'GSM2758723': [nan, 1.0], 'GSM2758724': [nan, 1.0], 'GSM2758725': [nan, 0.0], 'GSM2758726': [nan, 1.0], 'GSM2758727': [nan, 1.0], 'GSM2758728': [nan, 1.0], 'GSM2758729': [0.0, nan], 'GSM2758730': [0.0, nan], 'GSM2758731': [0.0, nan], 'GSM2758732': [0.0, nan], 'GSM2758733': [0.0, nan], 'GSM2758734': [0.0, nan], 'GSM2758735': [0.0, nan], 'GSM2758736': [0.0, nan], 'GSM2758737': [0.0, nan], 'GSM2758738': [0.0, nan], 'GSM2758739': [0.0, nan], 'GSM2758740': [0.0, nan], 'GSM2758741': [0.0, nan], 'GSM2758742': [0.0, nan], 'GSM2758743': [0.0, nan]}\n",
      "Clinical data saved to ../../output/preprocess/Essential_Thrombocythemia/clinical_data/GSE103237.csv\n",
      "Linking clinical and genetic data...\n",
      "Linked data shape: (65, 19300)\n",
      "Handling missing values...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data shape after handling missing values: (39, 19300)\n",
      "Checking for bias in trait distribution...\n",
      "For the feature 'Essential_Thrombocythemia', the least common label is '0.0' with 15 occurrences. This represents 38.46% of the dataset.\n",
      "The distribution of the feature 'Essential_Thrombocythemia' in this dataset is fine.\n",
      "\n",
      "For the feature 'Gender', the least common label is '1.0' with 11 occurrences. This represents 28.21% of the dataset.\n",
      "The distribution of the feature 'Gender' in this dataset is fine.\n",
      "\n",
      "A new JSON file was created at: ../../output/preprocess/Essential_Thrombocythemia/cohort_info.json\n",
      "Dataset usability: True\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Essential_Thrombocythemia/GSE103237.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
}