File size: 30,607 Bytes
e4183cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ac16a7e6",
   "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 = \"GSE135524\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Depression\"\n",
    "in_cohort_dir = \"../../input/GEO/Depression/GSE135524\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Depression/GSE135524.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Depression/gene_data/GSE135524.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Depression/clinical_data/GSE135524.csv\"\n",
    "json_path = \"../../output/preprocess/Depression/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7a644843",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c4a47f30",
   "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": "f3290c90",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "da652e54",
   "metadata": {},
   "outputs": [],
   "source": [
    "I'll write code for the current step that fixes the syntax issues and correctly processes the clinical data.\n",
    "\n",
    "```python\n",
    "# 1. Gene Expression Data Availability\n",
    "# Checking if gene expression data is available based on the background information\n",
    "# The study seems to involve gene expression analysis in whole blood samples\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "\n",
    "# 2.1 Data Availability\n",
    "# For trait (Depression) - using psychomotor composite score as a proxy for depression severity\n",
    "trait_row = 7  # psychomotor composite score\n",
    "\n",
    "# For age\n",
    "age_row = 1  # age\n",
    "\n",
    "# For gender\n",
    "gender_row = 2  # Sex\n",
    "\n",
    "# 2.2 Data Type Conversion functions\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert psychomotor composite score to a continuous value.\"\"\"\n",
    "    if value is None or not isinstance(value, str):\n",
    "        return None\n",
    "    # Extract the value after the colon\n",
    "    parts = value.split(':', 1)\n",
    "    if len(parts) < 2:\n",
    "        return None\n",
    "    try:\n",
    "        # Convert to float as it's a continuous measure\n",
    "        return float(parts[1].strip())\n",
    "    except (ValueError, TypeError):\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age to a continuous value.\"\"\"\n",
    "    if value is None or not isinstance(value, str):\n",
    "        return None\n",
    "    # Extract the value after the colon\n",
    "    parts = value.split(':', 1)\n",
    "    if len(parts) < 2:\n",
    "        return None\n",
    "    try:\n",
    "        # Convert to int as age is typically a whole number\n",
    "        return int(parts[1].strip())\n",
    "    except (ValueError, TypeError):\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender to a binary value (0 for female, 1 for male).\"\"\"\n",
    "    if value is None or not isinstance(value, str):\n",
    "        return None\n",
    "    # Extract the value after the colon\n",
    "    parts = value.split(':', 1)\n",
    "    if len(parts) < 2:\n",
    "        return None\n",
    "    \n",
    "    gender_value = parts[1].strip().lower()\n",
    "    if 'female' in gender_value:\n",
    "        return 0\n",
    "    elif 'male' in gender_value:\n",
    "        return 1\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait data availability based on trait_row\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Save cohort info using the provided function\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. Clinical Feature Extraction\n",
    "# Only proceed if trait_row is not None\n",
    "if trait_row is not None:\n",
    "    # Create DataFrame from sample characteristics dictionary\n",
    "    # We'll use the sample characteristics dictionary from the previous step output\n",
    "    sample_characteristics_dict = {\n",
    "        0: ['individual: Subject 71', 'individual: Subject 73', 'individual: Subject 74', 'individual: Subject 11', \n",
    "            'individual: Subject 95', 'individual: Subject 41', 'individual: Subject 91', 'individual: Subject 108', \n",
    "            'individual: Subject 109', 'individual: Subject 86', 'individual: Subject 66', 'individual: Subject 85', \n",
    "            'individual: Subject 54', 'individual: Subject 20', 'individual: Subject 103', 'individual: Subject 15', \n",
    "            'individual: Subject 13', 'individual: Subject 46', 'individual: Subject 30', 'individual: Subject 24', \n",
    "            'individual: Subject 105', 'individual: Subject 48', 'individual: Subject 31', 'individual: Subject 37', \n",
    "            'individual: Subject 104', 'individual: Subject 114', 'individual: Subject 61', 'individual: Subject 19', \n",
    "            'individual: Subject 113', 'individual: Subject 110'],\n",
    "        1: ['age: 55', 'age: 56', 'age: 24', 'age: 61', 'age: 40', 'age: 35', 'age: 41', 'age: 26', 'age: 64', \n",
    "            'age: 43', 'age: 29', 'age: 34', 'age: 25', 'age: 28', 'age: 27', 'age: 33', 'age: 51', 'age: 52', \n",
    "            'age: 45', 'age: 42', 'age: 46', 'age: 49', 'age: 38', 'age: 39', 'age: 30', 'age: 32', 'age: 36', \n",
    "            'age: 22', 'age: 37', 'age: 44'],\n",
    "        2: ['Sex: Male', 'Sex: Female'],\n",
    "        3: ['bmi: 24.079', 'bmi: 28.313', 'bmi: 26.549', 'bmi: 25.833', 'bmi: 40.436', 'bmi: 21.658', 'bmi: 52.288', \n",
    "            'bmi: 43.208', 'bmi: 34.132', 'bmi: 32.029', 'bmi: 32.058', 'bmi: 31.462', 'bmi: 27.924', 'bmi: 44.688', \n",
    "            'bmi: 38.714', 'bmi: 47.837', 'bmi: 37.67', 'bmi: 27.179', 'bmi: 29.966', 'bmi: 35.833', 'bmi: 24.355', \n",
    "            'bmi: 48.598', 'bmi: 30.613', 'bmi: 27.653', 'bmi: 28.954', 'bmi: 33.489', 'bmi: 27.836', 'bmi: 39.585', \n",
    "            'bmi: 30.08', 'bmi: 21.696'],\n",
    "        4: ['race: White', 'race: Black'],\n",
    "        5: ['hamd score excluding item 8: 25', 'hamd score excluding item 8: 23', 'hamd score excluding item 8: 21', \n",
    "            'hamd score excluding item 8: 28', 'hamd score excluding item 8: 24', 'hamd score excluding item 8: 29', \n",
    "            'hamd score excluding item 8: 22', 'hamd score excluding item 8: 19', 'hamd score excluding item 8: 30', \n",
    "            'hamd score excluding item 8: 20', 'hamd score excluding item 8: 26', 'hamd score excluding item 8: 27', \n",
    "            'hamd score excluding item 8: 17', 'hamd score excluding item 8: 18'],\n",
    "        6: ['college (yes/no): 1', 'college (yes/no): 0'],\n",
    "        7: ['psychomotor composite score: -0.06308', 'psychomotor composite score: 1.30018', \n",
    "            'psychomotor composite score: -0.41699', 'psychomotor composite score: -0.17858', \n",
    "            'psychomotor composite score: -0.64284', 'psychomotor composite score: -0.32956', \n",
    "            'psychomotor composite score: 0.00218', 'psychomotor composite score: 2.51701', \n",
    "            'psychomotor composite score: 1.2821', 'psychomotor composite score: 0.18995', \n",
    "            'psychomotor composite score: -0.40531', 'psychomotor composite score: 0.57381', \n",
    "            'psychomotor composite score: 0.8438', 'psychomotor composite score: 0.15064', \n",
    "            'psychomotor composite score: 1.89099', 'psychomotor composite score: 1.03181', \n",
    "            'psychomotor composite score: -1.73217', 'psychomotor composite score: -0.65832', \n",
    "            'psychomotor composite score: 0.78252', 'psychomotor composite score: -1.36392', \n",
    "            'psych\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6b997882",
   "metadata": {},
   "source": [
    "### Step 3: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "046d9daf",
   "metadata": {},
   "outputs": [],
   "source": [
    "I'll provide a properly formatted Python code solution for this step:\n",
    "\n",
    "```python\n",
    "# Let's analyze the dataset by looking at the results of the previous step\n",
    "import os\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import json\n",
    "import gzip\n",
    "from typing import Callable, Optional, Dict, Any\n",
    "import re\n",
    "\n",
    "# Let's look for the required files in the cohort directory\n",
    "files = os.listdir(in_cohort_dir)\n",
    "print(f\"Files in {in_cohort_dir}:\")\n",
    "for file in files:\n",
    "    print(file)\n",
    "\n",
    "# First, let's check if there's a series matrix file which would contain the gene expression data\n",
    "series_matrix_files = [f for f in files if \"series_matrix\" in f.lower()]\n",
    "sample_characteristics = {}\n",
    "\n",
    "if series_matrix_files:\n",
    "    print(f\"Found series matrix file: {series_matrix_files[0]}\")\n",
    "    matrix_file = os.path.join(in_cohort_dir, series_matrix_files[0])\n",
    "    \n",
    "    # Use gzip to open the compressed file\n",
    "    with gzip.open(matrix_file, 'rt') as f:\n",
    "        # Read header lines to analyze the dataset\n",
    "        header_lines = []\n",
    "        line = f.readline()\n",
    "        while line and not line.startswith('!series_matrix_table_begin'):\n",
    "            header_lines.append(line.strip())\n",
    "            line = f.readline()\n",
    "        \n",
    "        # Extract sample characteristics\n",
    "        sample_chars_lines = [line for line in header_lines if \"!Sample_characteristics_ch1\" in line]\n",
    "        \n",
    "        if sample_chars_lines:\n",
    "            print(\"Sample characteristics found in series matrix file (first 10):\")\n",
    "            for i, line in enumerate(sample_chars_lines[:10]):\n",
    "                print(line.strip())\n",
    "            \n",
    "            # Build a dictionary to store unique values for each characteristic row\n",
    "            for i, line in enumerate(sample_chars_lines):\n",
    "                # Get sample characteristic values\n",
    "                values = re.findall(r'\"([^\"]*)\"', line)\n",
    "                if i not in sample_characteristics:\n",
    "                    sample_characteristics[i] = []\n",
    "                sample_characteristics[i].extend(values)\n",
    "    \n",
    "    # Print unique values for each characteristic row to help identify relevant rows\n",
    "    print(\"\\nUnique values for each characteristic row:\")\n",
    "    for row, values in sample_characteristics.items():\n",
    "        unique_values = set(values)\n",
    "        print(f\"Row {row}: {unique_values}\")\n",
    "    \n",
    "    # Check if platform description indicates gene expression data\n",
    "    platform_lines = [line for line in header_lines if \"!Platform_\" in line]\n",
    "    platform_tech_lines = [line for line in platform_lines if \"_technology\" in line.lower() or \"_type\" in line.lower()]\n",
    "    \n",
    "    print(\"\\nPlatform information:\")\n",
    "    for line in platform_tech_lines:\n",
    "        print(line)\n",
    "\n",
    "# Based on our analysis of the characteristics rows, let's determine:\n",
    "# 1. Gene expression data availability\n",
    "# Assuming it's gene expression data based on platform information\n",
    "is_gene_available = True  # Update this based on actual platform information\n",
    "\n",
    "# 2. Trait, age, and gender data availability and row identification\n",
    "# For now using None as placeholders, we'll update these after analyzing the data\n",
    "trait_row = None  # Row containing depression status\n",
    "age_row = None    # Row containing age information\n",
    "gender_row = None # Row containing gender information\n",
    "\n",
    "# Let's analyze the sample characteristics to determine the correct rows\n",
    "for row, values in sample_characteristics.items():\n",
    "    unique_values = set(values)\n",
    "    lower_values = [v.lower() if isinstance(v, str) else v for v in unique_values]\n",
    "    \n",
    "    # Check for trait information (depression)\n",
    "    if any((\"depress\" in v or \"mdd\" in v or \"control\" in v or \"patient\" in v or \"case\" in v or \n",
    "            \"healthy\" in v or \"disorder\" in v or \"illness\" in v) for v in lower_values if isinstance(v, str)):\n",
    "        if len(unique_values) > 1:  # Ensure it's not a constant feature\n",
    "            trait_row = row\n",
    "            print(f\"Found Depression trait information at row {row}: {unique_values}\")\n",
    "    \n",
    "    # Check for age information\n",
    "    if any((\"age\" in v.lower() or \"years\" in v.lower()) for v in lower_values if isinstance(v, str)):\n",
    "        if len(unique_values) > 1:  # Ensure it's not a constant feature\n",
    "            age_row = row\n",
    "            print(f\"Found age information at row {row}: {unique_values}\")\n",
    "    \n",
    "    # Check for gender information\n",
    "    if any((\"gender\" in v.lower() or \"sex\" in v.lower() or \"female\" in v.lower() or \"male\" in v.lower()) \n",
    "           for v in lower_values if isinstance(v, str)):\n",
    "        if len(unique_values) > 1:  # Ensure it's not a constant feature\n",
    "            gender_row = row\n",
    "            print(f\"Found gender information at row {row}: {unique_values}\")\n",
    "\n",
    "# Define conversion functions based on the actual data patterns\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert depression trait value to binary (0: control, 1: case).\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    value = value.lower().strip()\n",
    "    \n",
    "    # Extract value after colon if present\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    if any(term in value for term in [\"control\", \"healthy\", \"non-depressed\", \"normal\", \"nd\"]):\n",
    "        return 0\n",
    "    elif any(term in value for term in [\"depressed\", \"mdd\", \"depression\", \"patient\", \"case\"]):\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age value to continuous numeric value.\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    # Extract numeric part after colon if present\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Try to extract numbers from the string\n",
    "    matches = re.findall(r'\\d+(?:\\.\\d+)?', value)\n",
    "    if matches:\n",
    "        try:\n",
    "            age = float(matches[0])\n",
    "            return age\n",
    "        except ValueError:\n",
    "            return None\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender value to binary (0: female, 1: male).\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    value = value.lower().strip()\n",
    "    \n",
    "    # Extract value after colon if present\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    if any(term in value for term in [\"female\", \"f\", \"woman\", \"women\"]):\n",
    "        return 0\n",
    "    elif any(term in value for term in [\"male\", \"m\", \"man\", \"men\"]):\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# Save metadata with initial filtering\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",
    "# If clinical data is available, extract and save it\n",
    "if trait_row is not None:\n",
    "    # Create a DataFrame from the sample characteristics\n",
    "    sample_ids = []\n",
    "    \n",
    "    with gzip.open(os.path.join(in_cohort_dir, series_matrix_files[0]), 'rt') as f:\n",
    "        for line in f:\n",
    "            if line.startswith('!Sample_geo_accession'):\n",
    "                sample_ids = re.findall(r'\"([^\"]*)\"', line)\n",
    "                break\n",
    "    \n",
    "    # Create a DataFrame with the correct structure for geo_select_clinical_features\n",
    "    clinical_data = pd.DataFrame(index=range(len(sample_characteristics)), columns=sample_ids)\n",
    "    \n",
    "    for row, values in sample_characteristics.items():\n",
    "        for i, value in enumerate(values):\n",
    "            if i < len(sample_ids):\n",
    "                clinical_data.iloc[row, i] = value\n",
    "    \n",
    "    # Extract clinical features\n",
    "    selected_clinical = 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\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7618eb97",
   "metadata": {},
   "source": [
    "### Step 4: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "21a4847d",
   "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": "a80ce1f5",
   "metadata": {},
   "source": [
    "### Step 5: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5fa23c4f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Analyzing the gene identifiers\n",
    "\n",
    "# Based on the observed identifiers (ILMN_XXXXXXX), these are Illumina probe IDs,\n",
    "# not standard human gene symbols. Illumina probe IDs are platform-specific identifiers\n",
    "# used in Illumina microarray platforms.\n",
    "\n",
    "# These identifiers need to be mapped to standard human gene symbols\n",
    "# for consistent cross-study analysis and biological interpretation.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7df4da38",
   "metadata": {},
   "source": [
    "### Step 6: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ca1967bd",
   "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": "779a83fd",
   "metadata": {},
   "source": [
    "### Step 7: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ba655e58",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Determine which columns in the gene annotation DataFrame contain probe IDs and gene symbols\n",
    "# Based on the preview, 'ID' column contains probe IDs like ILMN_XXXXXXX, matching the gene_data index\n",
    "# 'Symbol' column contains gene symbols\n",
    "\n",
    "# 2. Extract the probe-to-gene mapping columns\n",
    "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n",
    "print(f\"Mapping dataframe shape: {mapping_df.shape}\")\n",
    "print(\"First few rows of the mapping dataframe:\")\n",
    "print(mapping_df.head())\n",
    "\n",
    "# 3. Apply the gene mapping to convert probe-level measurements to gene-level expression 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 few gene symbols:\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# 4. Normalize gene symbols to ensure consistency\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Gene expression data shape after normalization: {gene_data.shape}\")\n",
    "print(\"First few normalized gene symbols:\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# Save the gene expression data to a CSV file\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Gene expression data saved to {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b11f479a",
   "metadata": {},
   "source": [
    "### Step 8: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "57ff1fdf",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. We'll normalize gene symbols in the gene expression data\n",
    "# Note: We've already done this in step 7, so we can skip this part\n",
    "\n",
    "# 2. Link the clinical and genetic data\n",
    "# First, let's re-acquire the clinical data from the matrix file\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\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",
    "# Load the normalized gene expression data saved in the previous step\n",
    "gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n",
    "print(f\"Loaded gene expression data shape: {gene_data.shape}\")\n",
    "\n",
    "# Define conversion functions for clinical features\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert psychomotor composite score to continuous value.\"\"\"\n",
    "    if isinstance(value, str) and \":\" in value:\n",
    "        parts = value.split(\":\", 1)\n",
    "        if len(parts) == 2:\n",
    "            try:\n",
    "                return float(parts[1].strip())\n",
    "            except ValueError:\n",
    "                return None\n",
    "    return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age to a continuous value.\"\"\"\n",
    "    if isinstance(value, str) and \":\" in value:\n",
    "        parts = value.split(\":\", 1)\n",
    "        if len(parts) == 2:\n",
    "            try:\n",
    "                return int(parts[1].strip())\n",
    "            except ValueError:\n",
    "                return None\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender to a binary value (0 for female, 1 for male).\"\"\"\n",
    "    if isinstance(value, str) and \":\" in value:\n",
    "        parts = value.split(\":\", 1)\n",
    "        if len(parts) == 2:\n",
    "            gender_str = parts[1].strip().lower()\n",
    "            if \"female\" in gender_str:\n",
    "                return 0\n",
    "            elif \"male\" in gender_str:\n",
    "                return 1\n",
    "    return None\n",
    "\n",
    "# Extract clinical features using the correct rows from the sample characteristics\n",
    "selected_clinical_df = geo_select_clinical_features(\n",
    "    clinical_df=clinical_data,\n",
    "    trait=trait,\n",
    "    trait_row=7,  # Psychomotor composite score (row 7)\n",
    "    convert_trait=convert_trait,\n",
    "    age_row=1,    # Age (row 1)\n",
    "    convert_age=convert_age,\n",
    "    gender_row=2, # Sex (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",
    "# Link clinical and genetic data\n",
    "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, 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 whole blood samples of depressed patients with psychomotor slowing traits.\"\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
}