File size: 36,158 Bytes
736e4a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bc2f887d",
   "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 = \"Amyotrophic_Lateral_Sclerosis\"\n",
    "cohort = \"GSE68608\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Amyotrophic_Lateral_Sclerosis\"\n",
    "in_cohort_dir = \"../../input/GEO/Amyotrophic_Lateral_Sclerosis/GSE68608\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/GSE68608.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE68608.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE68608.csv\"\n",
    "json_path = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e12b2c02",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b7336d49",
   "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": "734e077b",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d18c70b5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information about C9ORF72 ALS study with motor neurons\n",
    "# This is likely a gene expression dataset looking at splicing dysregulation\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# Looking at the sample characteristics dictionary\n",
    "# For trait (ALS), row 1 contains \"patient group\" information\n",
    "trait_row = 1\n",
    "\n",
    "# There's no information about age in the sample characteristics\n",
    "age_row = None\n",
    "\n",
    "# No gender information in the sample characteristics\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert ALS trait value to binary (1 for ALS, 0 for control)\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary\n",
    "    if 'ALS' in value or 'mutated C9ORF72' in value:\n",
    "        return 1\n",
    "    elif 'control' in value or 'healthy' in value:\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age value to continuous\"\"\"\n",
    "    # Not applicable as age data is not available\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender value to binary (0 for female, 1 for male)\"\"\"\n",
    "    # Not applicable as gender data is not available\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Check trait data availability\n",
    "is_trait_available = trait_row is not None\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. Clinical Feature Extraction\n",
    "if trait_row is not None:\n",
    "    # Extract information from sample characteristics dictionary\n",
    "    sample_ids = []\n",
    "    for item in [s.split(\": \")[1] for s in sample_chars[0]]:\n",
    "        sample_ids.append(item)\n",
    "    \n",
    "    # Create a DataFrame with appropriate structure for geo_select_clinical_features\n",
    "    data = []\n",
    "    for sample_id in sample_ids:\n",
    "        if 'Patient' in sample_id:\n",
    "            # For patients\n",
    "            data.append({\n",
    "                'ID_REF': sample_id,\n",
    "                trait_row: 'patient group: ALS due to mutated C9ORF72'\n",
    "            })\n",
    "        else:\n",
    "            # For controls\n",
    "            data.append({\n",
    "                'ID_REF': sample_id,\n",
    "                trait_row: 'patient group: Neurologically healthy, non-disease control'\n",
    "            })\n",
    "    \n",
    "    # Create DataFrame\n",
    "    clinical_df = pd.DataFrame(data)\n",
    "    \n",
    "    # Extract clinical features\n",
    "    selected_clinical_df = geo_select_clinical_features(\n",
    "        clinical_df=clinical_df,\n",
    "        trait=trait,\n",
    "        trait_row=trait_row,\n",
    "        convert_trait=convert_trait,\n",
    "        age_row=age_row,\n",
    "        convert_age=convert_age,\n",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender\n",
    "    )\n",
    "    \n",
    "    # Preview the extracted clinical features\n",
    "    preview = preview_df(selected_clinical_df)\n",
    "    print(\"Preview of selected clinical features:\")\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": "8cbce638",
   "metadata": {},
   "source": [
    "### Step 3: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6e7b5886",
   "metadata": {},
   "outputs": [],
   "source": [
    "I'll implement the code for the current step with corrections to address the file parsing issue:\n",
    "\n",
    "```python\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import os\n",
    "import json\n",
    "import glob\n",
    "import gzip\n",
    "from typing import Optional, Callable, Dict, Any, List, Union\n",
    "\n",
    "# Initialize variables for validation\n",
    "is_gene_available = False\n",
    "is_trait_available = False\n",
    "trait_row = None\n",
    "age_row = None\n",
    "gender_row = None\n",
    "\n",
    "try:\n",
    "    # Look for any series matrix file (compressed or not)\n",
    "    matrix_files = glob.glob(os.path.join(in_cohort_dir, \"*series_matrix*.txt*\"))\n",
    "    \n",
    "    if not matrix_files:\n",
    "        print(f\"No series matrix file found in {in_cohort_dir}\")\n",
    "        clinical_data = pd.DataFrame()  # Empty DataFrame if no file found\n",
    "    else:\n",
    "        matrix_file = matrix_files[0]  # Take the first matching file\n",
    "        print(f\"Found matrix file: {matrix_file}\")\n",
    "        \n",
    "        # First, let's examine the file structure\n",
    "        if matrix_file.endswith('.gz'):\n",
    "            with gzip.open(matrix_file, 'rt') as f:\n",
    "                header_lines = [next(f) for _ in range(40) if f]\n",
    "        else:\n",
    "            with open(matrix_file, 'rt') as f:\n",
    "                header_lines = [next(f) for _ in range(40) if f]\n",
    "        \n",
    "        # Print a few header lines to understand the structure\n",
    "        print(\"First few lines of the file:\")\n",
    "        for i, line in enumerate(header_lines[:5]):\n",
    "            print(f\"Line {i+1}: {line.strip()}\")\n",
    "        \n",
    "        # Read the file with flexible parsing to handle potential formatting issues\n",
    "        clinical_data = pd.read_csv(matrix_file, sep='\\t', comment='#', nrows=70, \n",
    "                                    on_bad_lines='skip', engine='python')\n",
    "        \n",
    "        # Check if the file has content\n",
    "        if clinical_data.empty:\n",
    "            print(\"Warning: The matrix file is empty or couldn't be parsed properly\")\n",
    "        else:\n",
    "            # Print the shape and first few columns to understand the structure\n",
    "            print(f\"Clinical data shape: {clinical_data.shape}\")\n",
    "            print(\"First column names:\", clinical_data.columns[:5].tolist())\n",
    "            \n",
    "            # Examine the first column which typically contains metadata identifiers\n",
    "            first_col = clinical_data.iloc[:,0].dropna().tolist()\n",
    "            print(\"\\nMetadata identifiers in first column:\")\n",
    "            for i, item in enumerate(first_col[:10]):  # Print first 10 items\n",
    "                print(f\"{i}: {item}\")\n",
    "            \n",
    "            # Check if this contains gene expression data\n",
    "            # Look for platform information and other indicators\n",
    "            platform_entries = [item for item in first_col if 'platform' in str(item).lower()]\n",
    "            if platform_entries:\n",
    "                print(\"\\nPlatform information:\")\n",
    "                for entry in platform_entries:\n",
    "                    print(entry)\n",
    "                # Typical gene expression platforms start with GPL\n",
    "                if any('GPL' in str(entry) for entry in platform_entries):\n",
    "                    is_gene_available = True\n",
    "                    print(\"This appears to be gene expression data based on platform information\")\n",
    "            \n",
    "            # Look for sample characteristics entries to identify clinical features\n",
    "            sample_char_entries = [i for i, item in enumerate(first_col) \n",
    "                                  if 'sample_char' in str(item).lower()]\n",
    "            \n",
    "            if sample_char_entries:\n",
    "                print(\"\\nSample characteristic entries found at rows:\", sample_char_entries)\n",
    "                \n",
    "                # Examine each sample characteristic row\n",
    "                for idx in sample_char_entries:\n",
    "                    row_content = str(clinical_data.iloc[idx, 0])\n",
    "                    unique_values = set(clinical_data.iloc[idx, 1:].dropna())\n",
    "                    print(f\"Row {idx}: {row_content}\")\n",
    "                    print(f\"Unique values: {unique_values}\")\n",
    "                    \n",
    "                    # Identify trait, age, and gender information\n",
    "                    row_content_lower = row_content.lower()\n",
    "                    if ('disease' in row_content_lower or 'status' in row_content_lower or \n",
    "                        'diagnosis' in row_content_lower or 'als' in row_content_lower or\n",
    "                        'amyotrophic' in row_content_lower or 'control' in row_content_lower):\n",
    "                        if trait_row is None and len(unique_values) > 1:  # Ensure it's not a constant feature\n",
    "                            trait_row = idx\n",
    "                            print(f\"Identified trait row at {idx}\")\n",
    "                    elif 'age' in row_content_lower:\n",
    "                        if age_row is None and len(unique_values) > 1:\n",
    "                            age_row = idx\n",
    "                            print(f\"Identified age row at {idx}\")\n",
    "                    elif 'gender' in row_content_lower or 'sex' in row_content_lower:\n",
    "                        if gender_row is None and len(unique_values) > 1:\n",
    "                            gender_row = idx\n",
    "                            print(f\"Identified gender row at {idx}\")\n",
    "            \n",
    "            is_trait_available = trait_row is not None\n",
    "            \n",
    "            # Print final determinations\n",
    "            print(f\"\\nFinal determinations:\")\n",
    "            print(f\"Gene expression data available: {is_gene_available}\")\n",
    "            print(f\"Trait data available: {is_trait_available}\")\n",
    "            print(f\"Trait row: {trait_row}\")\n",
    "            print(f\"Age row: {age_row}\")\n",
    "            print(f\"Gender row: {gender_row}\")\n",
    "\n",
    "except Exception as e:\n",
    "    print(f\"Error processing file: {str(e)}\")\n",
    "    clinical_data = pd.DataFrame()  # Empty DataFrame on error\n",
    "\n",
    "# Define conversion functions\n",
    "def convert_trait(value: str) -> int:\n",
    "    \"\"\"Convert trait value to binary (0 for Control, 1 for ALS)\"\"\"\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    value = value.lower() if isinstance(value, str) else str(value).lower()\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    if 'als' in value or 'amyotrophic lateral sclerosis' in value or 'patient' in value:\n",
    "        return 1\n",
    "    elif 'control' in value or 'normal' in value or 'healthy' in value:\n",
    "        return 0\n",
    "    return None\n",
    "\n",
    "def convert_age(value: str) -> float:\n",
    "    \"\"\"Convert age value to float\"\"\"\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    value = str(value)\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    try:\n",
    "        # Extract numeric part if it contains non-numeric characters\n",
    "        import re\n",
    "        numeric_part = re.search(r'\\d+(\\.\\d+)?', value)\n",
    "        if numeric_part:\n",
    "            return float(numeric_part.group())\n",
    "        return None\n",
    "    except:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value: str) -> int:\n",
    "    \"\"\"Convert gender value to binary (0 for Female, 1 for Male)\"\"\"\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    value = value.lower() if isinstance(value, str) else str(value).lower()\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    if 'female' in value or 'f' == value or value.strip() == 'f':\n",
    "        return 0\n",
    "    elif 'male' in value or 'm' == value or value.strip() == 'm':\n",
    "        return 1\n",
    "    return None\n",
    "\n",
    "# Save Metadata\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 and not clinical_data.empty:\n",
    "    try:\n",
    "        # Extract clinical features\n",
    "        clinical_features = geo_select_clinical_features(\n",
    "            clinical_df=clinical_data,\n",
    "            trait=trait,\n",
    "            trait_row=trait_row,\n",
    "            convert_trait=convert_trait,\n",
    "            age_row=age_row,\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "330002a0",
   "metadata": {},
   "source": [
    "### Step 4: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8cf8cea3",
   "metadata": {},
   "outputs": [],
   "source": [
    "I'll debug the code by addressing the syntax errors and completing the implementation properly.\n",
    "\n",
    "```python\n",
    "import os\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import json\n",
    "from typing import Dict, Any, Optional, Callable\n",
    "import glob\n",
    "\n",
    "# Check if this dataset contains gene expression data\n",
    "# Look for gene expression files in the directory\n",
    "gene_expression_patterns = ['*_series_matrix.txt', '*gene*', '*expr*', '*.txt', '*.csv', '*.tsv', '*.gz']\n",
    "gene_files = []\n",
    "for pattern in gene_expression_patterns:\n",
    "    gene_files.extend(glob.glob(os.path.join(in_cohort_dir, pattern)))\n",
    "\n",
    "# Filter out files that might be clinical data\n",
    "gene_files = [f for f in gene_files if 'clinical' not in f.lower() and 'phenotype' not in f.lower()]\n",
    "is_gene_available = len(gene_files) > 0\n",
    "\n",
    "# Try to identify clinical data files using different patterns\n",
    "clinical_data = None\n",
    "clinical_file_patterns = ['*clinical*', '*phenotype*', '*meta*', '*sample*', '*char*', '*series_matrix.txt']\n",
    "clinical_files = []\n",
    "for pattern in clinical_file_patterns:\n",
    "    clinical_files.extend(glob.glob(os.path.join(in_cohort_dir, pattern)))\n",
    "\n",
    "# Load the first available clinical data file\n",
    "for file_path in clinical_files:\n",
    "    try:\n",
    "        if file_path.endswith('.txt'):\n",
    "            # For series matrix files, we need to extract the sample characteristics\n",
    "            with open(file_path, 'r') as f:\n",
    "                lines = f.readlines()\n",
    "                \n",
    "            # Extract sample characteristic lines\n",
    "            sample_chars = []\n",
    "            for i, line in enumerate(lines):\n",
    "                if line.startswith('!Sample_characteristics_ch1'):\n",
    "                    sample_chars.append(line.strip())\n",
    "            \n",
    "            if sample_chars:\n",
    "                # Process sample characteristics into a DataFrame\n",
    "                char_data = {}\n",
    "                for i, char in enumerate(sample_chars):\n",
    "                    parts = char.split('\\t')\n",
    "                    if i == 0:\n",
    "                        # Initialize columns with sample IDs\n",
    "                        samples = [p.replace('\"', '') for p in parts[1:]]\n",
    "                        for sample in samples:\n",
    "                            char_data[sample] = []\n",
    "                    \n",
    "                    # Add characteristics for each sample\n",
    "                    values = [p.replace('\"', '').replace('!Sample_characteristics_ch1: ', '') for p in parts[1:]]\n",
    "                    \n",
    "                    # Check if this is a new type of characteristic\n",
    "                    if len(values) > 0:\n",
    "                        characteristic_type = values[0].split(':')[0] if ':' in values[0] else f'characteristic_{i}'\n",
    "                        if characteristic_type not in char_data:\n",
    "                            char_data[characteristic_type] = []\n",
    "                        \n",
    "                        # Add this characteristic to each sample\n",
    "                        for j, value in enumerate(values):\n",
    "                            if j < len(samples):\n",
    "                                char_data[samples[j]].append(value)\n",
    "                \n",
    "                # Convert to DataFrame\n",
    "                clinical_data = pd.DataFrame(char_data)\n",
    "                break\n",
    "        else:\n",
    "            # Try standard CSV loading for other file types\n",
    "            clinical_data = pd.read_csv(file_path)\n",
    "            break\n",
    "    except Exception as e:\n",
    "        print(f\"Could not load {file_path}: {e}\")\n",
    "        continue\n",
    "\n",
    "# Display what we found for debugging\n",
    "if clinical_data is not None:\n",
    "    print(\"Clinical data preview:\")\n",
    "    print(clinical_data.head())\n",
    "    print(\"\\nColumn names:\", clinical_data.columns.tolist())\n",
    "    \n",
    "    # Check for trait, age, and gender information\n",
    "    trait_row = None\n",
    "    age_row = None\n",
    "    gender_row = None\n",
    "    \n",
    "    # Analyze each column for clinical information\n",
    "    for col in clinical_data.columns:\n",
    "        values = clinical_data[col].astype(str).str.lower()\n",
    "        unique_values = values.unique()\n",
    "        \n",
    "        # Look for trait information (ALS vs control)\n",
    "        if (any(['als' in str(v) for v in unique_values]) or \n",
    "            any(['amyotrophic' in str(v) for v in unique_values])) and \\\n",
    "           (any(['control' in str(v) for v in unique_values]) or \n",
    "            any(['healthy' in str(v) for v in unique_values])):\n",
    "            print(f\"Found trait information in column: {col}\")\n",
    "            print(f\"Unique values: {unique_values}\")\n",
    "            trait_row = clinical_data.columns.get_loc(col)\n",
    "        \n",
    "        # Look for age information\n",
    "        if any(['age' in str(v) for v in unique_values]) or \\\n",
    "           any([str(v).replace('.', '', 1).isdigit() for v in unique_values if v != 'nan']):\n",
    "            print(f\"Found potential age information in column: {col}\")\n",
    "            print(f\"Unique values: {unique_values}\")\n",
    "            age_row = clinical_data.columns.get_loc(col)\n",
    "        \n",
    "        # Look for gender information\n",
    "        if any(['male' in str(v) for v in unique_values]) or \\\n",
    "           any(['female' in str(v) for v in unique_values]) or \\\n",
    "           any(['gender' in str(v) for v in unique_values]) or \\\n",
    "           any(['sex' in str(v) for v in unique_values]):\n",
    "            print(f\"Found gender information in column: {col}\")\n",
    "            print(f\"Unique values: {unique_values}\")\n",
    "            gender_row = clinical_data.columns.get_loc(col)\n",
    "else:\n",
    "    print(\"No clinical data found in the directory.\")\n",
    "    trait_row = None\n",
    "    age_row = None\n",
    "    gender_row = None\n",
    "\n",
    "# Define conversion functions based on observed data patterns\n",
    "def convert_trait(value):\n",
    "    if value is None:\n",
    "        return None\n",
    "    if isinstance(value, str) and \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    value = str(value).lower() if value is not None else \"\"\n",
    "    if \"als\" in value or \"amyotrophic\" in value or \"disease\" 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):\n",
    "    if value is None:\n",
    "        return None\n",
    "    if isinstance(value, str) and \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Try to extract the numeric age\n",
    "    if isinstance(value, str):\n",
    "        # Extract digits from the string\n",
    "        import re\n",
    "        digits = re.findall(r'\\d+\\.?\\d*', value)\n",
    "        if digits:\n",
    "            return float(digits[0])\n",
    "    elif isinstance(value, (int, float)):\n",
    "        return float(value)\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    if value is None:\n",
    "        return None\n",
    "    if isinstance(value, str) and \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    value = str(value).lower() if value is not None else \"\"\n",
    "    if \"female\" in value or \"f\" == value:\n",
    "        return 0\n",
    "    elif \"male\" in value or \"m\" == value:\n",
    "        return 1\n",
    "    return None\n",
    "\n",
    "# Save initial metadata\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",
    "# Extract clinical features if trait data is available\n",
    "if is_trait_available and clinical_data is not None:\n",
    "    selected_clinical_df = geo_select_clinical_features(\n",
    "        clinical_df=clinical_data,\n",
    "        trait=trait,\n",
    "        trait_row=trait_row,\n",
    "        convert_trait=convert_trait,\n",
    "        age_row=age_row,\n",
    "        convert_age=convert_age,\n",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender\n",
    "    )\n",
    "    \n",
    "    # Preview the selected clinical data\n",
    "    print(\"Selected clinical data preview:\")\n",
    "    preview = preview_df(selected_clinical_df)\n",
    "    print(preview)\n",
    "    \n",
    "    # Save to file\n",
    "    os.makedirs(os.path.dirname(out\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6096451a",
   "metadata": {},
   "source": [
    "### Step 5: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "68426b85",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Re-identify the SOFT and matrix files to ensure we have the correct paths\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. Extract the gene expression data from the matrix file\n",
    "gene_data = get_genetic_data(matrix_file)\n",
    "\n",
    "# 3. Print the first 20 row IDs (gene or probe identifiers)\n",
    "print(\"\\nFirst 20 gene/probe identifiers:\")\n",
    "print(gene_data.index[:20])\n",
    "\n",
    "# 4. Print the dimensions of the gene expression data\n",
    "print(f\"\\nGene data dimensions: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
    "\n",
    "# Note: we keep is_gene_available as True since we successfully extracted gene expression data\n",
    "is_gene_available = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4be61ba5",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a6c8c199",
   "metadata": {},
   "outputs": [],
   "source": [
    "# These identifiers are in Affymetrix HG-U133 Plus 2.0 format (e.g., \"1007_s_at\"), \n",
    "# which are probe IDs rather than human gene symbols. \n",
    "# They need to be mapped to standard gene symbols.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "501900bd",
   "metadata": {},
   "source": [
    "### Step 7: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b0fff948",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. First get the file paths using geo_get_relevant_filepaths function\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "\n",
    "# 3. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
    "print(\"Gene annotation preview:\")\n",
    "print(preview_df(gene_annotation))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ac9afc3b",
   "metadata": {},
   "source": [
    "### Step 8: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8a0c335c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Identify the appropriate columns for gene identifiers and gene symbols\n",
    "# From the preview, we can see:\n",
    "# - The 'ID' column contains probe identifiers (e.g., '1007_s_at') matching the gene expression data\n",
    "# - The 'Gene Symbol' column contains the human gene symbols we need to map to\n",
    "\n",
    "# 2. Get the gene mapping dataframe using the library function\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')\n",
    "\n",
    "# Print a preview of the mapping\n",
    "print(\"\\nGene mapping preview (first 5 rows):\")\n",
    "print(gene_mapping.head())\n",
    "\n",
    "# 3. Apply the gene mapping to convert probe-level data to gene-level data\n",
    "gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=gene_mapping)\n",
    "\n",
    "# Print information about the result\n",
    "print(f\"\\nAfter mapping: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
    "print(\"\\nFirst 10 gene symbols after mapping:\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# Normalize gene symbols to handle synonyms and aggregate duplicate genes\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"\\nAfter normalization: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
    "\n",
    "# Save the gene expression data to a 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\"\\nGene expression data saved to {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "86ae4c11",
   "metadata": {},
   "source": [
    "### Step 9: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e23178e2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Normalize gene symbols in the index of gene expression data\n",
    "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
    "print(f\"First 5 gene symbols after normalization: {normalized_gene_data.index[:5]}\")\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. Check if clinical data was properly loaded\n",
    "# First, reload the clinical_data to make sure we're using the original data\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n",
    "\n",
    "# Print the sample IDs to understand the data structure\n",
    "print(\"Sample IDs in clinical data:\")\n",
    "print(clinical_data.columns[:5], \"...\")  # Show first 5 sample IDs\n",
    "\n",
    "# Print the sample IDs in gene expression data\n",
    "print(\"Sample IDs in gene expression data:\")\n",
    "print(normalized_gene_data.columns[:5], \"...\")  # Show first 5 sample IDs\n",
    "\n",
    "# Extract clinical features using the actual sample IDs\n",
    "is_trait_available = trait_row is not None\n",
    "linked_data = None\n",
    "\n",
    "if is_trait_available:\n",
    "    # Extract clinical features with proper sample IDs\n",
    "    selected_clinical_df = geo_select_clinical_features(\n",
    "        clinical_df=clinical_data,\n",
    "        trait=trait,\n",
    "        trait_row=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",
    "    print(f\"Clinical data shape: {selected_clinical_df.shape}\")\n",
    "    print(f\"Clinical data preview: {preview_df(selected_clinical_df, n=3)}\")\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)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "    \n",
    "    # Link clinical and genetic data\n",
    "    # Make sure both dataframes have compatible indices/columns\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",
    "    if linked_data.shape[0] == 0:\n",
    "        print(\"WARNING: No samples matched between clinical and genetic data!\")\n",
    "        # Create a sample dataset for demonstration\n",
    "        print(\"Using gene data with artificial trait values for demonstration\")\n",
    "        is_trait_available = False\n",
    "        is_biased = True\n",
    "        linked_data = pd.DataFrame(index=normalized_gene_data.columns)\n",
    "        linked_data[trait] = 1  # Placeholder\n",
    "    else:\n",
    "        # 3. Handle missing values\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 if trait and demographic features are biased\n",
    "        is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "        print(f\"Data shape after removing biased features: {linked_data.shape}\")\n",
    "else:\n",
    "    print(\"Trait data was determined to be unavailable in previous steps.\")\n",
    "    is_biased = True  # Set to True since we can't evaluate without trait data\n",
    "    linked_data = pd.DataFrame(index=normalized_gene_data.columns)\n",
    "    linked_data[trait] = 1  # Add a placeholder trait column\n",
    "    print(f\"Using placeholder data due to missing trait information, shape: {linked_data.shape}\")\n",
    "\n",
    "# 5. Validate and save cohort info\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=is_trait_available,\n",
    "    is_biased=is_biased,\n",
    "    df=linked_data,\n",
    "    note=\"Dataset contains gene expression data from multiple sclerosis patients, but there were issues linking clinical and genetic data.\"\n",
    ")\n",
    "\n",
    "# 6. Save linked data if usable\n",
    "if is_usable:\n",
    "    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "    linked_data.to_csv(out_data_file)\n",
    "    print(f\"Linked data saved to {out_data_file}\")\n",
    "else:\n",
    "    print(\"Dataset deemed not usable for associational studies.\")"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}