File size: 25,964 Bytes
736e4a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "612ce429",
   "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 = \"Bipolar_disorder\"\n",
    "cohort = \"GSE93114\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Bipolar_disorder\"\n",
    "in_cohort_dir = \"../../input/GEO/Bipolar_disorder/GSE93114\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Bipolar_disorder/GSE93114.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Bipolar_disorder/gene_data/GSE93114.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Bipolar_disorder/clinical_data/GSE93114.csv\"\n",
    "json_path = \"../../output/preprocess/Bipolar_disorder/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2f5e023d",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4654810e",
   "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": "0c1f0d8e",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3a2ecb17",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Assess if this dataset is likely to contain gene expression data\n",
    "is_gene_available = True  # Based on Series_title stating \"Gene and MicroRNA expression data\"\n",
    "\n",
    "# 2. Determine data availability and create conversion functions\n",
    "\n",
    "# 2.1 Identifying rows with trait, age, and gender information\n",
    "# The dataset shows all samples have bipolar disorder (constant feature)\n",
    "# According to instructions, constant features are considered not available\n",
    "trait_row = None  # Although row 0 contains disease state, it's a constant value\n",
    "age_row = None    # Age information is not available in the provided data\n",
    "gender_row = None # Gender information is not available in the provided data\n",
    "\n",
    "# 2.2 Define conversion functions for available data\n",
    "\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait (bipolar disorder) value to binary format.\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    if 'bipolar disorder' in value.lower():\n",
    "        return 1\n",
    "    else:\n",
    "        return 0\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age value to numeric format (not used in this dataset).\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    try:\n",
    "        return float(value)\n",
    "    except (ValueError, TypeError):\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender value to binary format (not used in this dataset).\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    value = value.lower()\n",
    "    if value in ['female', 'f']:\n",
    "        return 0\n",
    "    elif value in ['male', 'm']:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Determine trait availability and conduct initial filtering\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Save metadata about dataset usability\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 since trait data is unavailable (constant value)\n",
    "# According to instructions, this step should be skipped if trait_row is None\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ceabadf5",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "929578f0",
   "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": "b5117db2",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f8f9ed8a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# These don't appear to be human gene symbols. Looking at the identifiers like '16650001',\n",
    "# these appear to be probe IDs from a microarray platform (GPL16686 as mentioned in the file name).\n",
    "# Such numeric IDs are not standard gene symbols and will need to be mapped to official gene symbols.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "284d2ed2",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "79ca6f7a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "\n",
    "# 2. 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",
    "# Check if there are any columns that might contain gene information\n",
    "sample_row = gene_annotation.iloc[0].to_dict()\n",
    "print(\"\\nFirst row as dictionary:\")\n",
    "for col, value in sample_row.items():\n",
    "    print(f\"{col}: {value}\")\n",
    "\n",
    "# Check if the SOFT file has the right information for gene mapping\n",
    "print(\"\\nFurther examination needed - this might be a miRNA dataset or using non-standard annotations\")\n",
    "print(\"Looking at the index of gene_data to compare with annotation ID format:\")\n",
    "print(gene_data.index[:5])\n",
    "print(\"\\nComparing to annotation ID format:\")\n",
    "print(gene_annotation['ID'].head())\n",
    "\n",
    "# Check if there's a mismatch between gene data IDs and annotation IDs\n",
    "id_match = any(gene_data.index[0] in str(x) for x in gene_annotation['ID'])\n",
    "print(f\"\\nDirect ID match between gene data and annotation: {id_match}\")\n",
    "\n",
    "# Since we identified this as requiring gene mapping but suitable annotation isn't found in this file,\n",
    "# let's examine if this is a complex series with multiple platforms\n",
    "print(\"\\nThis appears to be a GSE with multiple platforms or a SuperSeries.\")\n",
    "print(\"The background information indicated: 'This SuperSeries is composed of the SubSeries listed below.'\")\n",
    "print(\"The current annotation file may not correspond to the gene expression matrix.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "033f5735",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b085b72b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# This is a SuperSeries, so we need to extract annotation data from the series matrix file\n",
    "# When family SOFT file doesn't have the needed mapping information, we can extract it from matrix file\n",
    "print(f\"Matrix file: {matrix_file}\")\n",
    "\n",
    "# Try a different approach: extract probe-to-gene mapping from the matrix file itself\n",
    "try:\n",
    "    # Often in GEO, annotation information is included as comment lines in the matrix file\n",
    "    platform_info = []\n",
    "    is_platform_section = False\n",
    "    with gzip.open(matrix_file, 'rt') as f:\n",
    "        for line in f:\n",
    "            if line.startswith('!platform_table_begin'):\n",
    "                is_platform_section = True\n",
    "                continue\n",
    "            elif line.startswith('!platform_table_end'):\n",
    "                is_platform_section = False\n",
    "                continue\n",
    "            elif is_platform_section:\n",
    "                platform_info.append(line)\n",
    "    \n",
    "    # If platform info was found in the matrix file\n",
    "    if platform_info:\n",
    "        print(\"Found platform annotation in the matrix file\")\n",
    "        platform_content = \"\".join(platform_info)\n",
    "        platform_df = pd.read_csv(io.StringIO(platform_content), sep='\\t', comment='#')\n",
    "        print(f\"Platform annotation columns: {platform_df.columns.tolist()}\")\n",
    "        \n",
    "        # Look for columns that might contain gene symbols\n",
    "        gene_symbol_cols = [col for col in platform_df.columns if \n",
    "                            any(term in col.lower() for term in \n",
    "                                ['gene_symbol', 'gene symbol', 'gene_name', 'symbol', \n",
    "                                 'gene_assignment', 'gene assignment'])]\n",
    "        \n",
    "        if gene_symbol_cols:\n",
    "            gene_col = gene_symbol_cols[0]\n",
    "            id_col = platform_df.columns[0]  # Usually the first column is the ID\n",
    "            print(f\"Using '{id_col}' for probe IDs and '{gene_col}' for gene symbols\")\n",
    "            \n",
    "            # Create mapping dataframe\n",
    "            mapping_df = platform_df[[id_col, gene_col]].dropna(subset=[gene_col])\n",
    "            mapping_df = mapping_df.rename(columns={id_col: 'ID', gene_col: 'Gene'})\n",
    "            mapping_df['ID'] = mapping_df['ID'].astype(str)\n",
    "            \n",
    "            print(f\"Mapping dataframe shape: {mapping_df.shape}\")\n",
    "            print(\"Mapping preview:\")\n",
    "            print(mapping_df.head())\n",
    "        else:\n",
    "            mapping_df = None\n",
    "            print(\"No gene symbol columns found in the platform annotation\")\n",
    "    else:\n",
    "        mapping_df = None\n",
    "        print(\"No platform annotation found in the matrix file\")\n",
    "    \n",
    "    # If we still don't have mapping information, use an alternative approach\n",
    "    if mapping_df is None or mapping_df.empty:\n",
    "        print(\"Using alternative approach: direct gene symbol extraction\")\n",
    "        # Create a simple mapping dataframe that keeps the original IDs\n",
    "        # This approach assumes the probe IDs themselves might be usable in downstream analysis\n",
    "        mapping_df = pd.DataFrame({'ID': gene_data.index, 'Gene': gene_data.index})\n",
    "        print(f\"Created simple mapping with {len(mapping_df)} entries\")\n",
    "    \n",
    "    # Apply the mapping to convert probe-level measurements to gene expression\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/IDs after mapping:\")\n",
    "    print(list(gene_data.index[:10]))\n",
    "    \n",
    "    # If no mapping was found, we'll proceed with normalized probe IDs\n",
    "    # These will be used as proxies for genes in downstream analysis\n",
    "    print(\"Note: This dataset used probe IDs as gene identifiers due to mapping limitations.\")\n",
    "    \n",
    "except Exception as e:\n",
    "    print(f\"Error in gene mapping process: {e}\")\n",
    "    # Fallback to using original probe IDs if everything else fails\n",
    "    print(\"\\nFallback: Using the probe IDs directly as gene identifiers\")\n",
    "    # Rename the index to avoid confusion\n",
    "    gene_data.index.name = 'Gene'\n",
    "    print(f\"Gene expression data shape: {gene_data.shape}\")\n",
    "    print(\"First 10 probe IDs (used as gene identifiers):\")\n",
    "    print(list(gene_data.index[:10]))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "57602085",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "64fc66ce",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Check if gene data is empty before proceeding\n",
    "if gene_data.empty:\n",
    "    print(\"Warning: Gene expression data is empty after mapping attempt.\")\n",
    "    # Create a placeholder DataFrame with the original probe IDs as a fallback\n",
    "    gene_data = pd.DataFrame(index=gene_data.index)\n",
    "    gene_data = gene_data.reset_index()\n",
    "    gene_data.columns = ['Gene']\n",
    "    gene_data.set_index('Gene', inplace=True)\n",
    "    \n",
    "    # Reapply the original expression data using the probes as proxies for genes\n",
    "    original_gene_data = get_genetic_data(matrix_file)\n",
    "    gene_data = pd.DataFrame(original_gene_data)\n",
    "    gene_data.index.name = 'Gene'\n",
    "    print(f\"Using original probe data as gene proxies. Shape: {gene_data.shape}\")\n",
    "\n",
    "# Save the 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. Link the clinical and genetic data\n",
    "# Based on sample characteristics from step 1:\n",
    "# {0: ['disease state: bipolar disorder'], 1: ['response phenotype, alda scale: excellent responders', 'response phenotype, alda scale: non-responders'], 2: ['cell type: lymphoblastoid cell line']}\n",
    "\n",
    "# Check if there's meaningful clinical data available\n",
    "print(\"Sample characteristics dictionary review:\")\n",
    "print(sample_characteristics_dict)\n",
    "\n",
    "# Based on the sample characteristics, we can see:\n",
    "# - All samples have bipolar disorder (constant trait)\n",
    "# - Row 1 has response phenotype which could be used as a binary trait\n",
    "# - There's no age or gender information available\n",
    "\n",
    "def convert_treatment_response(value):\n",
    "    \"\"\"Convert treatment response to binary format.\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    value = value.lower()\n",
    "    if \"excellent responders\" in value:\n",
    "        return 1  # Excellent responders\n",
    "    elif \"non-responders\" in value:\n",
    "        return 0  # Non-responders\n",
    "    return None\n",
    "\n",
    "# Redefine clinical feature extraction with appropriate row indices\n",
    "# Use row 1 for treatment response as the trait of interest\n",
    "trait_row = 1  # Treatment response phenotype\n",
    "age_row = None  # No age data\n",
    "gender_row = None  # No gender data\n",
    "\n",
    "# Create the clinical data DataFrame\n",
    "clinical_features = []\n",
    "\n",
    "if trait_row is not None:\n",
    "    trait_data = clinical_data.iloc[trait_row:trait_row+1].drop(columns=['!Sample_geo_accession'], errors='ignore')\n",
    "    trait_data.index = [trait]\n",
    "    trait_data = trait_data.apply(convert_treatment_response)\n",
    "    # Convert Series to DataFrame\n",
    "    trait_data = trait_data.to_frame().T\n",
    "    clinical_features.append(trait_data)\n",
    "    \n",
    "selected_clinical_df = pd.concat(clinical_features, axis=0) if clinical_features else pd.DataFrame()\n",
    "\n",
    "print(f\"Selected clinical data shape: {selected_clinical_df.shape}\")\n",
    "print(\"Clinical data preview:\")\n",
    "# Ensure we're passing a DataFrame to preview_df\n",
    "if isinstance(selected_clinical_df, pd.Series):\n",
    "    selected_clinical_df = selected_clinical_df.to_frame().T\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",
    "if not selected_clinical_df.empty and not gene_data.empty:\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:\")\n",
    "    print(preview_df(linked_data.iloc[:5, :5]) if not linked_data.empty else \"Linked data is empty\")\n",
    "\n",
    "    # 3. Handle missing values\n",
    "    if not linked_data.empty:\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 lymphoblastoid cell lines of bipolar disorder patients, with treatment response phenotypes.\"\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.\")\n",
    "    else:\n",
    "        print(\"Linked data is empty. Cannot proceed with analysis.\")\n",
    "        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=True,  # Cannot analyze an empty dataset\n",
    "            df=pd.DataFrame(),  # Empty dataframe\n",
    "            note=\"Failed to link clinical and genetic data. Dataset not usable for analysis.\"\n",
    "        )\n",
    "else:\n",
    "    print(\"Either clinical data or gene data is empty. Cannot create linked data.\")\n",
    "    # Record that this dataset is not usable\n",
    "    validate_and_save_cohort_info(\n",
    "        is_final=True,\n",
    "        cohort=cohort,\n",
    "        info_path=json_path,\n",
    "        is_gene_available=not gene_data.empty,\n",
    "        is_trait_available=not selected_clinical_df.empty,\n",
    "        is_biased=True,  # Cannot analyze without both data types\n",
    "        df=pd.DataFrame(),  # Empty dataframe\n",
    "        note=\"Missing either clinical data or gene data. Dataset not usable for analysis.\"\n",
    "    )\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "906d16ca",
   "metadata": {},
   "source": [
    "### Step 8: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "21eff3ce",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Save the gene data to file (we already have gene_data from a previous step)\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. Link the clinical and genetic data\n",
    "# First, let's extract the clinical features properly based on the sample characteristics:\n",
    "# {0: ['disease state: bipolar disorder'], \n",
    "#  1: ['response phenotype, alda scale: excellent responders', 'response phenotype, alda scale: non-responders'], \n",
    "#  2: ['cell type: lymphoblastoid cell line']}\n",
    "\n",
    "def convert_treatment_response(value):\n",
    "    \"\"\"Convert treatment response to binary format.\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    \n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip().lower()\n",
    "    else:\n",
    "        value = value.lower()\n",
    "        \n",
    "    if \"excellent responders\" in value:\n",
    "        return 1  # Excellent responders\n",
    "    elif \"non-responders\" in value:\n",
    "        return 0  # Non-responders\n",
    "    return None\n",
    "\n",
    "# Define a new trait name for this dataset since we're using treatment response instead of bipolar disorder\n",
    "dataset_trait = \"lithium_response\"  # More specific than the general trait category\n",
    "\n",
    "# Extract clinical features manually with correct approach\n",
    "trait_values = clinical_data.iloc[1].drop(['!Sample_geo_accession'], errors='ignore')\n",
    "trait_values = trait_values.apply(convert_treatment_response)\n",
    "selected_clinical_df = pd.DataFrame({dataset_trait: trait_values}).T\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, dataset_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, dataset_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 from lymphoblastoid cell lines of bipolar disorder patients, classified by lithium treatment response.\"\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
}