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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
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "974f36c8",
   "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 = \"Depression\"\n",
    "cohort = \"GSE201332\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Depression\"\n",
    "in_cohort_dir = \"../../input/GEO/Depression/GSE201332\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Depression/GSE201332.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Depression/gene_data/GSE201332.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Depression/clinical_data/GSE201332.csv\"\n",
    "json_path = \"../../output/preprocess/Depression/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "388a3634",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0d3fa7c1",
   "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": "f5a442f1",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4353b83a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import os\n",
    "import json\n",
    "from typing import Callable, Optional, Dict, Any\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information, this study involves transcriptional profiling\n",
    "# in whole blood samples, which indicates gene expression data is available\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# From the Sample Characteristics Dictionary:\n",
    "# Row 1 contains subject status (healthy controls vs MDD patients) -> trait_row\n",
    "# Row 3 contains age information -> age_row\n",
    "# Row 2 contains gender information -> gender_row\n",
    "trait_row = 1\n",
    "age_row = 3\n",
    "gender_row = 2\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait value to binary (0 for healthy, 1 for depression)\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    value = value.lower().strip()\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    if \"healthy\" in value or \"control\" in value:\n",
    "        return 0\n",
    "    elif \"mdd\" in value or \"depress\" in value:\n",
    "        return 1\n",
    "    return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age value to continuous integer\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Extract numeric part and remove 'y' (years)\n",
    "    if 'y' in value:\n",
    "        try:\n",
    "            return int(value.replace('y', '').strip())\n",
    "        except ValueError:\n",
    "            return None\n",
    "    try:\n",
    "        return int(value)\n",
    "    except ValueError:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender value to binary (0 for female, 1 for male)\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    value = value.lower().strip()\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    if \"female\" in value:\n",
    "        return 0\n",
    "    elif \"male\" in value:\n",
    "        return 1\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata - Initial Filtering\n",
    "# trait_row is not None, so trait data is available\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",
    "# Since trait_row is not None, we need to extract clinical features\n",
    "if trait_row is not None:\n",
    "    # Create a clinical data DataFrame from the sample characteristics dictionary\n",
    "    sample_characteristics = {\n",
    "        0: ['tissue: whole blood'], \n",
    "        1: ['subject status: heathy controls', 'subject status: MDD patients'], \n",
    "        2: ['gender: male', 'gender: female'], \n",
    "        3: ['age: 48y', 'age: 33y', 'age: 43y', 'age: 24y', 'age: 45y', 'age: 36y', 'age: 59y', \n",
    "            'age: 51y', 'age: 26y', 'age: 25y', 'age: 32y', 'age: 39y', 'age: 41y', 'age: 52y', \n",
    "            'age: 53y', 'age: 44y', 'age: 22y', 'age: 47y', 'age: 54y', 'age: 28y', 'age: 30y']\n",
    "    }\n",
    "    \n",
    "    # Convert the dictionary to a DataFrame format that can be used with geo_select_clinical_features\n",
    "    clinical_data = pd.DataFrame(sample_characteristics)\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 extracted features\n",
    "    clinical_preview = preview_df(selected_clinical_df)\n",
    "    print(\"Clinical Data Preview:\")\n",
    "    print(clinical_preview)\n",
    "    \n",
    "    # Save the processed clinical data\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    selected_clinical_df.to_csv(out_clinical_data_file)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b8a39ddd",
   "metadata": {},
   "source": [
    "### Step 3: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "99b99a5e",
   "metadata": {},
   "outputs": [],
   "source": [
    "I'll implement code specifically to handle GEO compressed files and extract sample characteristics from the series matrix file format.\n",
    "\n",
    "```python\n",
    "import os\n",
    "import pandas as pd\n",
    "import json\n",
    "import numpy as np\n",
    "import gzip\n",
    "import re\n",
    "from typing import Callable, Optional, Dict, Any, List, Tuple\n",
    "\n",
    "# Function to extract sample characteristics from GEO series matrix file\n",
    "def extract_geo_characteristics(matrix_file_path: str) -> Tuple[Dict[str, List[str]], pd.DataFrame]:\n",
    "    \"\"\"Extract sample characteristics and data from a GEO series matrix file.\"\"\"\n",
    "    # Initialize variables\n",
    "    characteristics = {}\n",
    "    sample_ids = []\n",
    "    char_indices = {}\n",
    "    in_characteristics = False\n",
    "    series_matrix_lines = []\n",
    "    data_lines = []\n",
    "    \n",
    "    # Read the gzipped file\n",
    "    with gzip.open(matrix_file_path, 'rt') as f:\n",
    "        for line in f:\n",
    "            line = line.strip()\n",
    "            series_matrix_lines.append(line)\n",
    "            \n",
    "            # Detect sample characteristics lines\n",
    "            if line.startswith('!Sample_characteristics_ch'):\n",
    "                in_characteristics = True\n",
    "                parts = line.split('\\t')\n",
    "                key = parts[0].replace('!Sample_characteristics_ch', '').strip()\n",
    "                if key not in char_indices:\n",
    "                    char_indices[key] = len(char_indices)\n",
    "                    characteristics[str(char_indices[key])] = []\n",
    "                \n",
    "                # Add sample characteristic values for each sample\n",
    "                for value in parts[1:]:\n",
    "                    characteristics[str(char_indices[key])].append(value)\n",
    "            \n",
    "            # Collect sample IDs\n",
    "            elif line.startswith('!Sample_geo_accession'):\n",
    "                sample_ids = line.split('\\t')[1:]\n",
    "            \n",
    "            # Detect the beginning of data section\n",
    "            elif line.startswith('!series_matrix_table_begin'):\n",
    "                in_characteristics = False\n",
    "                in_data = True\n",
    "                \n",
    "            # Collect data lines\n",
    "            elif in_data and not line.startswith('!series_matrix_table_end'):\n",
    "                data_lines.append(line)\n",
    "            \n",
    "            # End of data section\n",
    "            elif line.startswith('!series_matrix_table_end'):\n",
    "                break\n",
    "    \n",
    "    # Extract relevant background information for gene availability check\n",
    "    background_info = \"\\n\".join([line for line in series_matrix_lines \n",
    "                                if line.startswith('!Series_summary') or \n",
    "                                   line.startswith('!Series_title') or\n",
    "                                   line.startswith('!Series_type')])\n",
    "    \n",
    "    # Create a DataFrame if data section is found\n",
    "    clinical_data = None\n",
    "    if data_lines:\n",
    "        # First line contains column headers\n",
    "        headers = data_lines[0].split('\\t')\n",
    "        # Data starts from second line\n",
    "        data = [line.split('\\t') for line in data_lines[1:]]\n",
    "        \n",
    "        # Create a DataFrame with gene expression data\n",
    "        gene_data = pd.DataFrame(data, columns=headers)\n",
    "        \n",
    "        # Create a transposed version as clinical data\n",
    "        # Here we assume samples are columns in the original data\n",
    "        clinical_data = pd.DataFrame(index=sample_ids)\n",
    "        \n",
    "    return characteristics, clinical_data, background_info\n",
    "\n",
    "# Find and process GEO series matrix file\n",
    "matrix_file = os.path.join(in_cohort_dir, \"GSE201332_series_matrix.txt.gz\")\n",
    "\n",
    "if os.path.exists(matrix_file):\n",
    "    print(f\"Found matrix file: {matrix_file}\")\n",
    "    sample_characteristics, clinical_data, background_info = extract_geo_characteristics(matrix_file)\n",
    "    \n",
    "    # Print sample characteristics to understand the data structure\n",
    "    for key, values in sample_characteristics.items():\n",
    "        if len(values) > 0:\n",
    "            unique_values = set(values)\n",
    "            print(f\"Key {key}, Example value: {values[0]}\")\n",
    "            print(f\"Key {key}, Unique values: {unique_values if len(unique_values) < 5 else list(unique_values)[:5]}\")\n",
    "else:\n",
    "    print(\"Matrix file not found!\")\n",
    "    sample_characteristics = {}\n",
    "    clinical_data = None\n",
    "    background_info = \"\"\n",
    "\n",
    "# 1. Check for gene expression data availability\n",
    "is_gene_available = True  # Default to True unless we find evidence otherwise\n",
    "\n",
    "if \"miRNA\" in background_info and \"gene expression\" not in background_info.lower():\n",
    "    is_gene_available = False\n",
    "if \"methylation\" in background_info and \"gene expression\" not in background_info.lower():\n",
    "    is_gene_available = False\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "trait_row = None\n",
    "age_row = None\n",
    "gender_row = None\n",
    "\n",
    "# Examine sample characteristics to identify rows for trait, age, and gender\n",
    "if sample_characteristics:\n",
    "    for key, values in sample_characteristics.items():\n",
    "        if not values:  # Skip empty lists\n",
    "            continue\n",
    "            \n",
    "        value_str = \" \".join(values).lower()\n",
    "        \n",
    "        # Look for depression-related indicators in values\n",
    "        depression_keywords = [\"depression\", \"depressive\", \"mdd\", \"major depression\", \"depressed\", \"patient: \"]\n",
    "        if any(keyword.lower() in value_str for keyword in depression_keywords):\n",
    "            trait_row = int(key)\n",
    "        \n",
    "        # Look for age indicators\n",
    "        if any((\"age:\" in val.lower() or \"age :\" in val.lower() or \"years\" in val.lower()) for val in values):\n",
    "            age_row = int(key)\n",
    "        \n",
    "        # Look for gender indicators\n",
    "        if any((\"gender:\" in val.lower() or \"gender :\" in val.lower() or \n",
    "               \"sex:\" in val.lower() or \"sex :\" in val.lower() or\n",
    "               \"male\" in val.lower() or \"female\" in val.lower()) for val in values):\n",
    "            gender_row = int(key)\n",
    "\n",
    "# Define conversion functions\n",
    "def convert_trait(value: str) -> Optional[int]:\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 \"depression\" in value or \"depressive\" in value or \"mdd\" in value or \"patient\" in value:\n",
    "        return 1\n",
    "    elif \"control\" in value or \"healthy\" in value or \"non-depression\" in value or \"normal\" in value:\n",
    "        return 0\n",
    "    return None\n",
    "\n",
    "def convert_age(value: str) -> Optional[float]:\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",
    "    # Extract numeric value (age in years)\n",
    "    age_match = re.search(r'(\\d+(?:\\.\\d+)?)', value)\n",
    "    if age_match:\n",
    "        try:\n",
    "            return float(age_match.group(1))\n",
    "        except ValueError:\n",
    "            return None\n",
    "    return None\n",
    "\n",
    "def convert_gender(value: str) -> Optional[int]:\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() or \"woman\" in value:\n",
    "        return 0\n",
    "    elif \"male\" in value or \"m\" == value.strip() or \"man\" in value:\n",
    "        return 1\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait data availability\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "print(f\"Gene 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",
    "# Conduct initial filtering and 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",
    "# 4. Clinical Feature Extraction\n",
    "# If trait data is available and clinical data exists, extract clinical features\n",
    "if trait_row is not\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f20ce7a6",
   "metadata": {},
   "source": [
    "### Step 4: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e981ccd9",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Task: Dataset Analysis and Clinical Feature Extraction\n",
    "\n",
    "import os\n",
    "import pandas as pd\n",
    "import json\n",
    "import gzip\n",
    "from typing import Optional, Callable, Dict, Any\n",
    "\n",
    "# 1. First, let's examine the available data files in the cohort directory\n",
    "available_files = os.listdir(in_cohort_dir)\n",
    "print(f\"Available files in the cohort directory: {available_files}\")\n",
    "\n",
    "# Let's load the series matrix file which contains both gene expression and clinical data\n",
    "matrix_file = os.path.join(in_cohort_dir, 'GSE201332_series_matrix.txt.gz')\n",
    "\n",
    "# Function to extract sample characteristics from series matrix file\n",
    "def extract_characteristics(file_path):\n",
    "    characteristics_data = []\n",
    "    sample_titles = None\n",
    "    \n",
    "    with gzip.open(file_path, 'rt') as f:\n",
    "        for line in f:\n",
    "            line = line.strip()\n",
    "            if line.startswith('!Sample_geo_accession'):\n",
    "                sample_titles = line.split('\\t')[1:]\n",
    "            elif line.startswith('!Sample_characteristics_ch'):\n",
    "                parts = line.split('\\t')\n",
    "                row_name = parts[0]\n",
    "                values = parts[1:]\n",
    "                characteristics_data.append((row_name, values))\n",
    "            elif line.startswith('!series_matrix_table_begin'):\n",
    "                break\n",
    "    \n",
    "    # Create DataFrame from characteristics\n",
    "    if sample_titles and characteristics_data:\n",
    "        df = pd.DataFrame({i: values for i, (_, values) in enumerate(characteristics_data)})\n",
    "        df.index = sample_titles\n",
    "        return df.transpose()\n",
    "    \n",
    "    return pd.DataFrame()\n",
    "\n",
    "# Extract clinical data\n",
    "clinical_data = extract_characteristics(matrix_file)\n",
    "print(\"\\nClinical data preview:\")\n",
    "print(clinical_data.head())\n",
    "print(f\"Clinical data shape: {clinical_data.shape}\")\n",
    "\n",
    "# Check if gene expression data exists\n",
    "is_gene_available = True  # Default assumption based on the file being a series matrix\n",
    "\n",
    "# Now examine each row to find trait, age, and gender information\n",
    "row_descriptions = []\n",
    "for i, row in clinical_data.iterrows():\n",
    "    unique_values = set(row)\n",
    "    row_descriptions.append((i, unique_values))\n",
    "    print(f\"Row {i}: {list(unique_values)[:3]}{'...' if len(unique_values) > 3 else ''}\")\n",
    "\n",
    "# Based on the row contents, identify trait_row, age_row, and gender_row\n",
    "trait_row = None\n",
    "age_row = None\n",
    "gender_row = None\n",
    "\n",
    "# Define conversion functions\n",
    "def convert_trait(value):\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    value = str(value).lower() if value is not None else \"\"\n",
    "    \n",
    "    # Extract the actual value if there's a colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary: 1 for depression, 0 for control\n",
    "    if any(term in value for term in ['depression', 'mdd', 'major depressive disorder']):\n",
    "        return 1\n",
    "    elif any(term in value for term in ['control', 'healthy', 'normal']):\n",
    "        return 0\n",
    "    return None\n",
    "\n",
    "def convert_age(value):\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    value = str(value)\n",
    "    \n",
    "    # Extract the actual value if there's a colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Try to extract numeric age\n",
    "    import re\n",
    "    age_match = re.search(r'(\\d+(?:\\.\\d+)?)', value)\n",
    "    if age_match:\n",
    "        return float(age_match.group(1))\n",
    "    \n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    value = str(value).lower()\n",
    "    \n",
    "    # Extract the actual value if there's a colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Female: 0, Male: 1\n",
    "    if any(term in value for term in ['f', 'female', 'women', 'woman']):\n",
    "        return 0\n",
    "    elif any(term in value for term in ['m', 'male', 'men', 'man']):\n",
    "        return 1\n",
    "    \n",
    "    return None\n",
    "\n",
    "# Search for trait, age, and gender rows by examining values\n",
    "for i, values in row_descriptions:\n",
    "    values_str = ' '.join([str(v).lower() for v in values])\n",
    "    \n",
    "    # Look for depression/MDD indicators\n",
    "    if trait_row is None and ('depression' in values_str or 'mdd' in values_str or 'control' in values_str):\n",
    "        trait_row = i\n",
    "        print(f\"Found trait row at index {i}\")\n",
    "    \n",
    "    # Look for age indicators\n",
    "    if age_row is None and ('age' in values_str or 'years' in values_str):\n",
    "        age_row = i\n",
    "        print(f\"Found age row at index {i}\")\n",
    "    \n",
    "    # Look for gender indicators\n",
    "    if gender_row is None and ('gender' in values_str or 'sex' in values_str or 'male' in values_str or 'female' in values_str):\n",
    "        gender_row = i\n",
    "        print(f\"Found gender row at index {i}\")\n",
    "\n",
    "# Check trait availability\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Initial validation to check if this dataset is worth processing further\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",
    "# If clinical data is available and trait_row is identified, extract and save features\n",
    "if is_trait_available and clinical_data is not None:\n",
    "    # Extract clinical features\n",
    "    clinical_features = geo_select_clinical_features(\n",
    "        clinical_df=clinical_data,\n",
    "        trait=trait,\n",
    "        trait_row=trait_row,\n",
    "        convert_trait=convert_trait,\n",
    "        age_row=age_row,\n",
    "        convert_age=convert_age 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",
    "    preview = preview_df(clinical_features)\n",
    "    print(\"\\nClinical features preview:\")\n",
    "    print(preview)\n",
    "    \n",
    "    # Save clinical features to CSV\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    clinical_features.to_csv(out_clinical_data_file, index=False)\n",
    "    print(f\"Clinical features saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c17bb83c",
   "metadata": {},
   "source": [
    "### Step 5: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "58437d7e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Get the SOFT and matrix file paths again \n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "print(f\"Matrix file found: {matrix_file}\")\n",
    "\n",
    "# 2. Use the get_genetic_data function from the library to get the gene_data\n",
    "try:\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    print(f\"Gene data shape: {gene_data.shape}\")\n",
    "    \n",
    "    # 3. Print the first 20 row IDs (gene or probe identifiers)\n",
    "    print(\"First 20 gene/probe identifiers:\")\n",
    "    print(gene_data.index[:20])\n",
    "except Exception as e:\n",
    "    print(f\"Error extracting gene data: {e}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9ee549f5",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8b6faf74",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Evaluating gene identifiers\n",
    "# The identifiers shown (1, 2, 3, etc.) are numeric indices, not human gene symbols\n",
    "# These are likely probe IDs or feature IDs from a microarray or sequencing platform\n",
    "# They need to be mapped to proper gene symbols for biological interpretation\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eb01dc47",
   "metadata": {},
   "source": [
    "### Step 7: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8008789d",
   "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",
    "# Check if there are any platforms defined in the SOFT file that might contain annotation data\n",
    "with gzip.open(soft_file, 'rt') as f:\n",
    "    soft_content = f.read()\n",
    "\n",
    "# Look for platform sections in the SOFT file\n",
    "platform_sections = re.findall(r'^!Platform_title\\s*=\\s*(.+)$', soft_content, re.MULTILINE)\n",
    "if platform_sections:\n",
    "    print(f\"Platform title found: {platform_sections[0]}\")\n",
    "\n",
    "# Try to extract more annotation data by reading directly from the SOFT file\n",
    "# Look for lines that might contain gene symbol mappings\n",
    "symbol_pattern = re.compile(r'ID_REF\\s+Symbol|ID\\s+Gene Symbol', re.IGNORECASE)\n",
    "annotation_lines = []\n",
    "with gzip.open(soft_file, 'rt') as f:\n",
    "    for line in f:\n",
    "        if symbol_pattern.search(line):\n",
    "            annotation_lines.append(line)\n",
    "            # Collect the next few lines to see the annotation structure\n",
    "            for _ in range(10):\n",
    "                annotation_lines.append(next(f, ''))\n",
    "\n",
    "if annotation_lines:\n",
    "    print(\"Found potential gene symbol mappings:\")\n",
    "    for line in annotation_lines:\n",
    "        print(line.strip())\n",
    "\n",
    "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
    "print(\"\\nGene annotation preview:\")\n",
    "print(preview_df(gene_annotation, n=10))\n",
    "\n",
    "# If we need an alternative source of mapping, check if there are any other annotation files in the cohort directory\n",
    "cohort_files = os.listdir(in_cohort_dir)\n",
    "annotation_files = [f for f in cohort_files if 'annotation' in f.lower() or 'platform' in f.lower()]\n",
    "if annotation_files:\n",
    "    print(\"\\nAdditional annotation files found in the cohort directory:\")\n",
    "    for file in annotation_files:\n",
    "        print(file)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "38803b07",
   "metadata": {},
   "source": [
    "### Step 8: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5888cd8e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Examine gene_annotation to find the column containing gene symbols\n",
    "print(\"Gene annotation columns:\", gene_annotation.columns.tolist())\n",
    "\n",
    "# After examining the annotation data and the first few rows, I need to determine which\n",
    "# columns contain the gene identifiers and gene symbols\n",
    "\n",
    "# Check if 'GENE_SYMBOL' column exists in the annotation\n",
    "if 'GENE_SYMBOL' in gene_annotation.columns:\n",
    "    gene_col = 'GENE_SYMBOL'\n",
    "elif 'GENE' in gene_annotation.columns:\n",
    "    gene_col = 'GENE'\n",
    "elif 'SYMBOL' in gene_annotation.columns:\n",
    "    gene_col = 'SYMBOL'\n",
    "else:\n",
    "    # If no obvious gene symbol column is found, check if gene symbol information\n",
    "    # might be embedded in another column like NAME or SPOT_ID\n",
    "    # For Agilent platforms, sometimes gene info is in the SEQUENCE column\n",
    "    sample_rows = gene_annotation.iloc[100:120]  # Check rows after control probes\n",
    "    print(\"Sample rows to look for gene symbols:\")\n",
    "    print(sample_rows[['ID', 'NAME', 'SPOT_ID']].head())\n",
    "    \n",
    "    # Default to NAME column which often contains gene information\n",
    "    gene_col = 'NAME'\n",
    "\n",
    "# The ID column should be the probe identifier that matches the gene expression data\n",
    "id_col = 'ID'\n",
    "\n",
    "print(f\"Using {id_col} for probe identifiers and {gene_col} for gene symbols\")\n",
    "\n",
    "# Get mapping between probe IDs and gene symbols\n",
    "mapping_df = get_gene_mapping(gene_annotation, id_col, gene_col)\n",
    "print(f\"Mapping dataframe shape: {mapping_df.shape}\")\n",
    "print(\"Mapping preview:\")\n",
    "print(mapping_df.head(10))\n",
    "\n",
    "# Apply the mapping to convert probe-level data to gene-level data\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
    "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n",
    "print(\"First 10 gene symbols:\")\n",
    "print(gene_data.index[:10].tolist())\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 expression data saved to: {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f722ce84",
   "metadata": {},
   "source": [
    "### Step 9: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "16ba7ece",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "try:\n",
    "    normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "    print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
    "    \n",
    "    # Save the normalized gene data\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",
    "except Exception as e:\n",
    "    print(f\"Error normalizing gene data: {e}\")\n",
    "    normalized_gene_data = gene_data  # Use original data if normalization fails\n",
    "    \n",
    "# 2. Recreate clinical data using correct row indices from step 2\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",
    "# Extract clinical features using correct row indices and conversion functions\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert depression history data to binary format (0 = no, 1 = yes)\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip().lower()\n",
    "    else:\n",
    "        value = value.strip().lower()\n",
    "    \n",
    "    if value == 'yes':\n",
    "        return 1\n",
    "    elif value == 'no':\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age data to continuous format\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if present\n",
    "    if ':' in value:\n",
    "        age_str = value.split(':', 1)[1].strip()\n",
    "    else:\n",
    "        age_str = value.strip()\n",
    "    \n",
    "    try:\n",
    "        return float(age_str)\n",
    "    except ValueError:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender data to binary format (0 = female, 1 = male)\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if present\n",
    "    if ':' in value:\n",
    "        gender = value.split(':', 1)[1].strip().lower()\n",
    "    else:\n",
    "        gender = value.strip().lower()\n",
    "    \n",
    "    if gender == 'female':\n",
    "        return 0\n",
    "    elif gender == 'male':\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# Use correct row indices identified in step 2\n",
    "selected_clinical_df = geo_select_clinical_features(\n",
    "    clinical_df=clinical_data,\n",
    "    trait=trait,  # Using the trait variable from context (Depression)\n",
    "    trait_row=9,  # Using row 9 for depression history as identified in step 2\n",
    "    convert_trait=convert_trait,\n",
    "    age_row=1,    # Age data is in row 1\n",
    "    convert_age=convert_age,\n",
    "    gender_row=2, # Gender data is in row 2\n",
    "    convert_gender=convert_gender\n",
    ")\n",
    "\n",
    "print(f\"Selected clinical data shape: {selected_clinical_df.shape}\")\n",
    "print(\"Clinical data preview:\")\n",
    "print(preview_df(selected_clinical_df))\n",
    "\n",
    "# Save clinical data for future reference\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",
    "# 2. Link clinical and genetic data\n",
    "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "print(\"Linked data preview (first 5 rows, 5 columns):\")\n",
    "print(linked_data.iloc[:5, :5] if not linked_data.empty else \"Linked data is empty\")\n",
    "\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. Check for bias in features\n",
    "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "\n",
    "# 5. Validate 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_biased,\n",
    "    df=linked_data,\n",
    "    note=\"Dataset contains gene expression data from peripheral blood mononuclear cells of older adults with and without depression history, from a study on insomnia disorder.\"\n",
    ")\n",
    "\n",
    "# 6. Save the linked data if usable\n",
    "if is_usable:\n",
    "    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "    linked_data.to_csv(out_data_file)\n",
    "    print(f\"Linked data saved to {out_data_file}\")\n",
    "else:\n",
    "    print(\"Dataset is not usable for analysis. No linked data file saved.\")"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}