File size: 27,289 Bytes
6bc7e45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "5679771c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:23:28.301110Z",
     "iopub.status.busy": "2025-03-25T06:23:28.300883Z",
     "iopub.status.idle": "2025-03-25T06:23:28.460622Z",
     "shell.execute_reply": "2025-03-25T06:23:28.460278Z"
    }
   },
   "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 = \"Allergies\"\n",
    "cohort = \"GSE192454\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Allergies\"\n",
    "in_cohort_dir = \"../../input/GEO/Allergies/GSE192454\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Allergies/GSE192454.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Allergies/gene_data/GSE192454.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Allergies/clinical_data/GSE192454.csv\"\n",
    "json_path = \"../../output/preprocess/Allergies/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5e1a3cf7",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "f25c1f80",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:23:28.462008Z",
     "iopub.status.busy": "2025-03-25T06:23:28.461862Z",
     "iopub.status.idle": "2025-03-25T06:23:28.573539Z",
     "shell.execute_reply": "2025-03-25T06:23:28.573241Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Host cellular and immune responses in models of inflammatory skin conditions\"\n",
      "!Series_summary\t\"Skin colonisation of varied communities of commensal microorganisms, such as Staphylococcus aureus (SA), Staphylococcus epidermidis (SE) and Staphylococcus capitis (SC) form the microbiome; a necessity for healthy skin. The skin changes characteristic of atopic dermatitis, a common inflammatory skin disease, have been shown to provide a favourable niche for SA colonisation. We utilised a reconstructed human epidermal (RHE) model recapitulating the stratified anatomy of the epidermis on which to test host responses to bacterial colonisation. SA proliferation was significantly inhibited in contrast to that seen with SE at both high and low colonisation loads after 24 hours. These data strongly suggest species specific regulation of staphylococcal growth, which is partially mediated by interaction with the epidermis.\"\n",
      "!Series_overall_design\t\"Confluent monolayer primary keratinocyte cultures were used to seed and establish reconstituted human epideris models after 13-15 days of growth within cell culture inserts at the air-liquid interface. Approximate absolute numbers of 10^6 CFU of bacteria were used per model for the challenge protocol. Models were challeged with either S. aureus (ATCC 29213 or NCTC-8325-4), S. epidermidis (ATCC 12228) or S. capitis (ATCC 27840). The challenge protocol consisted of an intial three hour incubation, at which point the 3-hour samples were collected, the 24-hour samples were then treated by PBS washing and further incubation of 21 hours. Subsequently models underwent trypsinisation and lysis for RNA extraction and whole transcriptome profiline by microarray. S. aureus ATCC 29213 proved destructive to models at 24h so data are not avialble for this strain at this timepoint. All three and 24 hour time points were conducted in triplicate or quadruplicate, while only a single unchallenged baseline sample was used for comparisons.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['tissue_type: reconsituted human epidermis (RHE)'], 1: ['bacterial_challenge: Control', 'bacterial_challenge: S. aureus NCTC-8325-4', 'bacterial_challenge: S. capitis ATCC 27840', 'bacterial_challenge: S. aureus ATCC 29213 (NCTC 12973)', 'bacterial_challenge: S. epidermidis ATCC 12228'], 2: ['challenge_time_course_hours: 0', 'challenge_time_course_hours: 3', 'challenge_time_course_hours: 24'], 3: ['batch_date: 180817', 'batch_date: 80917', 'batch_date: 220917', 'batch_date: 280917'], 4: ['array_id: 12342', 'array_id: 12343', 'array_id: 12344', 'array_id: 14525', 'array_id: 14526', 'array_id: 14527', 'array_id: 14576']}\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": "093f20aa",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "9131301b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:23:28.574747Z",
     "iopub.status.busy": "2025-03-25T06:23:28.574643Z",
     "iopub.status.idle": "2025-03-25T06:23:28.645263Z",
     "shell.execute_reply": "2025-03-25T06:23:28.644937Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of clinical features:\n",
      "{'GSM5747314': [0.0], 'GSM5747315': [1.0], 'GSM5747316': [1.0], 'GSM5747317': [1.0], 'GSM5747318': [0.0], 'GSM5747319': [1.0], 'GSM5747320': [0.0], 'GSM5747321': [1.0], 'GSM5747322': [1.0], 'GSM5747323': [1.0], 'GSM5747324': [1.0], 'GSM5747325': [1.0], 'GSM5747326': [0.0], 'GSM5747327': [1.0], 'GSM5747328': [1.0], 'GSM5747329': [1.0], 'GSM5747330': [1.0], 'GSM5747331': [1.0], 'GSM5747332': [0.0], 'GSM5747333': [1.0], 'GSM5747334': [0.0], 'GSM5747335': [1.0], 'GSM5747336': [1.0], 'GSM5747337': [1.0], 'GSM5747338': [1.0], 'GSM5747339': [0.0], 'GSM5747340': [1.0], 'GSM5747341': [1.0], 'GSM5747342': [1.0], 'GSM5747343': [1.0], 'GSM5747344': [0.0], 'GSM5747345': [1.0]}\n",
      "Clinical features saved to ../../output/preprocess/Allergies/clinical_data/GSE192454.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Based on background information, this dataset contains gene expression data from microarray analysis\n",
    "# of reconstructed human epidermal (RHE) models, so it's likely to contain gene expression data.\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "\n",
    "# Trait (Allergies):\n",
    "# From sample characteristics, we can use 'bacterial_challenge' (index 1) as the trait row\n",
    "# since we're studying allergies and bacterial colonization is related to skin conditions\n",
    "# like atopic dermatitis (an allergic condition)\n",
    "trait_row = 1\n",
    "\n",
    "# Age: Not available in the dataset\n",
    "age_row = None\n",
    "\n",
    "# Gender: Not available in the dataset\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "def convert_trait(value: str) -> int:\n",
    "    \"\"\"\n",
    "    Convert bacterial challenge information to binary trait values.\n",
    "    1 = bacterial challenge (potential allergen/inflammatory trigger)\n",
    "    0 = control (no bacterial challenge)\n",
    "    \"\"\"\n",
    "    if value is None or pd.isna(value) or \":\" not in value:\n",
    "        return None\n",
    "    \n",
    "    val = value.split(\":\", 1)[1].strip().lower()\n",
    "    \n",
    "    if \"control\" in val:\n",
    "        return 0\n",
    "    elif any(bacteria in val for bacteria in [\"s. aureus\", \"s. capitis\", \"s. epidermidis\"]):\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value: str) -> float:\n",
    "    \"\"\"Placeholder function for age conversion, not used in this dataset.\"\"\"\n",
    "    return None\n",
    "\n",
    "def convert_gender(value: str) -> int:\n",
    "    \"\"\"Placeholder function for gender conversion, not used in this dataset.\"\"\"\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Trait data is available (trait_row = 1), set is_trait_available to True\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Validate and save cohort info\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",
    "# Since trait_row is not None, we need to extract clinical features\n",
    "if trait_row is not None:\n",
    "    try:\n",
    "        # The clinical data is likely already loaded in a previous step\n",
    "        # and might be available in the variable 'clinical_data'\n",
    "        # If not, load from the appropriate source\n",
    "        if 'clinical_data' not in locals() or 'clinical_data' not in globals():\n",
    "            # Assuming clinical_data is available as a variable from previous steps\n",
    "            # If not, try to load it from the expected format\n",
    "            try:\n",
    "                clinical_data_path = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n",
    "                if os.path.exists(clinical_data_path):\n",
    "                    clinical_data = pd.read_csv(clinical_data_path)\n",
    "                else:\n",
    "                    # If CSV doesn't exist, use the sample characteristics data that was shown in previous output\n",
    "                    # Create a DataFrame from the sample characteristics dictionary\n",
    "                    sample_chars = {\n",
    "                        0: ['tissue_type: reconsituted human epidermis (RHE)'],\n",
    "                        1: ['bacterial_challenge: Control', 'bacterial_challenge: S. aureus NCTC-8325-4', \n",
    "                            'bacterial_challenge: S. capitis ATCC 27840', \n",
    "                            'bacterial_challenge: S. aureus ATCC 29213 (NCTC 12973)', \n",
    "                            'bacterial_challenge: S. epidermidis ATCC 12228'],\n",
    "                        2: ['challenge_time_course_hours: 0', 'challenge_time_course_hours: 3', \n",
    "                            'challenge_time_course_hours: 24'],\n",
    "                        3: ['batch_date: 180817', 'batch_date: 80917', 'batch_date: 220917', 'batch_date: 280917'],\n",
    "                        4: ['array_id: 12342', 'array_id: 12343', 'array_id: 12344', 'array_id: 14525', \n",
    "                            'array_id: 14526', 'array_id: 14527', 'array_id: 14576']\n",
    "                    }\n",
    "                    # Create a DataFrame from the sample characteristics\n",
    "                    clinical_data = pd.DataFrame({\n",
    "                        'key': list(sample_chars.keys()),\n",
    "                        'value': [sample_chars[k] for k in sample_chars.keys()]\n",
    "                    })\n",
    "            except Exception as e:\n",
    "                print(f\"Error loading clinical data: {e}\")\n",
    "                clinical_data = None\n",
    "        \n",
    "        if clinical_data 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 features\n",
    "            print(\"Preview of clinical features:\")\n",
    "            print(preview_df(clinical_features))\n",
    "            \n",
    "            # Save clinical features to CSV\n",
    "            os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "            clinical_features.to_csv(out_clinical_data_file)\n",
    "            print(f\"Clinical features saved to {out_clinical_data_file}\")\n",
    "        else:\n",
    "            print(\"No clinical data available for processing.\")\n",
    "    except Exception as e:\n",
    "        print(f\"Error processing clinical data: {e}\")\n",
    "        print(\"Continuing with processing without clinical features...\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9a538dae",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "761fb363",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:23:28.646368Z",
     "iopub.status.busy": "2025-03-25T06:23:28.646264Z",
     "iopub.status.idle": "2025-03-25T06:23:28.773902Z",
     "shell.execute_reply": "2025-03-25T06:23:28.773544Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "First 20 gene/probe identifiers:\n",
      "Index(['5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '17', '18',\n",
      "       '19', '20', '21', '22', '23', '24', '25'],\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": "688a2b5e",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "0420d5db",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:23:28.775170Z",
     "iopub.status.busy": "2025-03-25T06:23:28.775054Z",
     "iopub.status.idle": "2025-03-25T06:23:28.776894Z",
     "shell.execute_reply": "2025-03-25T06:23:28.776633Z"
    }
   },
   "outputs": [],
   "source": [
    "# The gene identifiers shown are simply numbers (5, 6, 7, 8, etc.)\n",
    "# These are not standard human gene symbols, which are typically alphabetic \n",
    "# characters (like BRCA1, TP53, etc.) or alphanumeric combinations\n",
    "# These appear to be probe IDs or some other identifiers that would need mapping\n",
    "# to standard gene symbols for meaningful biological interpretation\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8b5b08f9",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "df359736",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:23:28.777909Z",
     "iopub.status.busy": "2025-03-25T06:23:28.777816Z",
     "iopub.status.idle": "2025-03-25T06:23:30.873961Z",
     "shell.execute_reply": "2025-03-25T06:23:30.873594Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['1', '2', '3', '4', '5'], 'COL': ['192', '192', '192', '192', '192'], 'ROW': [328.0, 326.0, 324.0, 322.0, 320.0], 'NAME': ['GE_BrightCorner', 'DarkCorner', 'DarkCorner', 'A_21_P0014386', 'A_33_P3396872'], 'SPOT_ID': ['GE_BrightCorner', 'DarkCorner', 'DarkCorner', 'A_21_P0014386', 'A_33_P3396872'], 'CONTROL_TYPE': ['pos', 'pos', 'pos', 'FALSE', 'FALSE'], 'REFSEQ': [nan, nan, nan, nan, 'NM_001105533'], 'GB_ACC': [nan, nan, nan, nan, 'NM_001105533'], 'LOCUSLINK_ID': [nan, nan, nan, nan, 79974.0], 'GENE_SYMBOL': [nan, nan, nan, nan, 'CPED1'], 'GENE_NAME': [nan, nan, nan, nan, 'cadherin-like and PC-esterase domain containing 1'], 'UNIGENE_ID': [nan, nan, nan, nan, 'Hs.189652'], 'ENSEMBL_ID': [nan, nan, nan, nan, nan], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': [nan, nan, nan, nan, 'ref|NM_001105533|gb|AK025639|gb|BC030538|tc|THC2601673'], 'CHROMOSOMAL_LOCATION': [nan, nan, nan, 'unmapped', 'chr7:120901888-120901947'], 'CYTOBAND': [nan, nan, nan, nan, 'hs|7q31.31'], 'DESCRIPTION': [nan, nan, nan, nan, 'Homo sapiens cadherin-like and PC-esterase domain containing 1 (CPED1), transcript variant 2, mRNA [NM_001105533]'], 'GO_ID': [nan, nan, nan, nan, 'GO:0005783(endoplasmic reticulum)'], 'SEQUENCE': [nan, nan, nan, 'AATACATGTTTTGGTAAACACTCGGTCAGAGCACCCTCTTTCTGTGGAATCAGACTGGCA', 'GCTTATCTCACCTAATACAGGGACTATGCAACCAAGAAACTGGAAATAAAAACAAAGATA'], 'SPOT_ID.1': [nan, nan, nan, nan, nan]}\n"
     ]
    }
   ],
   "source": [
    "# 1. First get the file paths using geo_get_relevant_filepaths function\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. 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",
    "# 3. 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": "acb41508",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "694c894f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:23:30.875238Z",
     "iopub.status.busy": "2025-03-25T06:23:30.875107Z",
     "iopub.status.idle": "2025-03-25T06:23:31.006701Z",
     "shell.execute_reply": "2025-03-25T06:23:31.006329Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping dataframe shape: (51544, 2)\n",
      "Preview of gene mapping data:\n",
      "{'ID': ['5', '6', '7', '8', '12'], 'Gene': ['CPED1', 'BCOR', 'CHAC2', 'IFI30', 'GPR146']}\n",
      "Gene expression data shape after mapping: (19151, 32)\n",
      "Preview of first 5 genes after mapping:\n",
      "Index(['A1BG', 'A1BG-AS1', 'A2M', 'A2M-1', 'A2M-AS1'], dtype='object', name='Gene')\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the appropriate columns for mapping\n",
    "# Looking at the gene annotation preview, we see:\n",
    "# - 'ID' column contains numeric identifiers (1, 2, 3, 4, 5)\n",
    "# - 'GENE_SYMBOL' column contains gene symbols (e.g., CPED1)\n",
    "# These match the numeric IDs we saw in the gene expression data\n",
    "\n",
    "# 2. Create a gene mapping dataframe with the ID and gene symbol columns\n",
    "mapping_data = get_gene_mapping(gene_annotation, 'ID', 'GENE_SYMBOL')\n",
    "print(f\"Gene mapping dataframe shape: {mapping_data.shape}\")\n",
    "print(\"Preview of gene mapping data:\")\n",
    "print(preview_df(mapping_data))\n",
    "\n",
    "# 3. Apply the gene mapping to convert from probe-level to gene-level expression\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_data)\n",
    "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n",
    "print(\"Preview of first 5 genes after mapping:\")\n",
    "print(gene_data.index[:5])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "37e10ec9",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "bf80f9c1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:23:31.007967Z",
     "iopub.status.busy": "2025-03-25T06:23:31.007860Z",
     "iopub.status.idle": "2025-03-25T06:23:37.076076Z",
     "shell.execute_reply": "2025-03-25T06:23:37.075675Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalizing gene symbols...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape after normalization: (16005, 32)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Allergies/gene_data/GSE192454.csv\n",
      "Loading the original clinical data...\n",
      "Extracting clinical features...\n",
      "Clinical data preview:\n",
      "{'GSM5747314': [0.0], 'GSM5747315': [1.0], 'GSM5747316': [1.0], 'GSM5747317': [1.0], 'GSM5747318': [0.0], 'GSM5747319': [1.0], 'GSM5747320': [0.0], 'GSM5747321': [1.0], 'GSM5747322': [1.0], 'GSM5747323': [1.0], 'GSM5747324': [1.0], 'GSM5747325': [1.0], 'GSM5747326': [0.0], 'GSM5747327': [1.0], 'GSM5747328': [1.0], 'GSM5747329': [1.0], 'GSM5747330': [1.0], 'GSM5747331': [1.0], 'GSM5747332': [0.0], 'GSM5747333': [1.0], 'GSM5747334': [0.0], 'GSM5747335': [1.0], 'GSM5747336': [1.0], 'GSM5747337': [1.0], 'GSM5747338': [1.0], 'GSM5747339': [0.0], 'GSM5747340': [1.0], 'GSM5747341': [1.0], 'GSM5747342': [1.0], 'GSM5747343': [1.0], 'GSM5747344': [0.0], 'GSM5747345': [1.0]}\n",
      "Clinical data saved to ../../output/preprocess/Allergies/clinical_data/GSE192454.csv\n",
      "Linking clinical and genetic data...\n",
      "Linked data shape: (32, 16006)\n",
      "Handling missing values...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data shape after handling missing values: (32, 16006)\n",
      "Checking for bias in trait distribution...\n",
      "For the feature 'Allergies', the least common label is '0.0' with 8 occurrences. This represents 25.00% of the dataset.\n",
      "The distribution of the feature 'Allergies' in this dataset is fine.\n",
      "\n",
      "Dataset usability: True\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Allergies/GSE192454.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
}