File size: 27,617 Bytes
e4183cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "ed9d7816",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:35:30.035172Z",
     "iopub.status.busy": "2025-03-25T08:35:30.034990Z",
     "iopub.status.idle": "2025-03-25T08:35:30.200170Z",
     "shell.execute_reply": "2025-03-25T08:35:30.199722Z"
    }
   },
   "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 = \"Cystic_Fibrosis\"\n",
    "cohort = \"GSE142610\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Cystic_Fibrosis\"\n",
    "in_cohort_dir = \"../../input/GEO/Cystic_Fibrosis/GSE142610\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Cystic_Fibrosis/GSE142610.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Cystic_Fibrosis/gene_data/GSE142610.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Cystic_Fibrosis/clinical_data/GSE142610.csv\"\n",
    "json_path = \"../../output/preprocess/Cystic_Fibrosis/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ea7b74fe",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "35243b84",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:35:30.201627Z",
     "iopub.status.busy": "2025-03-25T08:35:30.201481Z",
     "iopub.status.idle": "2025-03-25T08:35:30.309681Z",
     "shell.execute_reply": "2025-03-25T08:35:30.309284Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Integrative genomic meta-analysis reveals novel molecular insights into cystic fibrosis and ΔF508-CFTR rescue\"\n",
      "!Series_summary\t\"Cystic fibrosis (CF), caused by mutations to CFTR, leads to severe and progressive lung disease. The most common mutant, ΔF508-CFTR, undergoes proteasomal degradation, depleting its anion channel function.  “Proteostasis” pathways, i.e. those relevant to protein processing and trafficking, are altered in cells with ΔF508-CFTR and can be modulated to partially rescue protein function. However, many details regarding proteostasis modulation, and its relevance to CF and ΔF508-CFTR rescue, remain poorly understood. To shed light on this, we re-analyzed public datasets characterizing transcription in CF vs. non-CF epithelia from human and pig airways, and also profiled established temperature, genetic, and chemical interventions that rescue ΔF508-CFTR. Meta-analysis yielded a core disease signature and two core rescue signatures. To interpret these, we compiled proteostasis pathways and an original “CFTR Gene Set Library”. The disease signature revealed differential regulation of mTORC1 signaling, endocytosis, and proteasomal degradation. Overlaying functional genomics data identified candidate mediators of low-temperature rescue, while multiple rescue strategies converged on activation of unfolded protein response pathways. Remarkably, however, C18, an analog of the CFTR corrector compound Lumacaftor, induced minimal transcriptional perturbation despite its rescue activity. This work elucidates the involvement of proteostasis in both disease and rescue perturbations while highlighting that not all CFTR rescue interventions act on transcription.\"\n",
      "!Series_overall_design\t\"Polarized air-liquid interface cultures of CFBE cells were treated to either knockdown of SIN3A, SYVN1 or NEED8, overexpression of miR-138, treated with corrector compound 18 (C18), or cultured at temperatures associated with improving ΔF508-CFTR trafficking.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['tag: Cell line: CFBE'], 1: ['treatment: DMSO for 24h', 'temperature: 40°C incubation for 24h followed by 27°C incubation for 24h', 'treatment: NEDD8 DsiRNA + 6µM Corrector Compound C18 treatment for 24h', 'treatment: Scrambled DsiRNA', 'temperature: 27°C incubation for 24h', 'treatment: SIN3A DsiRNA', 'temperature: 37°C incubation for 24h', 'treatment: SYVN1 DsiRNA', 'treatment: 6µM Corrector Compound C18 treatment for 24h', 'treatment: No treatment', 'treatment: miR-138 mimic', 'treatment: SYVN1 DsiRNA + 6µM Corrector Compound C18 treatment for 24h', 'temperature: 40°C incubation for 24h', 'treatment: NEDD8 DsiRNA']}\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": "07ce1988",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "3bad36fc",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:35:30.311112Z",
     "iopub.status.busy": "2025-03-25T08:35:30.310991Z",
     "iopub.status.idle": "2025-03-25T08:35:30.322221Z",
     "shell.execute_reply": "2025-03-25T08:35:30.321831Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical Data Preview: {'Sample_1': [1.0], 'Sample_2': [nan], 'Sample_3': [0.0], 'Sample_4': [1.0], 'Sample_5': [nan], 'Sample_6': [0.0], 'Sample_7': [nan], 'Sample_8': [0.0], 'Sample_9': [0.0], 'Sample_10': [1.0], 'Sample_11': [0.0], 'Sample_12': [0.0], 'Sample_13': [nan], 'Sample_14': [0.0]}\n",
      "Clinical data saved to ../../output/preprocess/Cystic_Fibrosis/clinical_data/GSE142610.csv\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "import numpy as np\n",
    "import re\n",
    "from typing import Callable, Optional, Dict, Any, Union\n",
    "import json\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information, this appears to be a gene expression dataset \n",
    "# analyzing transcriptional changes in CF, not just miRNA or methylation\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# For trait: Based on the characteristics dictionary, we see \"treatment\" at index 1\n",
    "# which can be used to determine CF vs non-CF status\n",
    "trait_row = 1  # The row with treatment information\n",
    "\n",
    "# There is no age data available in the sample characteristics\n",
    "age_row = None\n",
    "\n",
    "# There is no gender data available in the sample characteristics\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "def convert_trait(value: str) -> Optional[int]:\n",
    "    \"\"\"\n",
    "    Convert the treatment value to a binary trait (CF status).\n",
    "    1 = CF-like condition (DMSO, scrambled, no treatment as controls)\n",
    "    0 = Rescue interventions (treatments aimed at rescuing ΔF508-CFTR)\n",
    "    \n",
    "    Args:\n",
    "        value: The treatment value from the dataset\n",
    "    \n",
    "    Returns:\n",
    "        1 for CF-like (control) conditions, 0 for rescue interventions, None for unknown\n",
    "    \"\"\"\n",
    "    if not isinstance(value, str):\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",
    "    # Control conditions (CF-like)\n",
    "    if any(x in value.lower() for x in ['dmso', 'scrambled dsirna', 'no treatment']):\n",
    "        return 1\n",
    "    # Rescue interventions\n",
    "    elif any(x in value.lower() for x in ['temperature: 27', 'sin3a', 'syvn1', 'nedd8', 'mir-138', 'c18', 'corrector']):\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value: str) -> Optional[float]:\n",
    "    \"\"\"Placeholder function since age data is not available.\"\"\"\n",
    "    return None\n",
    "\n",
    "def convert_gender(value: str) -> Optional[int]:\n",
    "    \"\"\"Placeholder function since gender data is not available.\"\"\"\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata - Initial Filtering\n",
    "# Trait data is available if trait_row is not None\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",
    "# Only if trait data is available\n",
    "if trait_row is not None:\n",
    "    try:\n",
    "        # Create a DataFrame in the expected format for geo_select_clinical_features\n",
    "        # Samples as columns, features as rows\n",
    "        sample_characteristics = {\n",
    "            0: ['tag: Cell line: CFBE'],\n",
    "            1: ['treatment: DMSO for 24h', \n",
    "                'temperature: 40°C incubation for 24h followed by 27°C incubation for 24h', \n",
    "                'treatment: NEDD8 DsiRNA + 6µM Corrector Compound C18 treatment for 24h', \n",
    "                'treatment: Scrambled DsiRNA', \n",
    "                'temperature: 27°C incubation for 24h', \n",
    "                'treatment: SIN3A DsiRNA', \n",
    "                'temperature: 37°C incubation for 24h', \n",
    "                'treatment: SYVN1 DsiRNA', \n",
    "                'treatment: 6µM Corrector Compound C18 treatment for 24h', \n",
    "                'treatment: No treatment', \n",
    "                'treatment: miR-138 mimic', \n",
    "                'treatment: SYVN1 DsiRNA + 6µM Corrector Compound C18 treatment for 24h', \n",
    "                'temperature: 40°C incubation for 24h', \n",
    "                'treatment: NEDD8 DsiRNA']\n",
    "        }\n",
    "        \n",
    "        # Create a list of sample IDs\n",
    "        unique_treatments = sample_characteristics[1]\n",
    "        sample_ids = [f\"Sample_{i+1}\" for i in range(len(unique_treatments))]\n",
    "        \n",
    "        # Create the clinical data DataFrame with samples as columns\n",
    "        clinical_data = pd.DataFrame(index=range(max(sample_characteristics.keys())+1))\n",
    "        \n",
    "        for i, sample_id in enumerate(sample_ids):\n",
    "            clinical_data[sample_id] = None\n",
    "            \n",
    "            # Assign cell line info to all samples\n",
    "            clinical_data.at[0, sample_id] = sample_characteristics[0][0]\n",
    "            \n",
    "            # Assign treatment info\n",
    "            clinical_data.at[1, sample_id] = unique_treatments[i]\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 data\n",
    "        preview = preview_df(selected_clinical_df)\n",
    "        print(\"Clinical Data Preview:\", preview)\n",
    "        \n",
    "        # Save the processed 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, index=False)\n",
    "        print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "    except Exception as e:\n",
    "        print(f\"Error processing clinical data: {str(e)}\")\n",
    "        print(\"Clinical data processing skipped.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "590f5c7d",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "92e3e0fa",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:35:30.323480Z",
     "iopub.status.busy": "2025-03-25T08:35:30.323373Z",
     "iopub.status.idle": "2025-03-25T08:35:30.492362Z",
     "shell.execute_reply": "2025-03-25T08:35:30.491824Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found data marker at line 66\n",
      "Header line: \"ID_REF\"\t\"GSM4232834\"\t\"GSM4232835\"\t\"GSM4232836\"\t\"GSM4232837\"\t\"GSM4232838\"\t\"GSM4232839\"\t\"GSM4232840\"\t\"GSM4232841\"\t\"GSM4232842\"\t\"GSM4232843\"\t\"GSM4232844\"\t\"GSM4232845\"\t\"GSM4232846\"\t\"GSM4232847\"\t\"GSM4232848\"\t\"GSM4232849\"\t\"GSM4232850\"\t\"GSM4232851\"\t\"GSM4232852\"\t\"GSM4232853\"\t\"GSM4232854\"\t\"GSM4232855\"\t\"GSM4232856\"\t\"GSM4232857\"\t\"GSM4232858\"\t\"GSM4232859\"\t\"GSM4232860\"\t\"GSM4232861\"\t\"GSM4232862\"\t\"GSM4232863\"\t\"GSM4232864\"\t\"GSM4232865\"\t\"GSM4232866\"\t\"GSM4232867\"\t\"GSM4232868\"\t\"GSM4232869\"\t\"GSM4232870\"\t\"GSM4232871\"\t\"GSM4232872\"\t\"GSM4232873\"\t\"GSM4232874\"\t\"GSM4232875\"\t\"GSM4232876\"\t\"GSM4232877\"\t\"GSM4232878\"\t\"GSM4232879\"\t\"GSM4232880\"\t\"GSM4232881\"\t\"GSM4232882\"\t\"GSM4232883\"\t\"GSM4232884\"\t\"GSM4232885\"\t\"GSM4232886\"\t\"GSM4232887\"\t\"GSM4232888\"\t\"GSM4232889\"\t\"GSM4232890\"\t\"GSM4232891\"\t\"GSM4232892\"\t\"GSM4232893\"\n",
      "First data line: \"7A5\"\t7.00047\t7.4364\t7.2259\t6.95089\t7.01398\t6.94179\t6.35476\t6.39446\t7.04405\t6.67603\t6.38158\t6.87048\t6.78098\t6.94703\t7.00125\t7.0633\t6.01448\t7.10264\t6.87251\t7.03624\t7.04809\t6.72825\t7.0007\t6.90422\t6.90433\t7.23055\t7.52354\t6.29845\t6.93591\t6.45731\t6.93591\t6.44016\t7.30199\t6.90369\t6.44151\t6.8296\t6.27562\t6.85061\t7.22973\t6.96944\t6.52329\t6.62954\t6.69973\t6.95149\t6.17045\t6.70617\t6.7019\t6.9133\t6.78328\t6.98717\t7.05936\t6.44223\t7.03674\t7.01894\t7.03133\t7.28102\t6.84521\t7.02275\t6.80499\t7.24612\n",
      "Index(['7A5', 'A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1',\n",
      "       'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS', 'AACS', 'AACSL', 'AADAC',\n",
      "       'AADACL1', 'AADACL2', 'AADACL3', 'AADACL4'],\n",
      "      dtype='object', name='ID')\n"
     ]
    }
   ],
   "source": [
    "# 1. Get the file paths for the SOFT file and matrix file\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. First, let's examine the structure of the matrix file to understand its format\n",
    "import gzip\n",
    "\n",
    "# Peek at the first few lines of the file to understand its structure\n",
    "with gzip.open(matrix_file, 'rt') as file:\n",
    "    # Read first 100 lines to find the header structure\n",
    "    for i, line in enumerate(file):\n",
    "        if '!series_matrix_table_begin' in line:\n",
    "            print(f\"Found data marker at line {i}\")\n",
    "            # Read the next line which should be the header\n",
    "            header_line = next(file)\n",
    "            print(f\"Header line: {header_line.strip()}\")\n",
    "            # And the first data line\n",
    "            first_data_line = next(file)\n",
    "            print(f\"First data line: {first_data_line.strip()}\")\n",
    "            break\n",
    "        if i > 100:  # Limit search to first 100 lines\n",
    "            print(\"Matrix table marker not found in first 100 lines\")\n",
    "            break\n",
    "\n",
    "# 3. Now try to get the genetic data with better error handling\n",
    "try:\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    print(gene_data.index[:20])\n",
    "except KeyError as e:\n",
    "    print(f\"KeyError: {e}\")\n",
    "    \n",
    "    # Alternative approach: manually extract the data\n",
    "    print(\"\\nTrying alternative approach to read the gene data:\")\n",
    "    with gzip.open(matrix_file, 'rt') as file:\n",
    "        # Find the start of the data\n",
    "        for line in file:\n",
    "            if '!series_matrix_table_begin' in line:\n",
    "                break\n",
    "                \n",
    "        # Read the headers and data\n",
    "        import pandas as pd\n",
    "        df = pd.read_csv(file, sep='\\t', index_col=0)\n",
    "        print(f\"Column names: {df.columns[:5]}\")\n",
    "        print(f\"First 20 row IDs: {df.index[:20]}\")\n",
    "        gene_data = df\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d6ed32f3",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "2bc0731c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:35:30.493873Z",
     "iopub.status.busy": "2025-03-25T08:35:30.493748Z",
     "iopub.status.idle": "2025-03-25T08:35:30.495952Z",
     "shell.execute_reply": "2025-03-25T08:35:30.495587Z"
    }
   },
   "outputs": [],
   "source": [
    "# Reviewing the gene identifiers\n",
    "# Looking at the identifiers from the output, we can see entries like:\n",
    "# '7A5', 'A1BG', 'A1CF', 'A2BP1', etc.\n",
    "\n",
    "# These appear to be standard human gene symbols. \n",
    "# For example:\n",
    "# - A1BG is Alpha-1-B Glycoprotein\n",
    "# - A2M is Alpha-2-Macroglobulin\n",
    "# - AAAS is Achalasia, Adrenocortical Insufficiency, Alacrimia syndrome gene\n",
    "\n",
    "# While some identifiers might be less common (like 7A5), the majority appear to be\n",
    "# standard HGNC gene symbols, so no mapping should be required\n",
    "\n",
    "requires_gene_mapping = False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5aa4c749",
   "metadata": {},
   "source": [
    "### Step 5: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "f274558c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:35:30.497231Z",
     "iopub.status.busy": "2025-03-25T08:35:30.497121Z",
     "iopub.status.idle": "2025-03-25T08:35:42.410116Z",
     "shell.execute_reply": "2025-03-25T08:35:42.409470Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data shape: (20747, 60)\n",
      "First few genes with their expression values after normalization:\n",
      "          GSM4232834  GSM4232835  GSM4232836  GSM4232837  GSM4232838  \\\n",
      "ID                                                                     \n",
      "A1BG         4.79408     4.77433     5.09248     5.12294     5.22396   \n",
      "A1BG-AS1     4.41521     4.10095     4.19279     4.15799     4.01244   \n",
      "A1CF         4.47919     4.49296     4.96132     4.61623     4.62902   \n",
      "A2M          4.18512     3.43994     4.08894     3.50579     3.90165   \n",
      "A2ML1        4.53153     3.44832     4.08500     2.97268     4.07312   \n",
      "\n",
      "          GSM4232839  GSM4232840  GSM4232841  GSM4232842  GSM4232843  ...  \\\n",
      "ID                                                                    ...   \n",
      "A1BG         4.83021     5.07336     4.71037     5.22138     5.04408  ...   \n",
      "A1BG-AS1     4.37280     4.83188     4.62063     4.36214     3.76720  ...   \n",
      "A1CF         4.61928     4.64433     4.49737     4.74431     4.53624  ...   \n",
      "A2M          3.68211     3.59082     3.72203     3.68729     3.36298  ...   \n",
      "A2ML1        2.88517     3.25851     4.20093     4.47530     3.98375  ...   \n",
      "\n",
      "          GSM4232884  GSM4232885  GSM4232886  GSM4232887  GSM4232888  \\\n",
      "ID                                                                     \n",
      "A1BG         4.76957     4.83349     4.89837     4.95678     5.55280   \n",
      "A1BG-AS1     4.16814     4.50411     4.44726     3.90727     4.08097   \n",
      "A1CF         4.68982     4.46157     4.54973     4.70105     4.50531   \n",
      "A2M          3.98965     4.56486     3.47137     3.84234     4.02411   \n",
      "A2ML1        3.29743     4.00144     3.68519     4.54602     3.94150   \n",
      "\n",
      "          GSM4232889  GSM4232890  GSM4232891  GSM4232892  GSM4232893  \n",
      "ID                                                                    \n",
      "A1BG         5.31089     4.85788     5.19227     5.00836     4.98561  \n",
      "A1BG-AS1     4.40857     4.42194     4.27793     3.90266     4.25806  \n",
      "A1CF         4.34295     4.66214     4.30193     4.12278     4.21548  \n",
      "A2M          4.41546     3.47600     3.81681     4.10732     3.47600  \n",
      "A2ML1        3.31699     4.02810     3.84733     3.15712     3.85833  \n",
      "\n",
      "[5 rows x 60 columns]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Cystic_Fibrosis/gene_data/GSE142610.csv\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found treatment information for 60 samples\n",
      "Clinical data created with 60 samples\n",
      "Cystic_Fibrosis\n",
      "0    52\n",
      "1     8\n",
      "Name: count, dtype: int64\n",
      "Linked data shape: (60, 20748)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Data shape after handling missing values: (60, 20748)\n",
      "For the feature 'Cystic_Fibrosis', the least common label is '1' with 8 occurrences. This represents 13.33% of the dataset.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Cystic_Fibrosis/GSE142610.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n",
    "print(\"First few genes with their expression values after normalization:\")\n",
    "print(normalized_gene_data.head())\n",
    "\n",
    "# Save the normalized 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",
    "# 2. Properly extract original clinical data to match GSM IDs\n",
    "# First, let's get the proper mapping between GSM IDs and treatment conditions\n",
    "# Extract the relevant lines from the SOFT file for sample information\n",
    "with gzip.open(soft_file, 'rt') as f:\n",
    "    sample_info_lines = []\n",
    "    current_gsm = None\n",
    "    for line in f:\n",
    "        line = line.strip()\n",
    "        if line.startswith(\"^SAMPLE = \"):\n",
    "            current_gsm = line.split(\" = \")[1]\n",
    "        elif line.startswith(\"!Sample_title\") and current_gsm:\n",
    "            title = line.split(\" = \")[1].strip('\"')\n",
    "            sample_info_lines.append((current_gsm, title))\n",
    "\n",
    "# Create a mapping of GSM IDs to treatment conditions\n",
    "gsm_to_treatment = {}\n",
    "for gsm, title in sample_info_lines:\n",
    "    gsm_to_treatment[gsm] = title\n",
    "\n",
    "print(f\"Found treatment information for {len(gsm_to_treatment)} samples\")\n",
    "\n",
    "# Create clinical data with real GSM IDs\n",
    "clinical_data = pd.DataFrame(index=normalized_gene_data.columns)\n",
    "\n",
    "# Assign trait values based on treatment descriptions\n",
    "# 1 = CF-like condition (control)\n",
    "# 0 = Rescue intervention\n",
    "clinical_data[trait] = clinical_data.index.map(lambda gsm: 1 if any(x in gsm_to_treatment.get(gsm, \"\").lower() \n",
    "                                            for x in ['dmso', 'scrambled', 'control', 'untreated']) \n",
    "                                    else 0 if gsm in gsm_to_treatment else None)\n",
    "\n",
    "print(f\"Clinical data created with {len(clinical_data)} samples\")\n",
    "print(clinical_data[trait].value_counts())\n",
    "\n",
    "# Link the clinical and genetic data\n",
    "linked_data = clinical_data.join(normalized_gene_data.T)\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "\n",
    "# 3. Handle missing values in the linked data\n",
    "linked_data = handle_missing_values(linked_data, trait)\n",
    "print(f\"Data shape after handling missing values: {linked_data.shape}\")\n",
    "\n",
    "# 4. Determine whether the trait is biased\n",
    "trait_type = 'binary' if len(linked_data[trait].unique()) == 2 else 'continuous'\n",
    "if trait_type == \"binary\":\n",
    "    is_trait_biased = judge_binary_variable_biased(linked_data, trait)\n",
    "else:\n",
    "    is_trait_biased = judge_continuous_variable_biased(linked_data, trait)\n",
    "\n",
    "# 5. Conduct final quality validation and save 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=linked_data,\n",
    "    note=f\"Dataset contains gene expression data comparing rescue interventions with control conditions in CFBE cells.\"\n",
    ")\n",
    "\n",
    "# 6. If the linked data is usable, save it\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(\"Data was determined to be unusable and was not saved\")"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}