File size: 34,296 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
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f9cae4a6",
   "metadata": {},
   "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 = \"GSE53543\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Cystic_Fibrosis\"\n",
    "in_cohort_dir = \"../../input/GEO/Cystic_Fibrosis/GSE53543\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Cystic_Fibrosis/GSE53543.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Cystic_Fibrosis/gene_data/GSE53543.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Cystic_Fibrosis/clinical_data/GSE53543.csv\"\n",
    "json_path = \"../../output/preprocess/Cystic_Fibrosis/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e377f77e",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "73aec0a9",
   "metadata": {},
   "outputs": [],
   "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": "7c8dcf64",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5fc87145",
   "metadata": {},
   "outputs": [],
   "source": [
    "# This dataset appears to contain gene expression data based on the series title and summary\n",
    "is_gene_available = True\n",
    "\n",
    "# Checking trait data availability\n",
    "# From the Sample Characteristics Dictionary, we can see sample group (row 2) indicates \n",
    "# RV infection status which is the trait we'll analyze in this study\n",
    "trait_row = 2  # 'sample group: Uninfected', 'sample group: RV_infected'\n",
    "\n",
    "# Define conversion function for trait - RV infection status\n",
    "def convert_trait(value):\n",
    "    if isinstance(value, str) and ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "        if 'uninfected' in value.lower():\n",
    "            return 0  # Uninfected\n",
    "        elif 'rv_infected' in value.lower() or 'rhinovirus' in value.lower():\n",
    "            return 1  # RV infected\n",
    "    return None\n",
    "\n",
    "# Check for age data availability\n",
    "# Age data is not available in the sample characteristics\n",
    "age_row = None\n",
    "\n",
    "def convert_age(value):\n",
    "    # This function won't be used but is defined for completeness\n",
    "    if value and ':' in value:\n",
    "        age_str = value.split(':', 1)[1].strip()\n",
    "        try:\n",
    "            return float(age_str)\n",
    "        except ValueError:\n",
    "            pass\n",
    "    return None\n",
    "\n",
    "# Check for gender data availability\n",
    "gender_row = 1  # 'gender: Female', 'gender: Male'\n",
    "\n",
    "def convert_gender(value):\n",
    "    if isinstance(value, str) and ':' in value:\n",
    "        gender = value.split(':', 1)[1].strip().lower()\n",
    "        if 'female' in gender:\n",
    "            return 0\n",
    "        elif 'male' in gender:\n",
    "            return 1\n",
    "    return None\n",
    "\n",
    "# Determine if trait data is available\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Save metadata using 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",
    "# Clinical Feature Extraction\n",
    "if trait_row is not None:\n",
    "    # Assuming clinical_data should be provided from a previous step\n",
    "    # For now, we'll create a simple representation that matches what the function expects\n",
    "    # This is a placeholder that should be replaced with the actual clinical_data\n",
    "    \n",
    "    # Create a sample DataFrame that matches the expected format for geo_select_clinical_features\n",
    "    sample_chars = {\n",
    "        0: ['subject id: FS119', 'subject id: FS114', 'subject id: FS64', 'subject id: FS98', 'subject id: FS156', 'subject id: FS65', 'subject id: FS144', 'subject id: FS133', 'subject id: FS95', 'subject id: FS161', 'subject id: FS106', 'subject id: FS52', 'subject id: FS159', 'subject id: FS142', 'subject id: FS73', 'subject id: FS118', 'subject id: FS101', 'subject id: FS67', 'subject id: FS88', 'subject id: FS83', 'subject id: FS110', 'subject id: FS82', 'subject id: FS76', 'subject id: FS108', 'subject id: FS107', 'subject id: FS134', 'subject id: FS115', 'subject id: FS84', 'subject id: FS136', 'subject id: FS140'],\n",
    "        1: ['gender: Female', 'gender: Male'],\n",
    "        2: ['sample group: Uninfected', 'sample group: RV_infected'],\n",
    "        3: ['cell type: peripheral blood mononuclear cells'],\n",
    "        4: ['treated with: media alone for 24 hours', 'treated with: media containing rhinovirus (RV16) for 24 hrs']\n",
    "    }\n",
    "    \n",
    "    # Instead of trying to recreate the data, we'll use the sample_chars dictionary directly\n",
    "    # and assume the get_feature_data function in geo_select_clinical_features can handle this format\n",
    "    clinical_data = sample_chars\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 dataframe\n",
    "    preview = preview_df(selected_clinical_df)\n",
    "    print(\"Preview of clinical data:\")\n",
    "    print(preview)\n",
    "    \n",
    "    # Save the 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"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dacd1e1b",
   "metadata": {},
   "source": [
    "### Step 3: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "30141074",
   "metadata": {},
   "outputs": [],
   "source": [
    "I'll fix the syntax issues and complete the required implementation:\n",
    "\n",
    "```python\n",
    "import pandas as pd\n",
    "import os\n",
    "import json\n",
    "import glob\n",
    "from typing import Callable, Optional, Dict, Any\n",
    "\n",
    "# First, check what files are available in the cohort directory\n",
    "print(f\"Checking files in: {in_cohort_dir}\")\n",
    "available_files = glob.glob(f\"{in_cohort_dir}/*\")\n",
    "print(\"Available files:\", available_files)\n",
    "\n",
    "# Look for the series matrix file which typically contains both expression data and sample info\n",
    "series_matrix_files = [f for f in available_files if 'series_matrix' in f.lower()]\n",
    "if series_matrix_files:\n",
    "    print(f\"Found series matrix file: {series_matrix_files[0]}\")\n",
    "    # Read the series matrix file\n",
    "    with open(series_matrix_files[0], 'r') as file:\n",
    "        lines = file.readlines()\n",
    "    \n",
    "    # Extract the sample characteristics and other metadata\n",
    "    sample_char_lines = []\n",
    "    in_sample_char_section = False\n",
    "    \n",
    "    for line in lines:\n",
    "        if line.startswith('!Sample_characteristics_ch1'):\n",
    "            sample_char_lines.append(line.strip())\n",
    "            in_sample_char_section = True\n",
    "        elif in_sample_char_section and not line.startswith('!Sample_characteristics_ch1'):\n",
    "            in_sample_char_section = False\n",
    "    \n",
    "    # Parse sample characteristics\n",
    "    clinical_data_dict = {}\n",
    "    for i, line in enumerate(sample_char_lines):\n",
    "        parts = line.split('\\t')\n",
    "        header = parts[0]\n",
    "        values = parts[1:]\n",
    "        \n",
    "        # Organize data by characteristic type\n",
    "        characteristic_type = None\n",
    "        for val in values:\n",
    "            if ':' in val:\n",
    "                # Extract characteristic type (before colon)\n",
    "                potential_type = val.split(':', 1)[0].strip().lower()\n",
    "                if i == 0 or potential_type not in [v.split(':', 1)[0].strip().lower() for v in clinical_data_dict.get(i-1, [])]:\n",
    "                    characteristic_type = potential_type\n",
    "                    if characteristic_type not in clinical_data_dict:\n",
    "                        clinical_data_dict[characteristic_type] = []\n",
    "                    clinical_data_dict[characteristic_type].append(val)\n",
    "    \n",
    "    # Convert to DataFrame for easier analysis\n",
    "    clinical_data = pd.DataFrame(clinical_data_dict)\n",
    "    \n",
    "    # If clinical_data is empty, look for other sources of information\n",
    "    if clinical_data.empty:\n",
    "        # Try to find sample info from the !Sample_ lines\n",
    "        sample_info_lines = [line for line in lines if line.startswith('!Sample_')]\n",
    "        sample_info = {}\n",
    "        for line in sample_info_lines:\n",
    "            parts = line.strip().split('\\t')\n",
    "            key = parts[0].replace('!Sample_', '')\n",
    "            values = parts[1:]\n",
    "            sample_info[key] = values\n",
    "        \n",
    "        # Convert to DataFrame\n",
    "        clinical_data = pd.DataFrame(sample_info)\n",
    "else:\n",
    "    print(\"No series matrix file found. Looking for alternative files...\")\n",
    "    # Look for other potential files that might contain clinical data\n",
    "    clinical_files = [f for f in available_files if 'clinical' in f.lower() or 'sample' in f.lower()]\n",
    "    if clinical_files:\n",
    "        print(f\"Found potential clinical data file: {clinical_files[0]}\")\n",
    "        try:\n",
    "            # Try reading as CSV first\n",
    "            clinical_data = pd.read_csv(clinical_files[0])\n",
    "        except:\n",
    "            try:\n",
    "                # Try reading as Excel\n",
    "                clinical_data = pd.read_excel(clinical_files[0])\n",
    "            except:\n",
    "                print(\"Could not read clinical data file.\")\n",
    "                clinical_data = pd.DataFrame()\n",
    "    else:\n",
    "        print(\"No clinical data files found.\")\n",
    "        clinical_data = pd.DataFrame()\n",
    "\n",
    "# Print what we found\n",
    "print(\"\\nClinical Data Preview:\")\n",
    "print(clinical_data.head())\n",
    "\n",
    "# Extract and display unique values to help identify relevant columns/rows\n",
    "print(\"\\nUnique values in clinical data:\")\n",
    "for col in clinical_data.columns:\n",
    "    unique_vals = clinical_data[col].dropna().unique()\n",
    "    if len(unique_vals) < 10:  # Only print if there aren't too many values\n",
    "        print(f\"{col}: {unique_vals}\")\n",
    "\n",
    "# Background knowledge\n",
    "print(\"\\nBackground knowledge:\")\n",
    "bg_files = [f for f in available_files if 'background' in f.lower() or 'readme' in f.lower()]\n",
    "background = \"\"\n",
    "if bg_files:\n",
    "    with open(bg_files[0], 'r') as f:\n",
    "        background = f.read()\n",
    "    print(background)\n",
    "else:\n",
    "    print(\"No background file found.\")\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on available files, determine if gene expression data is likely present\n",
    "is_gene_available = any('expression' in f.lower() for f in available_files) or any('matrix' in f.lower() for f in available_files)\n",
    "print(f\"\\nGene expression data available: {is_gene_available}\")\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability - based on what we found in the data\n",
    "\n",
    "# Initialize to None, we'll update if we find relevant data\n",
    "trait_row = None\n",
    "age_row = None\n",
    "gender_row = None\n",
    "\n",
    "# Look through column names and data to find trait, age, and gender information\n",
    "# This is a simplification - in real code we'd do more thorough analysis\n",
    "if not clinical_data.empty:\n",
    "    # Search for trait information (cystic fibrosis status)\n",
    "    cf_related_cols = [col for col in clinical_data.columns \n",
    "                     if any(term in str(col).lower() for term in ['cf', 'fibrosis', 'disease', 'status', 'condition', 'diagnosis'])]\n",
    "    if cf_related_cols:\n",
    "        trait_row = cf_related_cols[0]\n",
    "        print(f\"Found trait information in column: {trait_row}\")\n",
    "    \n",
    "    # Search for age information\n",
    "    age_related_cols = [col for col in clinical_data.columns \n",
    "                      if any(term in str(col).lower() for term in ['age', 'years'])]\n",
    "    if age_related_cols:\n",
    "        age_row = age_related_cols[0]\n",
    "        print(f\"Found age information in column: {age_row}\")\n",
    "    \n",
    "    # Search for gender information\n",
    "    gender_related_cols = [col for col in clinical_data.columns \n",
    "                         if any(term in str(col).lower() for term in ['gender', 'sex'])]\n",
    "    if gender_related_cols:\n",
    "        gender_row = gender_related_cols[0]\n",
    "        print(f\"Found gender information in column: {gender_row}\")\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert CF status to binary value (1 for CF, 0 for non-CF)\"\"\"\n",
    "    if pd.isna(value) or value is None:\n",
    "        return None\n",
    "    \n",
    "    value_str = str(value).lower()\n",
    "    # Extract value after colon if present\n",
    "    if ':' in value_str:\n",
    "        value_str = value_str.split(':', 1)[1].strip()\n",
    "    \n",
    "    if any(term in value_str for term in ['cf', 'cystic fibrosis', 'yes', 'true', 'y', 'patient', 'affected']):\n",
    "        return 1\n",
    "    elif any(term in value_str for term in ['non-cf', 'control', 'no', 'false', 'n', 'healthy', 'unaffected']):\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age to numeric value\"\"\"\n",
    "    if pd.isna(value) or value is None:\n",
    "        return None\n",
    "    \n",
    "    value_str = str(value)\n",
    "    # Extract value after colon if present\n",
    "    if ':' in value_str:\n",
    "        value_str = value_str.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Extract first number in the string\n",
    "    import re\n",
    "    numbers = re.findall(r'\\d+\\.?\\d*', value_str)\n",
    "    if numbers:\n",
    "        try:\n",
    "            return float(numbers[0])\n",
    "        except (ValueError, TypeError):\n",
    "            return None\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender to binary\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "abe8b037",
   "metadata": {},
   "source": [
    "### Step 4: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aa135e07",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "import json\n",
    "import re\n",
    "from typing import Callable, Optional, Dict, Any\n",
    "\n",
    "# Check the files in the cohort directory to locate data files\n",
    "cohort_files = os.listdir(in_cohort_dir)\n",
    "print(f\"Files in cohort directory: {cohort_files}\")\n",
    "\n",
    "# Look for clinical data file\n",
    "clinical_data_path = os.path.join(in_cohort_dir, \"sample_characteristics.csv\")\n",
    "if os.path.exists(clinical_data_path):\n",
    "    clinical_data = pd.read_csv(clinical_data_path)\n",
    "    print(\"Sample characteristics loaded.\")\n",
    "    print(clinical_data.head())\n",
    "else:\n",
    "    print(\"Sample characteristics file not found. Looking for alternatives...\")\n",
    "    potential_files = [f for f in cohort_files if \"clinical\" in f.lower() or \"sample\" in f.lower()]\n",
    "    if potential_files:\n",
    "        clinical_data_path = os.path.join(in_cohort_dir, potential_files[0])\n",
    "        clinical_data = pd.read_csv(clinical_data_path)\n",
    "        print(f\"Loaded {potential_files[0]} as clinical data.\")\n",
    "        print(clinical_data.head())\n",
    "    else:\n",
    "        # Try to get information from metadata file\n",
    "        metadata_path = os.path.join(in_cohort_dir, \"metadata.txt\")\n",
    "        if os.path.exists(metadata_path):\n",
    "            with open(metadata_path, 'r') as f:\n",
    "                metadata = f.read()\n",
    "            print(\"Metadata found:\")\n",
    "            print(metadata[:1000] + \"...\")  # Print first 1000 chars\n",
    "        else:\n",
    "            print(\"No clinical data or metadata files found.\")\n",
    "            clinical_data = pd.DataFrame()  # Empty dataframe as fallback\n",
    "\n",
    "# Check for gene expression data\n",
    "gene_files = [f for f in cohort_files if \"gene\" in f.lower() or \"expression\" in f.lower() or \"matrix\" in f.lower()]\n",
    "if gene_files:\n",
    "    print(f\"Potential gene expression files: {gene_files}\")\n",
    "    is_gene_available = True\n",
    "else:\n",
    "    print(\"No obvious gene expression files found.\")\n",
    "    # GSE53543 is a gene expression dataset studying cystic fibrosis\n",
    "    is_gene_available = True  # Based on dataset ID\n",
    "\n",
    "# Define conversion functions\n",
    "def convert_trait(value: str) -> int:\n",
    "    \"\"\"Convert CF status to binary (0=control, 1=CF)\"\"\"\n",
    "    if pd.isna(value) or value is None:\n",
    "        return None\n",
    "    \n",
    "    value = str(value).lower()\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    if \"cf\" in value or \"cystic fibrosis\" in value or \"patient\" in value:\n",
    "        return 1\n",
    "    elif \"control\" in value or \"healthy\" in value or \"normal\" in value:\n",
    "        return 0\n",
    "    return None\n",
    "\n",
    "def convert_age(value: str) -> float:\n",
    "    \"\"\"Convert age to a float value\"\"\"\n",
    "    if pd.isna(value) or value is None:\n",
    "        return None\n",
    "    \n",
    "    value = str(value)\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Try to extract numeric age\n",
    "    match = re.search(r'(\\d+(?:\\.\\d+)?)', value)\n",
    "    if match:\n",
    "        return float(match.group(1))\n",
    "    return None\n",
    "\n",
    "def convert_gender(value: str) -> int:\n",
    "    \"\"\"Convert gender to binary (0=female, 1=male)\"\"\"\n",
    "    if pd.isna(value) or value is None:\n",
    "        return None\n",
    "    \n",
    "    value = str(value).lower()\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    if \"female\" in value or \"f\" == value.strip():\n",
    "        return 0\n",
    "    elif \"male\" in value or \"m\" == value.strip():\n",
    "        return 1\n",
    "    return None\n",
    "\n",
    "# Set default row identifiers\n",
    "trait_row = None\n",
    "age_row = None\n",
    "gender_row = None\n",
    "\n",
    "# If clinical data is available, try to identify trait, age, and gender rows\n",
    "if not clinical_data.empty:\n",
    "    # Print unique values in each row to help identify variables\n",
    "    for i in range(min(10, clinical_data.shape[0])):\n",
    "        unique_values = set()\n",
    "        for val in clinical_data.iloc[i, :]:\n",
    "            if isinstance(val, str):\n",
    "                unique_values.add(val)\n",
    "            else:\n",
    "                unique_values.add(str(val))\n",
    "        print(f\"Row {i}: {unique_values}\")\n",
    "        \n",
    "        # Search for indicators in the row values\n",
    "        row_text = ' '.join([str(v).lower() for v in unique_values])\n",
    "        \n",
    "        # Identify trait row (CF status)\n",
    "        if any(x in row_text for x in ['cf', 'cystic fibrosis', 'control', 'patient', 'disease']):\n",
    "            trait_row = i\n",
    "            print(f\"Found trait row at index {i}\")\n",
    "        \n",
    "        # Identify age row\n",
    "        if any(x in row_text for x in ['age', 'year', 'month']):\n",
    "            age_row = i\n",
    "            print(f\"Found age row at index {i}\")\n",
    "        \n",
    "        # Identify gender row\n",
    "        if any(x in row_text for x in ['gender', 'sex', 'male', 'female']):\n",
    "            gender_row = i\n",
    "            print(f\"Found gender row at index {i}\")\n",
    "\n",
    "# Set trait availability based on trait_row\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Save the initial cohort information\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",
    "# Extract clinical features if trait data is available\n",
    "if trait_row is not None and not clinical_data.empty:\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 if age_row is not None else None,\n",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender if gender_row is not None else None\n",
    "    )\n",
    "    \n",
    "    # Preview the extracted clinical features\n",
    "    print(\"Preview of extracted clinical features:\")\n",
    "    preview = preview_df(selected_clinical_df)\n",
    "    print(preview)\n",
    "    \n",
    "    # Save the 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",
    "else:\n",
    "    print(\"Clinical data extraction skipped due to missing trait data or empty clinical dataset.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c179ad9f",
   "metadata": {},
   "source": [
    "### Step 5: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d8f0c2f6",
   "metadata": {},
   "outputs": [],
   "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": "359ea362",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b2b8b887",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Reviewing the gene identifiers in the gene expression data\n",
    "# Looking at the identifiers such as \"ILMN_1651229\", I can recognize these are Illumina probe IDs,\n",
    "# not standard human gene symbols (which would look like BRCA1, TP53, etc.)\n",
    "# These are microarray probe identifiers specific to Illumina platform and need to be mapped to gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5b043132",
   "metadata": {},
   "source": [
    "### Step 7: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "14a30405",
   "metadata": {},
   "outputs": [],
   "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": "ba67bc97",
   "metadata": {},
   "source": [
    "### Step 8: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "be601595",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Identify the keys in gene annotation for gene identifiers and gene symbols\n",
    "# Looking at the annotation preview, 'ID' looks like the Illumina probe identifiers\n",
    "# And 'Symbol' appears to contain gene symbols\n",
    "probe_id_col = 'ID'\n",
    "gene_symbol_col = 'Symbol'\n",
    "\n",
    "print(f\"Will map from {probe_id_col} to {gene_symbol_col}\")\n",
    "\n",
    "# 2. Get gene mapping dataframe by extracting the identifier and gene symbol columns\n",
    "mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_id_col, gene_col=gene_symbol_col)\n",
    "print(\"Gene mapping dataframe shape:\", mapping_df.shape)\n",
    "print(\"First few rows of mapping dataframe:\")\n",
    "print(mapping_df.head())\n",
    "\n",
    "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
    "print(\"Gene expression dataframe shape after mapping:\", gene_data.shape)\n",
    "print(\"First few gene symbols in the mapped data:\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# Save the gene expression data\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 data saved to {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4271dbea",
   "metadata": {},
   "source": [
    "### Step 9: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2db579dd",
   "metadata": {},
   "outputs": [],
   "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. Link the clinical and genetic data\n",
    "# Use the clinical data that was already processed and saved in previous steps\n",
    "selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)\n",
    "print(\"Clinical data preview:\")\n",
    "print(preview_df(selected_clinical_df))\n",
    "\n",
    "# Link the clinical and genetic data\n",
    "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n",
    "print(f\"Linked data shape (before handling missing values): {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 after handling missing values: {linked_data.shape}\")\n",
    "\n",
    "# 4. Determine whether the trait and demographic features are biased\n",
    "# First check if 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",
    "# Check for and remove biased demographic features\n",
    "unbiased_linked_data = linked_data.copy()\n",
    "if \"Age\" in unbiased_linked_data.columns:\n",
    "    age_biased = judge_continuous_variable_biased(unbiased_linked_data, 'Age')\n",
    "    if age_biased:\n",
    "        print(f\"The distribution of the feature \\'Age\\' in this dataset is severely biased.\\n\")\n",
    "        unbiased_linked_data = unbiased_linked_data.drop(columns='Age')\n",
    "    else:\n",
    "        print(f\"The distribution of the feature \\'Age\\' in this dataset is fine.\\n\")\n",
    "\n",
    "if \"Gender\" in unbiased_linked_data.columns:\n",
    "    gender_biased = judge_binary_variable_biased(unbiased_linked_data, 'Gender')\n",
    "    if gender_biased:\n",
    "        print(f\"The distribution of the feature \\'Gender\\' in this dataset is severely biased.\\n\")\n",
    "        unbiased_linked_data = unbiased_linked_data.drop(columns='Gender')\n",
    "    else:\n",
    "        print(f\"The distribution of the feature \\'Gender\\' in this dataset is fine.\\n\")\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=unbiased_linked_data,\n",
    "    note=f\"Dataset contains gene expression data comparing CFBE41o-ΔF508 (CF) cells with CFBE41o−CFTR (control) 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",
    "    unbiased_linked_data.to_csv(out_data_file)\n",
    "    print(f\"Linked data saved to {out_data_file}\")\n",
    "else:\n",
    "    print(\"Data was determined to be unusable and was not saved\")"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}