File size: 25,872 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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a099ebda",
   "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 = \"GSE110298\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Depression\"\n",
    "in_cohort_dir = \"../../input/GEO/Depression/GSE110298\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Depression/GSE110298.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Depression/gene_data/GSE110298.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Depression/clinical_data/GSE110298.csv\"\n",
    "json_path = \"../../output/preprocess/Depression/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aa9a9c30",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "11b2172f",
   "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": "e0975ad3",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c5c2784d",
   "metadata": {},
   "outputs": [],
   "source": [
    "I understand the task requires creating and analyzing a clinical dataset from the provided sample characteristics dictionary. Here's my implementation:\n",
    "\n",
    "```python\n",
    "import pandas as pd\n",
    "import os\n",
    "import numpy as np\n",
    "import re\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information, this dataset contains microarray data which indicates gene expression\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "\n",
    "# 2.1 Data Availability\n",
    "# For trait (Depression), looking at row 6\n",
    "trait_row = 6  # Depression scores are available in row 6\n",
    "\n",
    "# For age, looking at row 2\n",
    "age_row = 2  # Age is available in row 2\n",
    "\n",
    "# For gender, looking at row 1\n",
    "gender_row = 1  # Gender is available in row 1\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert depression value to binary (0/1)\"\"\"\n",
    "    if pd.isna(value) or value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract numerical value after the colon\n",
    "    if isinstance(value, str) and \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    try:\n",
    "        depression_score = int(value)\n",
    "        # Convert to binary: 0 for no depression (score 0), 1 for any depression symptoms (score > 0)\n",
    "        return 0 if depression_score == 0 else 1\n",
    "    except (ValueError, TypeError):\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age to continuous value\"\"\"\n",
    "    if pd.isna(value) or value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract numerical value after the colon\n",
    "    if isinstance(value, str) and \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    try:\n",
    "        return int(value)\n",
    "    except (ValueError, TypeError):\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender to binary (0 for female, 1 for male)\"\"\"\n",
    "    if pd.isna(value) or value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract value after the colon\n",
    "    if isinstance(value, str) and \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip().lower()\n",
    "    \n",
    "    if 'female' in value:\n",
    "        return 0\n",
    "    elif 'male' in value:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Initial filtering on the usability of the dataset\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",
    "    # Create clinical data from the sample characteristics dictionary\n",
    "    # Sample data from the provided dictionary\n",
    "    sample_characteristics = {\n",
    "        0: ['tissue: hippocampus'], \n",
    "        1: ['sex (self-reported): female', 'sex (self-reported): male'], \n",
    "        2: ['age: 89', 'age: 95', 'age: 84', 'age: 76', 'age: 86', 'age: 96', 'age: 80', 'age: 101', 'age: 85', 'age: 92', 'age: 78', 'age: 88', 'age: 81', 'age: 91', 'age: 99', 'age: 79', 'age: 93', 'age: 87'], \n",
    "        3: ['physical activity tier: low activity', 'physical activity tier: moderate activity', 'physical activity tier: high activity'], \n",
    "        4: ['physical activity: Actical average counts/day: 1.02', 'physical activity: Actical average counts/day: 0.74', 'physical activity: Actical average counts/day: 1.05', 'physical activity: Actical average counts/day: 0.71', 'physical activity: Actical average counts/day: 0.13', 'physical activity: Actical average counts/day: 1.06', 'physical activity: Actical average counts/day: 0.37', 'physical activity: Actical average counts/day: 0.89', 'physical activity: Actical average counts/day: 0.94', 'physical activity: Actical average counts/day: 0.65', 'physical activity: Actical average counts/day: 0.57', 'physical activity: Actical average counts/day: 1.75', 'physical activity: Actical average counts/day: 2', 'physical activity: Actical average counts/day: 1.48', 'physical activity: Actical average counts/day: 1.72', 'physical activity: Actical average counts/day: 2.06', 'physical activity: Actical average counts/day: 1.4', 'physical activity: Actical average counts/day: 1.8', 'physical activity: Actical average counts/day: 1.99', 'physical activity: Actical average counts/day: 1.87', 'physical activity: Actical average counts/day: 1.44', 'physical activity: Actical average counts/day: 2.32', 'physical activity: Actical average counts/day: 2.6', 'physical activity: Actical average counts/day: 3.53', 'physical activity: Actical average counts/day: 2.82', 'physical activity: Actical average counts/day: 4.19', 'physical activity: Actical average counts/day: 5.6', 'physical activity: Actical average counts/day: 3.26', 'physical activity: Actical average counts/day: 2.99', 'physical activity: Actical average counts/day: 4.7'], \n",
    "        5: ['education: 10', 'education: 14', 'education: 16', 'education: 12', 'education: 13', 'education: 21', 'education: 11', 'education: 18', 'education: 20', 'education: 15', 'education: 19', 'education: 22'], \n",
    "        6: ['depression: 0', 'depression: 2', 'depression: 8', 'depression: 1', 'depression: 3', 'depression: 4'], \n",
    "        7: ['cognitive frequency: 2.429', 'cognitive frequency: 3.143', 'cognitive frequency: 3', 'cognitive frequency: 3.714', 'cognitive frequency: NA', 'cognitive frequency: 1', 'cognitive frequency: 1.14', 'cognitive frequency: 2.29', 'cognitive frequency: 2.57', 'cognitive frequency: 3.57', 'cognitive frequency: 3.71', 'cognitive frequency: 3.571', 'cognitive frequency: 3.86', 'cognitive frequency: 2.71', 'cognitive frequency: 4.29', 'cognitive frequency: 3.429', 'cognitive frequency: 3.857', 'cognitive frequency: 4.143', 'cognitive frequency: 2.286', 'cognitive frequency: 2.86', 'cognitive frequency: 4', 'cognitive frequency: 2.43'], \n",
    "        8: ['social frequency: 2.167', 'social frequency: 1.333', 'social frequency: 2.333', 'social frequency: 3', 'social frequency: NA', 'social frequency: 1.83', 'social frequency: 2.83', 'social frequency: 2.17', 'social frequency: 1.5', 'social frequency: 2.33', 'social frequency: 2.5', 'social frequency: 1.833', 'social frequency: 2', 'social frequency: 2.67', 'social frequency: 3.167', 'social frequency: 3.333', 'social frequency: 2.667', 'social frequency: 1.67']\n",
    "    }\n",
    "    \n",
    "    # Convert the sample characteristics dictionary to a DataFrame format expected by geo_select_clinical_features\n",
    "    # We want each row to represent a characteristic and each column to represent a sample\n",
    "    # First, determine\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "68e5dce7",
   "metadata": {},
   "source": [
    "### Step 3: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "30600a63",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Import necessary libraries\n",
    "import pandas as pd\n",
    "import os\n",
    "import json\n",
    "from typing import Callable, Optional, Dict, Any\n",
    "\n",
    "# Since we don't have output from a previous step, let's first check if the files exist\n",
    "# before making assumptions about the data\n",
    "\n",
    "# Check for matrix file which typically contains sample information\n",
    "matrix_files = [f for f in os.listdir(in_cohort_dir) if f.endswith(\"_matrix.txt\")]\n",
    "sample_files = [f for f in os.listdir(in_cohort_dir) if \"sample\" in f.lower() and f.endswith(\".txt\")]\n",
    "clinical_files = [f for f in os.listdir(in_cohort_dir) if \"clinical\" in f.lower()]\n",
    "\n",
    "# Print available files to understand what we're working with\n",
    "print(f\"Files in {in_cohort_dir}:\")\n",
    "for file in os.listdir(in_cohort_dir):\n",
    "    print(f\"  - {file}\")\n",
    "\n",
    "# 1. Determine gene expression data availability\n",
    "# For GEO datasets, we typically look for series matrix files which contain gene expression data\n",
    "# Let's check if any files suggest gene expression data\n",
    "is_gene_available = any(f for f in os.listdir(in_cohort_dir) if \"matrix\" in f.lower() or \"expression\" in f.lower())\n",
    "print(f\"Gene expression data available: {is_gene_available}\")\n",
    "\n",
    "# 2. Variable Availability - Since we don't have sample characteristics data yet, we'll set these to None\n",
    "# We'll need to analyze the actual data in future steps\n",
    "trait_row = None\n",
    "age_row = None\n",
    "gender_row = None\n",
    "\n",
    "# Define conversion functions that will be used if we find the relevant data\n",
    "def convert_trait(value: str) -> int:\n",
    "    \"\"\"Convert depression status to binary (0: Control, 1: Depression).\"\"\"\n",
    "    if value is None:\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",
    "    # Convert to binary\n",
    "    if 'depression' in value or 'mdd' in value or 'case' in value or 'patient' in value:\n",
    "        return 1\n",
    "    elif 'control' in value or 'healthy' in value or 'normal' in value:\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value: str) -> float:\n",
    "    \"\"\"Convert age to float.\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    else:\n",
    "        value = value.strip()\n",
    "    \n",
    "    # Try to extract numeric value\n",
    "    try:\n",
    "        # Handle ranges (e.g., \"25-30\") by taking average\n",
    "        if '-' in value:\n",
    "            parts = value.split('-')\n",
    "            return (float(parts[0]) + float(parts[1])) / 2\n",
    "        \n",
    "        # Handle years notation\n",
    "        if 'years' in value or 'y' in value:\n",
    "            return float(value.replace('years', '').replace('y', '').strip())\n",
    "        \n",
    "        return float(value)\n",
    "    except (ValueError, TypeError):\n",
    "        return None\n",
    "\n",
    "def convert_gender(value: str) -> int:\n",
    "    \"\"\"Convert gender to binary (0: Female, 1: Male).\"\"\"\n",
    "    if value is None:\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",
    "    # Convert to binary\n",
    "    if 'female' in value or 'f' == value:\n",
    "        return 0\n",
    "    elif 'male' in value or 'm' == value:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata with initial filtering\n",
    "# As we don't have enough information yet, we'll set is_trait_available based on trait_row\n",
    "is_trait_available = trait_row is not None\n",
    "print(f\"Trait data available: {is_trait_available}\")\n",
    "\n",
    "# Validate and save cohort information with is_final=False for initial validation\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. Skip clinical feature extraction for now since we don't have confirmed data availability\n",
    "print(\"Clinical feature extraction will be performed in a later step once data availability is confirmed.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1a6d9584",
   "metadata": {},
   "source": [
    "### Step 4: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c2131edc",
   "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": "24032189",
   "metadata": {},
   "source": [
    "### Step 5: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5bf5e3ce",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Reviewing the gene identifiers\n",
    "# These identifiers appear to be probe IDs from Affymetrix microarray platform\n",
    "# Format like \"1007_s_at\" is typical of Affymetrix array probes\n",
    "# These are not standard human gene symbols (like BRCA1, TP53, etc.)\n",
    "# Therefore, they need to be mapped to standard gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0f7dccb2",
   "metadata": {},
   "source": [
    "### Step 6: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "57a5b062",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Get the SOFT and matrix file paths\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "\n",
    "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
    "print(\"\\nGene annotation preview:\")\n",
    "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
    "print(preview_df(gene_annotation, n=5))\n",
    "\n",
    "# Look at the columns available and choose the correct ones for mapping\n",
    "# Based on the columns in the preview, 'ID' is for probe IDs and 'Gene Symbol' contains gene symbols\n",
    "prob_col = 'ID'\n",
    "gene_col = 'Gene Symbol'\n",
    "print(f\"\\nWill use '{prob_col}' for probe IDs and '{gene_col}' for gene symbols in mapping step\")\n",
    "\n",
    "# Test extracting mapping data\n",
    "mapping_data = get_gene_mapping(gene_annotation, prob_col, gene_col)\n",
    "print(f\"\\nMapping data shape: {mapping_data.shape}\")\n",
    "print(\"First few rows of mapping data:\")\n",
    "print(preview_df(mapping_data, n=3))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1845b87c",
   "metadata": {},
   "source": [
    "### Step 7: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b2c774a7",
   "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",
    "\n",
    "# 2. Load the gene expression data again\n",
    "genetic_data = get_genetic_data(matrix_file)\n",
    "print(f\"Loaded genetic data with shape: {genetic_data.shape}\")\n",
    "\n",
    "# 3. Extract gene annotation data from the SOFT file\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "print(f\"Loaded gene annotation data with shape: {gene_annotation.shape}\")\n",
    "\n",
    "# 4. Perform gene identifier mapping\n",
    "print(\"\\nPerforming gene identifier mapping...\")\n",
    "\n",
    "# Create mapping from probe IDs to gene symbols\n",
    "mapping_data = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')\n",
    "print(f\"Created mapping data with shape: {mapping_data.shape}\")\n",
    "print(f\"Sample of mapping data: {preview_df(mapping_data, n=3)}\")\n",
    "\n",
    "# Apply the mapping to convert probe-level measurements to gene-level expression data\n",
    "gene_data = apply_gene_mapping(expression_df=genetic_data, mapping_df=mapping_data)\n",
    "print(f\"Transformed gene data shape after mapping: {gene_data.shape}\")\n",
    "print(\"First 10 gene symbols after mapping:\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# Preview a sample of the mapped gene expression data\n",
    "gene_sample = gene_data.iloc[:5, :5]\n",
    "print(\"\\nSample of gene expression data (first 5 genes, first 5 samples):\")\n",
    "print(gene_sample)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b8fb2cb4",
   "metadata": {},
   "source": [
    "### Step 8: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c9abddc7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Get the SOFT and matrix file paths\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# Re-extract gene expression data and create the gene_data\n",
    "# Load the gene expression data\n",
    "genetic_data = get_genetic_data(matrix_file)\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "mapping_data = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')\n",
    "gene_data = apply_gene_mapping(expression_df=genetic_data, mapping_df=mapping_data)\n",
    "\n",
    "# Normalize gene symbols in the gene expression data\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Gene data shape after normalization: {gene_data.shape}\")\n",
    "\n",
    "# Save the normalized gene data to file\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Gene expression data saved to {out_gene_data_file}\")\n",
    "\n",
    "# 2. Re-extract the clinical 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",
    "# Define conversion functions for clinical features\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert depression score to binary format.\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    value = value.split(\": \")[-1].strip()\n",
    "    try:\n",
    "        # Depression is measured as a score, converting to binary\n",
    "        # 0 = no depression, 1 = any depression symptoms\n",
    "        depression_score = int(value)\n",
    "        return 0 if depression_score == 0 else 1\n",
    "    except:\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",
    "    value = value.split(\": \")[-1].strip()\n",
    "    try:\n",
    "        return float(value)\n",
    "    except:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender data to binary format (0 for female, 1 for male).\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    value = value.split(\": \")[-1].strip().lower()\n",
    "    if \"female\" in value:\n",
    "        return 0\n",
    "    elif \"male\" in value:\n",
    "        return 1\n",
    "    return None\n",
    "\n",
    "# Get clinical data using the identified row indices\n",
    "selected_clinical_df = geo_select_clinical_features(\n",
    "    clinical_df=clinical_data,\n",
    "    trait=trait,\n",
    "    trait_row=6,  # Depression scores in row 6\n",
    "    convert_trait=convert_trait,\n",
    "    age_row=2,    # Age data in row 2\n",
    "    convert_age=convert_age,\n",
    "    gender_row=1, # Gender data in row 1\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\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 hippocampus samples of elderly subjects with depression scores.\"\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
}