File size: 34,843 Bytes
32677ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "91c01dd4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:35:16.178932Z",
     "iopub.status.busy": "2025-03-25T08:35:16.178757Z",
     "iopub.status.idle": "2025-03-25T08:35:16.348634Z",
     "shell.execute_reply": "2025-03-25T08:35:16.348186Z"
    }
   },
   "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 = \"GSE139038\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Cystic_Fibrosis\"\n",
    "in_cohort_dir = \"../../input/GEO/Cystic_Fibrosis/GSE139038\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Cystic_Fibrosis/GSE139038.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Cystic_Fibrosis/gene_data/GSE139038.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Cystic_Fibrosis/clinical_data/GSE139038.csv\"\n",
    "json_path = \"../../output/preprocess/Cystic_Fibrosis/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a300cb0b",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "9834675d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:35:16.350142Z",
     "iopub.status.busy": "2025-03-25T08:35:16.349982Z",
     "iopub.status.idle": "2025-03-25T08:35:16.460253Z",
     "shell.execute_reply": "2025-03-25T08:35:16.459825Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Gene expression profiling in paired normal, apparently normal and breast tumour tissues\"\n",
      "!Series_summary\t\"The main objective of the study was to identify potential diagnostic and follow up markers along with therapeutic targets for breast cancer. We performed gene expression studies using the microarray technology on 65 samples including 41 breast tumours [24 early stage, 17 locally advanced, 18 adjacent normal tissue [paired normal] and 6 apparently normal from breasts which had been operated for non-malignant conditions. All the samples had frozen section done – tumours needed to have 70% or more tumour cells; paired normal and apparently normal had to be morphologically normal with no tumour cells.\"\n",
      "!Series_overall_design\t\"Two-dye experiments using Universal Control RNA (Stratagene) and RNA from tissues.\"\n",
      "!Series_overall_design\t\"Biological replicates - Apparently normal = 6, Paired normal = 18, Breast tumor tissues = 41\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['age: 35', 'age: 67', 'age: 36', 'age: 40', 'age: 52', 'age: 50', 'age: 59', 'age: 60', 'age: 55', 'age: 56', 'age: 42', 'age: 48', 'age: 46', 'age: 45', 'age: 54', 'age: 65', 'age: 74', 'age: 63', 'age: 32', 'age: 61', 'age: 64', 'age: 31', 'age: 70', 'age: 41', 'age: 58', 'age: 53', 'age: 75', 'age: 57'], 1: ['gender: Female'], 2: ['histopathological examination (hpe); inflitrating lobular carcinoma (ilc); infiltrating ductal carcinoma (idc): Morphologically normal', 'histopathological examination (hpe); inflitrating lobular carcinoma (ilc); infiltrating ductal carcinoma (idc): IDC', 'histopathological examination (hpe); inflitrating lobular carcinoma (ilc); infiltrating ductal carcinoma (idc): Infiltrating mammary carcinoma, probably ILC', 'histopathological examination (hpe); inflitrating lobular carcinoma (ilc); infiltrating ductal carcinoma (idc): ILC', 'histopathological examination (hpe); inflitrating lobular carcinoma (ilc); infiltrating ductal carcinoma (idc): IDC with extensive DCIS', 'histopathological examination (hpe); inflitrating lobular carcinoma (ilc); infiltrating ductal carcinoma (idc): IDC with DCIS', 'histopathological examination (hpe); inflitrating lobular carcinoma (ilc); infiltrating ductal carcinoma (idc): IDC with vascular emboli'], 3: ['cancer stage: Apparent normal', 'cancer stage: T2N1M0', 'cancer stage: T4bN1M0', 'cancer stage: T4bN2M0', 'cancer stage: T4bN3M1', 'cancer stage: T3N1Mx', 'cancer stage: T3N2M0', 'cancer stage: T4bN3M0', 'cancer stage: T1N1M0', 'cancer stage: T1N0Mx', 'cancer stage: T1N0M0', 'cancer stage: Paired normal', 'cancer stage: T2N0M0', 'cancer stage: Both breast T2N0M0', 'cancer stage: T1N1'], 4: ['tissue origin: breast', 'er status: Positive', 'er status: Negative'], 5: ['sample type: surgery (frozen tissue)', 'sample type: trucut biopsy (frozen tissue)', 'pr status: Positive', 'pr status: Negative', 'pr status: positive'], 6: [nan, 'her2 status: Positive', 'her2 status: Negative', 'her2 status: positive', 'her2 status: Block not available'], 7: [nan, 'tissue origin: breast'], 8: [nan, 'sample type: surgery (frozen tissue)', 'sample type: trucut biopsy (frozen tissue)', 'sample type: trucut (frozen tissue)']}\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": "8f4c5cc1",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "076572ec",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:35:16.461447Z",
     "iopub.status.busy": "2025-03-25T08:35:16.461330Z",
     "iopub.status.idle": "2025-03-25T08:35:16.471547Z",
     "shell.execute_reply": "2025-03-25T08:35:16.471162Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of selected clinical features:\n",
      "{0: [nan, 35.0], 1: [nan, nan], 2: [nan, nan], 3: [1.0, nan], 4: [nan, nan], 5: [1.0, nan], 6: [nan, nan], 7: [nan, nan], 8: [1.0, nan]}\n",
      "Clinical data saved to ../../output/preprocess/Cystic_Fibrosis/clinical_data/GSE139038.csv\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import os\n",
    "import json\n",
    "from typing import Dict, Any, Callable, Optional\n",
    "\n",
    "# 1. Determine gene expression data availability\n",
    "# Based on the background information, this dataset contains gene expression data for breast cancer\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "\n",
    "# Trait: Looking at row 3 which contains 'cancer stage' to distinguish between normal and tumor samples\n",
    "trait_row = 3  # 'cancer stage' row\n",
    "\n",
    "# Age: Available in row 0\n",
    "age_row = 0  # 'age' row\n",
    "\n",
    "# Gender: All samples are female (row 1 shows \"gender: Female\" with no variation)\n",
    "# This is a constant feature, so not useful for association study\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert cancer stage information to binary trait (0 for normal, 1 for cancer)\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Determine if the sample is normal or cancer\n",
    "    if 'normal' in value.lower() or 'apparent normal' in value.lower():\n",
    "        return 0  # Normal tissue\n",
    "    elif 't' in value.lower() and any(x in value.lower() for x in ['n', 'm']):\n",
    "        return 1  # Cancer tissue\n",
    "    else:\n",
    "        return None  # Unknown\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age information to a continuous numeric value\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    try:\n",
    "        return float(value)  # Convert to float (continuous variable)\n",
    "    except (ValueError, TypeError):\n",
    "        return None  # Invalid or non-numeric age\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender information to binary (0 for female, 1 for male)\"\"\"\n",
    "    # Not used in this dataset as all samples are female\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip().lower()\n",
    "    \n",
    "    if 'female' in value:\n",
    "        return 0\n",
    "    elif 'male' in value:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Initial validation\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",
    "    # Assuming clinical_data was obtained in a previous step and contains the sample characteristics\n",
    "    # In this case, we need to create a DataFrame from the sample characteristics dictionary\n",
    "    \n",
    "    # Convert the sample characteristics dictionary to a DataFrame\n",
    "    characteristics = {}\n",
    "    for row_idx, values in sample_characteristics_dict.items():\n",
    "        characteristics[row_idx] = values\n",
    "    \n",
    "    clinical_data = pd.DataFrame.from_dict(characteristics, orient='index').T\n",
    "    \n",
    "    # Extract clinical features\n",
    "    selected_clinical_df = geo_select_clinical_features(\n",
    "        clinical_df=clinical_data,\n",
    "        trait=trait,\n",
    "        trait_row=trait_row,\n",
    "        convert_trait=convert_trait,\n",
    "        age_row=age_row,\n",
    "        convert_age=convert_age,\n",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender\n",
    "    )\n",
    "    \n",
    "    # Preview the data\n",
    "    print(\"Preview of selected clinical features:\")\n",
    "    print(preview_df(selected_clinical_df))\n",
    "    \n",
    "    # Save to CSV\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    selected_clinical_df.to_csv(out_clinical_data_file)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "218fcad8",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "37f54fe5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:35:16.472660Z",
     "iopub.status.busy": "2025-03-25T08:35:16.472547Z",
     "iopub.status.idle": "2025-03-25T08:35:16.686669Z",
     "shell.execute_reply": "2025-03-25T08:35:16.686209Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found data marker at line 80\n",
      "Header line: \"ID_REF\"\t\"GSM4127905\"\t\"GSM4127906\"\t\"GSM4127907\"\t\"GSM4127908\"\t\"GSM4127909\"\t\"GSM4127910\"\t\"GSM4127911\"\t\"GSM4127912\"\t\"GSM4127913\"\t\"GSM4127914\"\t\"GSM4127915\"\t\"GSM4127916\"\t\"GSM4127917\"\t\"GSM4127918\"\t\"GSM4127919\"\t\"GSM4127920\"\t\"GSM4127921\"\t\"GSM4127922\"\t\"GSM4127923\"\t\"GSM4127924\"\t\"GSM4127925\"\t\"GSM4127926\"\t\"GSM4127927\"\t\"GSM4127928\"\t\"GSM4127929\"\t\"GSM4127930\"\t\"GSM4127931\"\t\"GSM4127932\"\t\"GSM4127933\"\t\"GSM4127934\"\t\"GSM4127935\"\t\"GSM4127936\"\t\"GSM4127937\"\t\"GSM4127938\"\t\"GSM4127939\"\t\"GSM4127940\"\t\"GSM4127941\"\t\"GSM4127942\"\t\"GSM4127943\"\t\"GSM4127944\"\t\"GSM4127945\"\t\"GSM4127946\"\t\"GSM4127947\"\t\"GSM4127948\"\t\"GSM4127949\"\t\"GSM4127950\"\t\"GSM4127951\"\t\"GSM4127952\"\t\"GSM4127953\"\t\"GSM4127954\"\t\"GSM4127955\"\t\"GSM4127956\"\t\"GSM4127957\"\t\"GSM4127958\"\t\"GSM4127959\"\t\"GSM4127960\"\t\"GSM4127961\"\t\"GSM4127962\"\t\"GSM4127963\"\t\"GSM4127964\"\t\"GSM4127965\"\t\"GSM4127966\"\t\"GSM4127967\"\t\"GSM4127968\"\t\"GSM4127969\"\n",
      "First data line: \"10_10_1\"\t-0.943\t0.844\t0.14\t0.566\t-1.208\t-0.216\t0.036\t0.136\t0.542\t0.205\t0.848\t-0.322\t-0.706\t1.363\t1.538\t0.879\t0.939\t-0.234\t1\t1.489\t0.974\t-1.204\t1.208\t1.727\t0.072\t-0.016\t-2.632\t-1.121\t-0.522\t0.476\t1.386\t0.14\t1.095\t0.399\t0.062\t1.429\t-0.174\t0.724\t0.356\t0.491\t0.36\t0.943\t0.134\t0.814\t-1.478\t1.298\t0.045\t-2.363\t0.49\t-2.111\t1.234\t-0.392\t1.694\t-1\t1.549\t-2.796\t-0.411\t-0.616\t0.801\t0.713\t-0.196\t-0.026\t-0.635\t-1.074\t0.659\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['10_10_1', '10_10_10', '10_10_11', '10_10_12', '10_10_13', '10_10_14',\n",
      "       '10_10_15', '10_10_16', '10_10_17', '10_10_18', '10_10_19', '10_10_2',\n",
      "       '10_10_20', '10_10_21', '10_10_22', '10_10_23', '10_10_24', '10_10_25',\n",
      "       '10_10_26', '10_10_27'],\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": "0c57d677",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "be7a3f63",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:35:16.688016Z",
     "iopub.status.busy": "2025-03-25T08:35:16.687881Z",
     "iopub.status.idle": "2025-03-25T08:35:16.690031Z",
     "shell.execute_reply": "2025-03-25T08:35:16.689656Z"
    }
   },
   "outputs": [],
   "source": [
    "# The identifiers shown (like \"10_10_1\", \"10_10_10\", etc.) are not standard human gene symbols.\n",
    "# Standard human gene symbols would typically be recognizable names like \"CFTR\", \"TP53\", etc.\n",
    "# These appear to be probe or feature identifiers from the microarray platform that need mapping.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "10f52574",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "ab4d4c70",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:35:16.691154Z",
     "iopub.status.busy": "2025-03-25T08:35:16.691045Z",
     "iopub.status.idle": "2025-03-25T08:35:19.286281Z",
     "shell.execute_reply": "2025-03-25T08:35:19.285720Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['1_1_1', '1_2_1', '1_3_1', '1_4_1', '1_5_1'], 'Block': ['1', '1', '1', '1', '1'], 'Column': [1.0, 2.0, 3.0, 4.0, 5.0], 'Row': [1.0, 1.0, 1.0, 1.0, 1.0], 'description': ['Actin, beta', 'Actin, beta', 'Ribosomal protein L13a', 'Actin, beta', 'Hypoxanthine phosphoribosyltransferase 1 (Lesch-Nyhan syndrome)'], 'Gene_Symbol': ['ACTB', 'ACTB', 'RPL13A', 'ACTB', 'HPRT1'], 'SPOT_ID': ['hSQ025392', 'hSQ025392', 'hSQ018331', 'hSQ025392', 'hSQ021313']}\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": "ce4044be",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "e9965dd5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:35:19.287772Z",
     "iopub.status.busy": "2025-03-25T08:35:19.287639Z",
     "iopub.status.idle": "2025-03-25T08:35:20.087249Z",
     "shell.execute_reply": "2025-03-25T08:35:20.086697Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping preview:\n",
      "{'ID': ['1_1_1', '1_2_1', '1_3_1', '1_4_1', '1_5_1'], 'Gene': ['ACTB', 'ACTB', 'RPL13A', 'ACTB', 'HPRT1']}\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data after mapping:\n",
      "Shape: (18744, 65)\n",
      "First few gene symbols: ['A1BG', 'A2BP1', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS', 'AACS', 'AADAC']\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to ../../output/preprocess/Cystic_Fibrosis/gene_data/GSE139038.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Determine which columns in the gene annotation correspond to gene IDs and gene symbols\n",
    "# Looking at the data preview, we can see:\n",
    "# - The 'ID' column in gene_annotation contains identifiers like '1_1_1'\n",
    "# - The gene expression data has row IDs like '10_10_1'\n",
    "# - The 'Gene_Symbol' column contains standard gene symbols like 'ACTB'\n",
    "\n",
    "# Since both datasets use the 'ID' column for identifiers, and 'Gene_Symbol' contains the gene symbols:\n",
    "prob_col = 'ID'\n",
    "gene_col = 'Gene_Symbol'\n",
    "\n",
    "# 2. Create the gene mapping dataframe\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)\n",
    "print(\"Gene mapping preview:\")\n",
    "print(preview_df(gene_mapping))\n",
    "\n",
    "# 3. Apply the gene mapping to convert probe-level measurements to gene-level expression\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "print(\"Gene expression data after mapping:\")\n",
    "print(f\"Shape: {gene_data.shape}\")\n",
    "print(f\"First few gene symbols: {list(gene_data.index[:10])}\")\n",
    "\n",
    "# Save gene expression data to file\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Gene expression data saved to {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "66895b27",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "72a500b9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:35:20.088840Z",
     "iopub.status.busy": "2025-03-25T08:35:20.088708Z",
     "iopub.status.idle": "2025-03-25T08:35:29.153888Z",
     "shell.execute_reply": "2025-03-25T08:35:29.153516Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data shape: (17356, 65)\n",
      "First few genes with their expression values after normalization:\n",
      "        GSM4127905  GSM4127906  GSM4127907  GSM4127908  GSM4127909  \\\n",
      "Gene                                                                 \n",
      "A1BG         1.121       0.642       0.495       0.979      -1.178   \n",
      "A2M          3.808       1.866       2.066       2.439       2.413   \n",
      "A2ML1        1.433       0.974       0.905       0.688       0.807   \n",
      "A4GALT      -0.253       0.835       1.503       0.943      -0.485   \n",
      "A4GNT       -0.617      -0.231       1.585      -0.133       0.348   \n",
      "\n",
      "        GSM4127910  GSM4127911  GSM4127912  GSM4127913  GSM4127914  ...  \\\n",
      "Gene                                                                ...   \n",
      "A1BG        -0.152       0.530       1.520       0.769       0.709  ...   \n",
      "A2M          1.896       1.527       1.776       1.970       0.804  ...   \n",
      "A2ML1       -0.074      -0.170       0.500       0.597       0.766  ...   \n",
      "A4GALT       0.117       1.184       0.559       2.202      -0.555  ...   \n",
      "A4GNT        0.446       2.807       0.000       1.170      -0.387  ...   \n",
      "\n",
      "        GSM4127960  GSM4127961  GSM4127962  GSM4127963  GSM4127964  \\\n",
      "Gene                                                                 \n",
      "A1BG        -6.113      -0.816       0.811       0.185      -0.785   \n",
      "A2M         -1.170       3.590       0.594       2.559      -0.773   \n",
      "A2ML1       -7.745       0.000      -1.732      -0.485       0.087   \n",
      "A4GALT       1.000      -1.000      -0.948       0.212       0.359   \n",
      "A4GNT       -2.241      -0.737      -1.979      -0.788      -0.405   \n",
      "\n",
      "        GSM4127965  GSM4127966  GSM4127967  GSM4127968  GSM4127969  \n",
      "Gene                                                                \n",
      "A1BG         0.831       1.779      -0.767      -1.504       1.091  \n",
      "A2M          3.142       1.153       3.025      -0.528       3.856  \n",
      "A2ML1        0.795       0.098      -1.275      -1.830       0.152  \n",
      "A4GALT       2.147       0.036      -1.193      -0.089       1.469  \n",
      "A4GNT        0.181       0.925      -1.585      -1.646       1.093  \n",
      "\n",
      "[5 rows x 65 columns]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Cystic_Fibrosis/gene_data/GSE139038.csv\n",
      "Clinical data shape: (2, 9)\n",
      "Clinical data preview:\n",
      "                    0   1   2    3   4    5   6   7    8\n",
      "Cystic_Fibrosis   NaN NaN NaN  1.0 NaN  1.0 NaN NaN  1.0\n",
      "Age              35.0 NaN NaN  NaN NaN  NaN NaN NaN  NaN\n",
      "Sample IDs from gene expression data: Index(['GSM4127905', 'GSM4127906', 'GSM4127907', 'GSM4127908', 'GSM4127909'], dtype='object') ...\n",
      "Raw clinical data columns: Index(['!Sample_geo_accession', 'GSM4127905', 'GSM4127906', 'GSM4127907',\n",
      "       'GSM4127908'],\n",
      "      dtype='object') ...\n",
      "Rebuilt clinical features:\n",
      "                 GSM4127905  GSM4127906  GSM4127907  GSM4127908  GSM4127909  \\\n",
      "Cystic_Fibrosis         0.0         0.0         0.0         0.0         0.0   \n",
      "Age                    35.0        67.0        35.0        36.0        40.0   \n",
      "\n",
      "                 GSM4127910  GSM4127911  GSM4127912  GSM4127913  GSM4127914  \\\n",
      "Cystic_Fibrosis         0.0         1.0         1.0         1.0         1.0   \n",
      "Age                    52.0        50.0        59.0        60.0        55.0   \n",
      "\n",
      "                 ...  GSM4127960  GSM4127961  GSM4127962  GSM4127963  \\\n",
      "Cystic_Fibrosis  ...         1.0         0.0         1.0         0.0   \n",
      "Age              ...        54.0        54.0        67.0        67.0   \n",
      "\n",
      "                 GSM4127964  GSM4127965  GSM4127966  GSM4127967  GSM4127968  \\\n",
      "Cystic_Fibrosis         1.0         0.0         1.0         0.0         1.0   \n",
      "Age                    64.0        64.0        60.0        60.0        57.0   \n",
      "\n",
      "                 GSM4127969  \n",
      "Cystic_Fibrosis         0.0  \n",
      "Age                    57.0  \n",
      "\n",
      "[2 rows x 65 columns]\n",
      "Linked data shape: (65, 17358)\n",
      "Linked data preview (first 5 rows, first 5 columns):\n",
      "            Cystic_Fibrosis   Age   A1BG    A2M  A2ML1\n",
      "GSM4127905              0.0  35.0  1.121  3.808  1.433\n",
      "GSM4127906              0.0  67.0  0.642  1.866  0.974\n",
      "GSM4127907              0.0  35.0  0.495  2.066  0.905\n",
      "GSM4127908              0.0  36.0  0.979  2.439  0.688\n",
      "GSM4127909              0.0  40.0 -1.178  2.413  0.807\n",
      "Missing values before handling:\n",
      "  Trait (Cystic_Fibrosis) missing: 0 out of 65\n",
      "  Age missing: 0 out of 65\n",
      "  Genes with >20% missing: 0\n",
      "  Samples with >5% missing genes: 0\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Data shape after handling missing values: (65, 17358)\n",
      "For the feature 'Cystic_Fibrosis', the least common label is '0.0' with 24 occurrences. This represents 36.92% of the dataset.\n",
      "The distribution of the feature 'Cystic_Fibrosis' in this dataset is fine.\n",
      "\n",
      "Quartiles for 'Age':\n",
      "  25%: 45.0\n",
      "  50% (Median): 54.0\n",
      "  75%: 60.0\n",
      "Min: 31.0\n",
      "Max: 75.0\n",
      "The distribution of the feature 'Age' in this dataset is fine.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Cystic_Fibrosis/GSE139038.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. Load the clinical data that was saved in a previous step\n",
    "try:\n",
    "    clinical_data = pd.read_csv(out_clinical_data_file, index_col=0)\n",
    "    print(\"Clinical data shape:\", clinical_data.shape)\n",
    "    print(\"Clinical data preview:\")\n",
    "    print(clinical_data.head())\n",
    "    \n",
    "    # The clinical data appears to have numeric column names, not sample IDs\n",
    "    # Need to reconstruct clinical data to use proper sample IDs\n",
    "    \n",
    "    # Get sample IDs from gene expression data\n",
    "    sample_ids = normalized_gene_data.columns\n",
    "    \n",
    "    # Reconstruct clinical data with appropriate structure\n",
    "    print(\"Sample IDs from gene expression data:\", sample_ids[:5], \"...\")\n",
    "    \n",
    "    # Get raw clinical data again from the original matrix file\n",
    "    _, clinical_raw = get_background_and_clinical_data(matrix_file)\n",
    "    \n",
    "    # Verify raw clinical data has sample IDs\n",
    "    print(\"Raw clinical data columns:\", clinical_raw.columns[:5], \"...\")\n",
    "    \n",
    "    # Extract trait information using already defined conversion functions\n",
    "    clinical_features = geo_select_clinical_features(\n",
    "        clinical_df=clinical_raw,\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(\"Rebuilt clinical features:\")\n",
    "    print(clinical_features.head())\n",
    "    \n",
    "    # 3. Link clinical and genetic data properly\n",
    "    linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n",
    "    print(f\"Linked data shape: {linked_data.shape}\")\n",
    "    print(\"Linked data preview (first 5 rows, first 5 columns):\")\n",
    "    print(linked_data.iloc[:5, :5])\n",
    "    \n",
    "    # 4. Handle missing values\n",
    "    print(\"Missing values before handling:\")\n",
    "    print(f\"  Trait ({trait}) missing: {linked_data[trait].isna().sum()} out of {len(linked_data)}\")\n",
    "    if 'Age' in linked_data.columns:\n",
    "        print(f\"  Age missing: {linked_data['Age'].isna().sum()} out of {len(linked_data)}\")\n",
    "    if 'Gender' in linked_data.columns:\n",
    "        print(f\"  Gender missing: {linked_data['Gender'].isna().sum()} out of {len(linked_data)}\")\n",
    "    print(f\"  Genes with >20% missing: {sum(linked_data.iloc[:, 3:].isna().mean() > 0.2)}\")\n",
    "    print(f\"  Samples with >5% missing genes: {sum(linked_data.iloc[:, 3:].isna().mean(axis=1) > 0.05)}\")\n",
    "    \n",
    "    cleaned_data = handle_missing_values(linked_data, trait)\n",
    "    print(f\"Data shape after handling missing values: {cleaned_data.shape}\")\n",
    "    \n",
    "    # 5. Evaluate bias in trait and demographic features\n",
    "    is_trait_biased = False\n",
    "    if len(cleaned_data) > 0:\n",
    "        trait_biased, cleaned_data = judge_and_remove_biased_features(cleaned_data, trait)\n",
    "        is_trait_biased = trait_biased\n",
    "    else:\n",
    "        print(\"No data remains after handling missing values.\")\n",
    "        is_trait_biased = True\n",
    "    \n",
    "    # 6. Final validation and save\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=cleaned_data,\n",
    "        note=\"Dataset contains gene expression data of breast cancer vs normal samples. Despite the cohort being in the Cystic_Fibrosis directory, the content is actually related to breast cancer.\"\n",
    "    )\n",
    "    \n",
    "    # 7. Save if usable\n",
    "    if is_usable and len(cleaned_data) > 0:\n",
    "        os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "        cleaned_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 or empty and was not saved\")\n",
    "        \n",
    "except Exception as e:\n",
    "    print(f\"Error processing data: {e}\")\n",
    "    # Handle the error case by still recording cohort info\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=False,  # Mark as not available due to processing issues\n",
    "        is_biased=True, \n",
    "        df=pd.DataFrame(),  # Empty dataframe\n",
    "        note=f\"Error processing data: Dataset seems to be about breast cancer, not cystic fibrosis. Processing failed with error: {str(e)}\"\n",
    "    )\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
}