File size: 29,502 Bytes
f88156f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "726c02be",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:14:01.525445Z",
     "iopub.status.busy": "2025-03-25T08:14:01.525252Z",
     "iopub.status.idle": "2025-03-25T08:14:01.689714Z",
     "shell.execute_reply": "2025-03-25T08:14:01.689354Z"
    }
   },
   "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 = \"Cervical_Cancer\"\n",
    "cohort = \"GSE146114\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Cervical_Cancer\"\n",
    "in_cohort_dir = \"../../input/GEO/Cervical_Cancer/GSE146114\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Cervical_Cancer/GSE146114.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Cervical_Cancer/gene_data/GSE146114.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Cervical_Cancer/clinical_data/GSE146114.csv\"\n",
    "json_path = \"../../output/preprocess/Cervical_Cancer/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0cf9a872",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "85a24119",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:14:01.690924Z",
     "iopub.status.busy": "2025-03-25T08:14:01.690784Z",
     "iopub.status.idle": "2025-03-25T08:14:01.854742Z",
     "shell.execute_reply": "2025-03-25T08:14:01.854383Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Combining imaging- and gene-based hypoxia biomarkers in cervical cancer improves prediction of treatment failure independent of intratumor heterogeneity\"\n",
      "!Series_summary\t\"Emerging biomarkers based on medical images and molecular characterization of tumor biopsies open up for combining the two disciplines and exploiting their synergy in treatment planning. We compared pretreatment classification of cervical cancer patients by two previously validated imaging- and gene-based hypoxia biomarkers, evaluated the influence of intratumor heterogeneity, and investigated the benefit of combining them in prediction of treatment failure. The imaging-based biomarker was hypoxic fraction, determined from diagnostic dynamic contrast enhanced (DCE)-MR images. The gene-based biomarker was a hypoxia gene expression signature determined from tumor biopsies. Paired data were available for 118 patients. Intratumor heterogeneity was assessed by variance analysis of MR images and multiple biopsies from the same tumor. The two biomarkers were combined using a dimension-reduction procedure. The biomarkers classified 75% of the tumors with the same hypoxia status. Both intratumor heterogeneity and distribution pattern of hypoxia from imaging were unrelated to inconsistent classification by the two biomarkers, and the hypoxia status of the slice covering the biopsy region was representative of the whole tumor. Hypoxia by genes was independent on tumor cell fraction and showed minor heterogeneity across multiple biopsies in 9 tumors. This suggested that the two biomarkers could contain complementary biological information. Combination of the biomarkers into a composite score led to improved prediction of treatment failure (HR:7.3) compared to imaging (HR:3.8) and genes (HR:3.0) and prognostic impact in multivariate analysis with clinical variables.  In conclusion, combining imaging- and gene-based biomarkers enables more precise and informative assessment of hypoxia-related treatment resistance in cervical cancer, independent of intratumor heterogeneity.\"\n",
      "!Series_overall_design\t\"Totally 118 samples using pooled RNA isolated from 1-4 biopsies (median 2) per tumor were analysed; 84 with Illumina WG-6 v3 and 34 with Illumina HT-12 v4. In addition, each of 2-4 biopsies in nine tumors (24 samples in total) were analyzed with Illumina HT-12 v4.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['histology: Squamous cell carcinoma', 'histology: Adenocarcinom', 'histology: Adenosquamous'], 1: ['gene-based hypoxia: Less hypoxic', 'gene-based hypoxia: More hypoxic'], 2: ['imaging-based hypoxia: Less hypoxic', 'imaging-based hypoxia: More hypoxic'], 3: ['combined hypoxia biomarker: Less hypoxic', 'combined hypoxia biomarker: More hypoxic', 'combined hypoxia biomarker: NA'], 4: ['figo stage: 2B', 'figo stage: 3B', 'figo stage: 1B1', 'figo stage: 2A'], 5: ['hypoxia classifier: Less hypoxic', 'hypoxia classifier: More hypoxic', 'rna isolation method: Trizol', 'rna isolation method: miRNeasy'], 6: ['cohort: Cohort 2', 'cohort: Adeno', 'biopsy: Single biopsy']}\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": "94a5f3bf",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "05731bfc",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:14:01.855985Z",
     "iopub.status.busy": "2025-03-25T08:14:01.855847Z",
     "iopub.status.idle": "2025-03-25T08:14:01.879880Z",
     "shell.execute_reply": "2025-03-25T08:14:01.879600Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of selected clinical features:\n",
      "{'Sample_1': [1.0], 'Sample_2': [0.0], 'Sample_3': [nan], 'Sample_4': [nan], 'Sample_5': [nan], 'Sample_6': [nan], 'Sample_7': [nan], 'Sample_8': [nan], 'Sample_9': [nan]}\n",
      "Clinical data saved to ../../output/preprocess/Cervical_Cancer/clinical_data/GSE146114.csv\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import os\n",
    "from typing import Optional, Dict, Any, Callable\n",
    "import json\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# From the background information, we know this is a gene expression dataset\n",
    "# The background mentions Illumina WG-6 v3 and Illumina HT-12 v4 which are gene expression platforms\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "\n",
    "# For trait (Cervical Cancer)\n",
    "# The key value 1 contains gene-based hypoxia status which is a binary trait related to cervical cancer hypoxia\n",
    "trait_row = 1\n",
    "\n",
    "# For age\n",
    "# There is no age information in the sample characteristics\n",
    "age_row = None\n",
    "\n",
    "# For gender\n",
    "# All patients are female (cervical cancer patients), but gender is not explicitly mentioned\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait value to binary (0 or 1)\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Convert based on hypoxia status\n",
    "    if 'less hypoxic' in value.lower():\n",
    "        return 0  # Less hypoxic\n",
    "    elif 'more hypoxic' in value.lower():\n",
    "        return 1  # More hypoxic\n",
    "    else:\n",
    "        return None  # Unknown or invalid value\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age value to continuous\"\"\"\n",
    "    # No age data available\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender value to binary (0 for female, 1 for male)\"\"\"\n",
    "    # No gender data available\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Initial validation - check if both gene and trait data are available\n",
    "is_trait_available = trait_row is not None\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. Clinical Feature Extraction\n",
    "if trait_row is not None:\n",
    "    # Create a dataframe from the sample characteristics dictionary provided in the previous step\n",
    "    # The sample characteristics dictionary contains the relevant clinical information\n",
    "    # Sample characteristics were provided in the previous step output\n",
    "    sample_char_dict = {0: ['histology: Squamous cell carcinoma', 'histology: Adenosquamous'], \n",
    "                        1: ['gene-based hypoxia: More hypoxic', 'gene-based hypoxia: Less hypoxic'], \n",
    "                        2: ['imaging-based hypoxia: Less hypoxic', 'imaging-based hypoxia: More hypoxic'], \n",
    "                        3: ['combined hypoxia biomarker: More hypoxic', 'combined hypoxia biomarker: Less hypoxic'], \n",
    "                        4: ['cohort (gse36562 study): DCE-MRI cohort', 'tissue: cervical tumor', 'cohort (gse36562 study): Validation cohort', 'figo stage: 2B'], \n",
    "                        5: ['hypoxia score: High', 'hypoxia score: Low', 'figo stage: 2B', 'figo stage: 3B', 'rna isolation method: Trizol'], \n",
    "                        6: ['tissue: cervical tumor', 'cohort (gse36562 study): DCE-MRI cohort', 'biopsy: Pooled biopsies'], \n",
    "                        7: ['figo stage: 2B', 'figo stage: 3B', 'hypoxia score: Low', 'figo stage: 4A', 'figo stage: 3A', 'figo stage: 1B1', 'figo stage: 2A', 'figo stage: 1B2', np.nan], \n",
    "                        8: ['cohort: Validation cohort', 'cohort: basic cohort', np.nan], \n",
    "                        9: ['cohort (gse38964 study): Integrative cohort', 'lymph node status (gse38433 study): 1', np.nan, 'lymph node status (gse38433 study): 0', 'cohort (gse38964 study): Validation cohort'], \n",
    "                        10: ['3p status: Loss', 'cohort (gse38964 study): Integrative cohort', np.nan, '3p status: No loss', 'cohort (gse38964 study): Validation cohort', '3p status: Not determined'], \n",
    "                        11: [np.nan, '3p status: Loss', '3p status: No loss', '3p status: Not determined']}\n",
    "    \n",
    "    # Create a dataframe with the sample characteristics dictionary\n",
    "    # The index will be the row numbers, and columns will be sample IDs (we'll create dummy IDs)\n",
    "    max_samples = max(len(features) for features in sample_char_dict.values())\n",
    "    sample_ids = [f\"Sample_{i+1}\" for i in range(max_samples)]\n",
    "    \n",
    "    clinical_data = pd.DataFrame(index=sample_char_dict.keys(), columns=sample_ids)\n",
    "    \n",
    "    # Fill the dataframe with the sample characteristics\n",
    "    for row, features in sample_char_dict.items():\n",
    "        for col, feature in enumerate(features):\n",
    "            if col < len(sample_ids):\n",
    "                clinical_data.loc[row, sample_ids[col]] = feature\n",
    "    \n",
    "    # Use geo_select_clinical_features to 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 selected clinical features\n",
    "    preview = preview_df(selected_clinical_df)\n",
    "    print(\"Preview of selected clinical features:\")\n",
    "    print(preview)\n",
    "    \n",
    "    # Save the selected clinical features to the output 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"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b8a30856",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "a82ece09",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:14:01.880920Z",
     "iopub.status.busy": "2025-03-25T08:14:01.880814Z",
     "iopub.status.idle": "2025-03-25T08:14:02.130358Z",
     "shell.execute_reply": "2025-03-25T08:14:02.129918Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209',\n",
      "       'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229',\n",
      "       'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236',\n",
      "       'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253',\n",
      "       'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262'],\n",
      "      dtype='object', name='ID')\n"
     ]
    }
   ],
   "source": [
    "# 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.\n",
    "gene_data = get_genetic_data(matrix_file)\n",
    "\n",
    "# 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.\n",
    "print(gene_data.index[:20])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eab42279",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "6c438850",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:14:02.132068Z",
     "iopub.status.busy": "2025-03-25T08:14:02.131890Z",
     "iopub.status.idle": "2025-03-25T08:14:02.133724Z",
     "shell.execute_reply": "2025-03-25T08:14:02.133440Z"
    }
   },
   "outputs": [],
   "source": [
    "# These identifiers are Illumina probe IDs (ILMN_*), not human gene symbols. \n",
    "# They need to be mapped to standard gene symbols for meaningful analysis.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dc40c6d2",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "57febdc9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:14:02.135258Z",
     "iopub.status.busy": "2025-03-25T08:14:02.135128Z",
     "iopub.status.idle": "2025-03-25T08:14:15.042213Z",
     "shell.execute_reply": "2025-03-25T08:14:15.041847Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['ILMN_1825594', 'ILMN_1810803', 'ILMN_1722532', 'ILMN_1884413', 'ILMN_1906034'], 'Species': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Source': ['Unigene', 'RefSeq', 'RefSeq', 'Unigene', 'Unigene'], 'Search_Key': ['ILMN_89282', 'ILMN_35826', 'ILMN_25544', 'ILMN_132331', 'ILMN_105017'], 'Transcript': ['ILMN_89282', 'ILMN_35826', 'ILMN_25544', 'ILMN_132331', 'ILMN_105017'], 'ILMN_Gene': ['HS.388528', 'LOC441782', 'JMJD1A', 'HS.580150', 'HS.540210'], 'Source_Reference_ID': ['Hs.388528', 'XM_497527.2', 'NM_018433.3', 'Hs.580150', 'Hs.540210'], 'RefSeq_ID': [nan, 'XM_497527.2', 'NM_018433.3', nan, nan], 'Unigene_ID': ['Hs.388528', nan, nan, 'Hs.580150', 'Hs.540210'], 'Entrez_Gene_ID': [nan, 441782.0, 55818.0, nan, nan], 'GI': [23525203.0, 89042416.0, 46358420.0, 7376124.0, 5437312.0], 'Accession': ['BU678343', 'XM_497527.2', 'NM_018433.3', 'AW629334', 'AI818233'], 'Symbol': [nan, 'LOC441782', 'JMJD1A', nan, nan], 'Protein_Product': [nan, 'XP_497527.2', 'NP_060903.2', nan, nan], 'Array_Address_Id': [1740241.0, 1850750.0, 1240504.0, 4050487.0, 2190598.0], 'Probe_Type': ['S', 'S', 'S', 'S', 'S'], 'Probe_Start': [349.0, 902.0, 4359.0, 117.0, 304.0], 'SEQUENCE': ['CTCTCTAAAGGGACAACAGAGTGGACAGTCAAGGAACTCCACATATTCAT', 'GGGGTCAAGCCCAGGTGAAATGTGGATTGGAAAAGTGCTTCCCTTGCCCC', 'CCAGGCTGTAAAAGCAAAACCTCGTATCAGCTCTGGAACAATACCTGCAG', 'CCAGACAGGAAGCATCAAGCCCTTCAGGAAAGAATATGCGAGAGTGCTGC', 'TGTGCAGAAAGCTGATGGAAGGGAGAAAGAATGGAAGTGGGTCACACAGC'], 'Chromosome': [nan, nan, '2', nan, nan], 'Probe_Chr_Orientation': [nan, nan, '+', nan, nan], 'Probe_Coordinates': [nan, nan, '86572991-86573040', nan, nan], 'Cytoband': [nan, nan, '2p11.2e', nan, nan], 'Definition': ['UI-CF-EC0-abi-c-12-0-UI.s1 UI-CF-EC0 Homo sapiens cDNA clone UI-CF-EC0-abi-c-12-0-UI 3, mRNA sequence', 'PREDICTED: Homo sapiens similar to spectrin domain with coiled-coils 1 (LOC441782), mRNA.', 'Homo sapiens jumonji domain containing 1A (JMJD1A), mRNA.', 'hi56g05.x1 Soares_NFL_T_GBC_S1 Homo sapiens cDNA clone IMAGE:2976344 3, mRNA sequence', 'wk77d04.x1 NCI_CGAP_Pan1 Homo sapiens cDNA clone IMAGE:2421415 3, mRNA sequence'], 'Ontology_Component': [nan, nan, 'nucleus [goid 5634] [evidence IEA]', nan, nan], 'Ontology_Process': [nan, nan, 'chromatin modification [goid 16568] [evidence IEA]; transcription [goid 6350] [evidence IEA]; regulation of transcription, DNA-dependent [goid 6355] [evidence IEA]', nan, nan], 'Ontology_Function': [nan, nan, 'oxidoreductase activity [goid 16491] [evidence IEA]; oxidoreductase activity, acting on single donors with incorporation of molecular oxygen, incorporation of two atoms of oxygen [goid 16702] [evidence IEA]; zinc ion binding [goid 8270] [evidence IEA]; metal ion binding [goid 46872] [evidence IEA]; iron ion binding [goid 5506] [evidence IEA]', nan, nan], 'Synonyms': [nan, nan, 'JHMD2A; JMJD1; TSGA; KIAA0742; DKFZp686A24246; DKFZp686P07111', nan, nan], 'GB_ACC': ['BU678343', 'XM_497527.2', 'NM_018433.3', 'AW629334', 'AI818233']}\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": "1fc79ff3",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "6b88fc77",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:14:15.043645Z",
     "iopub.status.busy": "2025-03-25T08:14:15.043532Z",
     "iopub.status.idle": "2025-03-25T08:14:15.451623Z",
     "shell.execute_reply": "2025-03-25T08:14:15.451244Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Mapped gene expression data shape: (18838, 58)\n",
      "First few gene symbols:\n",
      "Index(['A1BG', 'A2BP1', 'A2M', 'A2ML1', 'A3GALT2'], dtype='object', name='Gene')\n"
     ]
    }
   ],
   "source": [
    "# 1. Determine which columns in gene_annotation store identifiers and gene symbols\n",
    "# After examining the preview, we can see that:\n",
    "# 'ID' column contains the Illumina probe IDs (ILMN_*) matching the gene_data index\n",
    "# 'Symbol' column contains the gene symbols we need to map to\n",
    "\n",
    "# 2. Get gene mapping dataframe using the two relevant columns\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n",
    "\n",
    "# 3. Apply gene mapping to convert probe measurements to gene expression data\n",
    "# This handles the many-to-many relationship between probes and genes\n",
    "# If a probe maps to multiple genes, its expression is divided equally among those genes\n",
    "# Then values for each gene are summed across all contributing probes\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "\n",
    "# Print the shape of the new gene expression dataframe\n",
    "print(f\"Mapped gene expression data shape: {gene_data.shape}\")\n",
    "# Print the first few gene symbols to confirm successful mapping\n",
    "print(\"First few gene symbols:\")\n",
    "print(gene_data.index[:5])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "08d9fb72",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "c5d91eaf",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:14:15.452928Z",
     "iopub.status.busy": "2025-03-25T08:14:15.452823Z",
     "iopub.status.idle": "2025-03-25T08:14:24.440339Z",
     "shell.execute_reply": "2025-03-25T08:14:24.439588Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Cervical_Cancer/gene_data/GSE146114.csv\n",
      "Clinical data saved to ../../output/preprocess/Cervical_Cancer/clinical_data/GSE146114.csv\n",
      "Gene data samples: Index(['GSM1868975', 'GSM1868976', 'GSM1868977', 'GSM1868978', 'GSM1868979'], dtype='object') ...\n",
      "Clinical data samples: Index(['GSM1868975', 'GSM1868976', 'GSM1868977', 'GSM1868978', 'GSM1868979'], dtype='object') ...\n",
      "Number of common samples: 58\n",
      "Linked data shape: (58, 17552)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data shape after handling missing values: (58, 17552)\n",
      "For the feature 'Cervical_Cancer', the least common label is '1.0' with 13 occurrences. This represents 22.41% of the dataset.\n",
      "The distribution of the feature 'Cervical_Cancer' in this dataset is fine.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Cervical_Cancer/GSE146114.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.\n",
    "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "normalized_gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
    "\n",
    "# Re-extract clinical data directly from the source file to get proper sample IDs\n",
    "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n",
    "\n",
    "# Define the conversion function for the trait (gene-based hypoxia)\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait value to binary (0 or 1)\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Convert based on hypoxia status\n",
    "    if 'less hypoxic' in value.lower():\n",
    "        return 0  # Less hypoxic\n",
    "    elif 'more hypoxic' in value.lower():\n",
    "        return 1  # More hypoxic\n",
    "    else:\n",
    "        return None  # Unknown or invalid value\n",
    "\n",
    "# Extract clinical features with proper sample IDs\n",
    "selected_clinical_df = geo_select_clinical_features(\n",
    "    clinical_df=clinical_data,\n",
    "    trait=trait,\n",
    "    trait_row=1,  # Row 1 contains gene-based hypoxia information\n",
    "    convert_trait=convert_trait\n",
    ")\n",
    "\n",
    "# Save the correctly formatted clinical data\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",
    "# Print sample IDs from both datasets for diagnostic purposes\n",
    "print(\"Gene data samples:\", normalized_gene_data.columns[:5], \"...\")\n",
    "print(\"Clinical data samples:\", selected_clinical_df.columns[:5], \"...\")\n",
    "\n",
    "# Find common samples between the datasets\n",
    "common_samples = set(normalized_gene_data.columns).intersection(set(selected_clinical_df.columns))\n",
    "print(f\"Number of common samples: {len(common_samples)}\")\n",
    "\n",
    "if len(common_samples) > 0:\n",
    "    # Filter both datasets to only include common samples\n",
    "    normalized_gene_data = normalized_gene_data[list(common_samples)]\n",
    "    selected_clinical_df = selected_clinical_df[list(common_samples)]\n",
    "    \n",
    "    # Now link the clinical and genetic data\n",
    "    linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n",
    "    print(\"Linked data shape:\", linked_data.shape)\n",
    "    \n",
    "    # Handle missing values in the linked data\n",
    "    linked_data = handle_missing_values(linked_data, trait)\n",
    "    print(\"Linked data shape after handling missing values:\", linked_data.shape)\n",
    "    \n",
    "    if linked_data.shape[0] > 0:\n",
    "        # 4. Determine whether the trait and some demographic features are severely biased\n",
    "        is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "        \n",
    "        # 5. Conduct quality check and save the cohort information\n",
    "        is_usable = validate_and_save_cohort_info(\n",
    "            is_final=True, \n",
    "            cohort=cohort, \n",
    "            info_path=json_path, \n",
    "            is_gene_available=True, \n",
    "            is_trait_available=True, \n",
    "            is_biased=is_trait_biased, \n",
    "            df=unbiased_linked_data,\n",
    "            note=\"Study on hypoxia biomarkers in cervical cancer patients. Trait is gene-based hypoxic status.\"\n",
    "        )\n",
    "        \n",
    "        # 6. If the linked data is usable, save it as a CSV file\n",
    "        if is_usable:\n",
    "            os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "            unbiased_linked_data.to_csv(out_data_file)\n",
    "            print(f\"Linked data saved to {out_data_file}\")\n",
    "        else:\n",
    "            print(\"Data was determined to be unusable and was not saved\")\n",
    "    else:\n",
    "        print(\"No samples remained after handling missing values. Dataset is unusable.\")\n",
    "        validate_and_save_cohort_info(\n",
    "            is_final=True, \n",
    "            cohort=cohort, \n",
    "            info_path=json_path, \n",
    "            is_gene_available=True, \n",
    "            is_trait_available=True, \n",
    "            is_biased=True,  # We consider empty datasets as biased\n",
    "            df=pd.DataFrame(),\n",
    "            note=\"All samples were filtered out due to missing trait values or excessive missing genes.\"\n",
    "        )\n",
    "else:\n",
    "    print(\"No common samples between clinical and gene expression data. Cannot create linked dataset.\")\n",
    "    validate_and_save_cohort_info(\n",
    "        is_final=True, \n",
    "        cohort=cohort, \n",
    "        info_path=json_path, \n",
    "        is_gene_available=True, \n",
    "        is_trait_available=True, \n",
    "        is_biased=True,  # We consider datasets with no overlap as biased\n",
    "        df=pd.DataFrame(),\n",
    "        note=\"No overlapping samples between clinical and gene expression data.\"\n",
    "    )"
   ]
  }
 ],
 "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
}