File size: 43,058 Bytes
32677ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "f5c6c4a4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:33:32.568488Z",
     "iopub.status.busy": "2025-03-25T08:33:32.568308Z",
     "iopub.status.idle": "2025-03-25T08:33:32.735935Z",
     "shell.execute_reply": "2025-03-25T08:33:32.735602Z"
    }
   },
   "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 = \"Crohns_Disease\"\n",
    "cohort = \"GSE186963\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Crohns_Disease\"\n",
    "in_cohort_dir = \"../../input/GEO/Crohns_Disease/GSE186963\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Crohns_Disease/GSE186963.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Crohns_Disease/gene_data/GSE186963.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Crohns_Disease/clinical_data/GSE186963.csv\"\n",
    "json_path = \"../../output/preprocess/Crohns_Disease/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1589674e",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "e1e1f6c0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:33:32.737271Z",
     "iopub.status.busy": "2025-03-25T08:33:32.737007Z",
     "iopub.status.idle": "2025-03-25T08:33:32.840700Z",
     "shell.execute_reply": "2025-03-25T08:33:32.840396Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Whole blood gene expression from infliximab treated Crohn's disease patients at three time points: pre-treatment, two weeks and fourteen weeks post first treatment\"\n",
      "!Series_summary\t\"Personalized treatment of complex diseases is an unmet medical need pushing towards drug biomarker identification of one drug-disease combination at a time. Here, we used a novel computational approach for modeling cell-centered individual-level network dynamics from high-dimensional blood data to predict infliximab response and uncover individual variation of non-response. We identified and validated that the RAC1-PAK1 axis is predictive of infliximab response in inflammatory bowel disease. Intermediate monocytes, which closely correlated with inflammation state, play a key role in the RAC1-PAK1 responses, supporting their modulation as a therapeutic target. This axis also predicts response in Rheumatoid arthritis, validated in three public cohorts. Our findings support pan-disease drug response diagnostics from blood, implicating common mechanisms of drug response or failure across diseases.\"\n",
      "!Series_overall_design\t\"Whole blood samples from anti-TNF responding (n=15) and non-responding (n=9) IBD patients at three time points: pre-treatment, two weeks and fourteen weeks post first treatment\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: [\"disease: Crohn's disease\"], 1: ['treatment: Infliximab'], 2: ['patient: HR-38', 'patient: HR-39', 'patient: HR-40', 'patient: HR-42', 'patient: HR-44', 'patient: HR-46', 'patient: HR-47', 'patient: HR-48', 'patient: HR-29', 'patient: HR-30', 'patient: HR-31', 'patient: HR-32', 'patient: HR-33', 'patient: HR-35', 'patient: HR-36', 'patient: HR-37', 'patient: HR-20', 'patient: HR-21', 'patient: HR-22', 'patient: HR-23', 'patient: HR-24', 'patient: HR-26', 'patient: HR-27', 'patient: HR-28'], 3: ['response status: Non-responder', 'response status: Responder'], 4: ['visit: Baseline', 'visit: W2', 'visit: W14'], 5: ['crp: 2.1', 'crp: 1.2', 'crp: 2', 'crp: 2.6', 'crp: 0.1', 'crp: 0.4', 'crp: 1', 'crp: 1.1', 'crp: 2.67', 'crp: 3.4', 'crp: 0.9', 'crp: 0.48', 'crp: 19.6', 'crp: 1.19', 'crp: 6.8', 'crp: 3.22', 'crp: 3', 'crp: 125.7', 'crp: 2.7', 'crp: 24.2', 'crp: 1.8', 'crp: 0.8', 'crp: 4.9', 'crp: 2.5', 'crp: 1.15', 'crp: 15.8', 'crp: 4.78', 'crp: 43.6', 'crp: 44', 'crp: 5.43']}\n"
     ]
    }
   ],
   "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": "ffbb7dca",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "e15ed7e8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:33:32.842060Z",
     "iopub.status.busy": "2025-03-25T08:33:32.841946Z",
     "iopub.status.idle": "2025-03-25T08:33:32.845667Z",
     "shell.execute_reply": "2025-03-25T08:33:32.845377Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Since we don't have access to the properly formatted clinical data at this stage, we'll skip the clinical feature extraction.\n",
      "We've recorded that trait data is available (response status) for the initial filtering.\n"
     ]
    }
   ],
   "source": [
    "# Step 1: Determine if gene expression data is available\n",
    "# Based on the background information about whole blood gene expression, this dataset is likely to contain gene expression data\n",
    "is_gene_available = True\n",
    "\n",
    "# Step 2.1: Identify rows in the sample characteristics dictionary for trait, age, and gender\n",
    "# For response status (which we can use as our trait of interest), we can find it in row 3\n",
    "# Looking at the data, everyone has Crohn's disease (row 0), so it's a constant feature\n",
    "# Instead, we'll use response status (row 3) as our trait of interest\n",
    "trait_row = 3\n",
    "\n",
    "# For age: Not available in the dictionary\n",
    "age_row = None\n",
    "\n",
    "# For gender: Not available in the dictionary\n",
    "gender_row = None\n",
    "\n",
    "# Step 2.2: Create conversion functions for available variables\n",
    "\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert response status to binary (0 for Non-responder, 1 for Responder)\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    if value.lower() == 'responder':\n",
    "        return 1\n",
    "    elif value.lower() == 'non-responder':\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age to float, but since age is not available, this function won't be used\"\"\"\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender to binary (0 for female, 1 for male), but since gender is not available, this function won't be used\"\"\"\n",
    "    return None\n",
    "\n",
    "# Step 3: Validate and save metadata\n",
    "# Trait data is available since trait_row is not None\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Save the metadata\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# Step 4: Skip clinical feature extraction for now since we don't have access to the proper clinical_data\n",
    "# We've already recorded that trait data is available, which is what's needed for the initial filtering\n",
    "print(\"Since we don't have access to the properly formatted clinical data at this stage, we'll skip the clinical feature extraction.\")\n",
    "print(\"We've recorded that trait data is available (response status) for the initial filtering.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "efb0606a",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "1f947a6f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:33:32.846861Z",
     "iopub.status.busy": "2025-03-25T08:33:32.846756Z",
     "iopub.status.idle": "2025-03-25T08:33:33.014678Z",
     "shell.execute_reply": "2025-03-25T08:33:33.014298Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "First 20 gene/probe identifiers:\n",
      "Index(['TC0100006437.hg.1', 'TC0100006476.hg.1', 'TC0100006479.hg.1',\n",
      "       'TC0100006480.hg.1', 'TC0100006483.hg.1', 'TC0100006486.hg.1',\n",
      "       'TC0100006490.hg.1', 'TC0100006492.hg.1', 'TC0100006494.hg.1',\n",
      "       'TC0100006497.hg.1', 'TC0100006499.hg.1', 'TC0100006501.hg.1',\n",
      "       'TC0100006502.hg.1', 'TC0100006514.hg.1', 'TC0100006516.hg.1',\n",
      "       'TC0100006517.hg.1', 'TC0100006524.hg.1', 'TC0100006540.hg.1',\n",
      "       'TC0100006548.hg.1', 'TC0100006550.hg.1'],\n",
      "      dtype='object', name='ID')\n",
      "\n",
      "Gene data dimensions: 19577 genes × 72 samples\n"
     ]
    }
   ],
   "source": [
    "# 1. Re-identify the SOFT and matrix files to ensure we have the correct paths\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. Extract the gene expression data from the matrix file\n",
    "gene_data = get_genetic_data(matrix_file)\n",
    "\n",
    "# 3. Print the first 20 row IDs (gene or probe identifiers)\n",
    "print(\"\\nFirst 20 gene/probe identifiers:\")\n",
    "print(gene_data.index[:20])\n",
    "\n",
    "# 4. Print the dimensions of the gene expression data\n",
    "print(f\"\\nGene data dimensions: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
    "\n",
    "# Note: we keep is_gene_available as True since we successfully extracted gene expression data\n",
    "is_gene_available = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9d0b97ef",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "f3bf04a0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:33:33.016103Z",
     "iopub.status.busy": "2025-03-25T08:33:33.015981Z",
     "iopub.status.idle": "2025-03-25T08:33:33.017875Z",
     "shell.execute_reply": "2025-03-25T08:33:33.017592Z"
    }
   },
   "outputs": [],
   "source": [
    "# The identifiers shown (like 'TC0100006437.hg.1') appear to be probe IDs from an Affymetrix microarray platform,\n",
    "# specifically the Clariom D Human array based on the 'TC' prefix and '.hg.1' suffix.\n",
    "# These are not standard human gene symbols (like BRCA1, TP53, etc.), so they will need to be mapped.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f29eba43",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "7751301d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:33:33.019186Z",
     "iopub.status.busy": "2025-03-25T08:33:33.019078Z",
     "iopub.status.idle": "2025-03-25T08:33:36.177102Z",
     "shell.execute_reply": "2025-03-25T08:33:36.176709Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation dataframe column names:\n",
      "Index(['ID', 'probeset_id', 'seqname', 'strand', 'start', 'stop',\n",
      "       'total_probes', 'category', 'SPOT_ID', 'SPOT_ID.1'],\n",
      "      dtype='object')\n",
      "\n",
      "Preview of gene annotation data:\n",
      "{'ID': ['TC0100006437.hg.1', 'TC0100006476.hg.1', 'TC0100006479.hg.1'], 'probeset_id': ['TC0100006437.hg.1', 'TC0100006476.hg.1', 'TC0100006479.hg.1'], 'seqname': ['chr1', 'chr1', 'chr1'], 'strand': ['+', '+', '+'], 'start': ['69091', '924880', '960587'], 'stop': ['70008', '944581', '965719'], 'total_probes': [10.0, 10.0, 10.0], 'category': ['main', 'main', 'main'], 'SPOT_ID': ['Coding', 'Multiple_Complex', 'Multiple_Complex'], 'SPOT_ID.1': ['NM_001005484 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 5 (OR4F5), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000335137 // ENSEMBL // olfactory receptor, family 4, subfamily F, member 5 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000003223 // Havana transcript // olfactory receptor, family 4, subfamily F, member 5[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// uc001aal.1 // UCSC Genes // Homo sapiens olfactory receptor, family 4, subfamily F, member 5 (OR4F5), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// CCDS30547.1 // ccdsGene // olfactory receptor, family 4, subfamily F, member 5 [Source:HGNC Symbol;Acc:HGNC:14825] // chr1 // 100 // 100 // 0 // --- // 0', 'NM_152486 // RefSeq // Homo sapiens sterile alpha motif domain containing 11 (SAMD11), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000341065 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000342066 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000420190 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000437963 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000455979 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000464948 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000466827 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000474461 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000478729 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:processed_transcript] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000616016 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000616125 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000617307 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000618181 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000618323 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000618779 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000620200 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000622503 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// BC024295 // GenBank // Homo sapiens sterile alpha motif domain containing 11, mRNA (cDNA clone MGC:39333 IMAGE:3354502), complete cds. // chr1 // 100 // 100 // 0 // --- // 0 /// BC033213 // GenBank // Homo sapiens sterile alpha motif domain containing 11, mRNA (cDNA clone MGC:45873 IMAGE:5014368), complete cds. // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097860 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097862 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097863 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097865 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:processed_transcript] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097866 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097867 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097868 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000276866 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000316521 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// CCDS2.2 // ccdsGene // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009185 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVERLAPTX, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009186 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVERLAPTX, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009187 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009188 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009189 // circbase // Salzman2013 ALT_DONOR, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009190 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009191 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009192 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVERLAPTX, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009193 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVERLAPTX, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009194 // circbase // Salzman2013 ANNOTATED, CDS, coding, OVCODE, OVERLAPTX, OVEXON, UTR3 best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009195 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVERLAPTX, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// uc001abw.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pjt.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pju.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pkg.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pkh.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pkk.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pkm.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pko.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axs.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axt.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axu.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axv.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axw.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axx.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axy.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axz.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057aya.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000212 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000212 // NONCODE // Non-coding transcript identified by NONCODE: Exonic // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000213 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000213 // NONCODE // Non-coding transcript identified by NONCODE: Exonic // chr1 // 100 // 100 // 0 // --- // 0', 'NM_198317 // RefSeq // Homo sapiens kelch-like family member 17 (KLHL17), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000338591 // ENSEMBL // kelch-like family member 17 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000463212 // ENSEMBL // kelch-like family member 17 [gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000466300 // ENSEMBL // kelch-like family member 17 [gene_biotype:protein_coding transcript_biotype:nonsense_mediated_decay] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000481067 // ENSEMBL // kelch-like family member 17 [gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000622660 // ENSEMBL // kelch-like family member 17 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097875 // Havana transcript // kelch-like 17 (Drosophila)[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097877 // Havana transcript // kelch-like 17 (Drosophila)[gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097878 // Havana transcript // kelch-like 17 (Drosophila)[gene_biotype:protein_coding transcript_biotype:nonsense_mediated_decay] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097931 // Havana transcript // kelch-like 17 (Drosophila)[gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// BC166618 // GenBank // Synthetic construct Homo sapiens clone IMAGE:100066344, MGC:195481 kelch-like 17 (Drosophila) (KLHL17) mRNA, encodes complete protein. // chr1 // 100 // 100 // 0 // --- // 0 /// CCDS30550.1 // ccdsGene // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009209 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_198317 // chr1 // 100 // 100 // 0 // --- // 0 /// uc001aca.3 // UCSC Genes // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// uc001acb.2 // UCSC Genes // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057ayg.1 // UCSC Genes // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057ayh.1 // UCSC Genes // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057ayi.1 // UCSC Genes // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057ayj.1 // UCSC Genes // N/A // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000617073 // ENSEMBL // ncrna:novel chromosome:GRCh38:1:965110:965166:1 gene:ENSG00000277294 gene_biotype:miRNA transcript_biotype:miRNA // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000216 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000216 // NONCODE // Non-coding transcript identified by NONCODE: Exonic // chr1 // 100 // 100 // 0 // --- // 0']}\n"
     ]
    }
   ],
   "source": [
    "# 1. First get the file paths using geo_get_relevant_filepaths function\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. Extract gene annotation data from the SOFT file\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "\n",
    "# 3. Preview the gene annotation dataframe\n",
    "print(\"Gene annotation dataframe column names:\")\n",
    "print(gene_annotation.columns)\n",
    "\n",
    "# Preview the first few rows to understand the data structure\n",
    "print(\"\\nPreview of gene annotation data:\")\n",
    "annotation_preview = preview_df(gene_annotation, n=3)\n",
    "print(annotation_preview)\n",
    "\n",
    "# Maintain gene availability status as True based on previous steps\n",
    "is_gene_available = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5a71d53e",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "a745e360",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:33:36.178735Z",
     "iopub.status.busy": "2025-03-25T08:33:36.178584Z",
     "iopub.status.idle": "2025-03-25T08:33:51.389071Z",
     "shell.execute_reply": "2025-03-25T08:33:51.388681Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Analyzing gene annotation format...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found gene symbols for 17945/1436805 probes (1.2%)\n",
      "\n",
      "Sample of probe to gene mappings:\n",
      "Probe: TC0100006437.hg.1, Genes: ['OR4F5']\n",
      "Probe: TC0100006476.hg.1, Genes: ['SAMD11']\n",
      "Probe: TC0100006479.hg.1, Genes: ['KLHL17']\n",
      "Probe: TC0100006480.hg.1, Genes: ['PLEKHN1']\n",
      "Probe: TC0100006483.hg.1, Genes: ['ISG15']\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Converted gene expression data dimensions: 0 genes × 72 samples\n",
      "\n",
      "WARNING: No genes were mapped. The gene expression matrix is empty.\n",
      "\n",
      "Gene expression data saved to ../../output/preprocess/Crohns_Disease/gene_data/GSE186963.csv\n"
     ]
    }
   ],
   "source": [
    "# Examine the annotation data to identify gene symbols\n",
    "print(\"Analyzing gene annotation format...\")\n",
    "\n",
    "# Step 1: Look at the SPOT_ID.1 column which contains gene information\n",
    "def extract_better_gene_symbols(text):\n",
    "    \"\"\"Extract gene symbols from the annotation text using a more targeted approach\"\"\"\n",
    "    if not isinstance(text, str):\n",
    "        return []\n",
    "    \n",
    "    # Look for RefSeq pattern: gene name in parentheses\n",
    "    # Example: \"olfactory receptor, family 4, subfamily F, member 5 (OR4F5)\"\n",
    "    refseq_pattern = re.compile(r'([A-Za-z0-9\\-]+\\s+)+\\(([A-Z0-9\\-]{1,15})\\)')\n",
    "    refseq_matches = refseq_pattern.findall(text)\n",
    "    symbols = [match[1] for match in refseq_matches if match[1] not in ('RNA', 'DNA', 'PCR', 'EST', 'CHR')]\n",
    "    \n",
    "    # Also look for HGNC pattern: [Source:HGNC Symbol;Acc:HGNC:XXXXX]\n",
    "    hgnc_pattern = re.compile(r'\\[Source:HGNC Symbol;Acc:HGNC:\\d+\\]\\s+//\\s+([A-Z0-9\\-]{1,15})')\n",
    "    hgnc_matches = hgnc_pattern.findall(text)\n",
    "    symbols.extend([m for m in hgnc_matches if m not in ('RNA', 'DNA', 'PCR', 'EST', 'CHR')])\n",
    "    \n",
    "    # Common non-gene terms that appear in the annotations\n",
    "    exclude_terms = {'ENSEMBL', 'UCSC', 'MGC', 'IMAGE', 'CDS', 'INTERNAL', 'OVCODE', \n",
    "                     'OVERLAPTX', 'OVEXON', 'UTR3', 'NONCODE', 'ANNOTATED', 'ID', \n",
    "                     'CCDS', 'CHR', 'RNA', 'DNA', 'PCR', 'EST'}\n",
    "    \n",
    "    # Remove any non-gene terms\n",
    "    symbols = [s for s in symbols if s not in exclude_terms]\n",
    "    \n",
    "    # Deduplicate while maintaining order\n",
    "    return list(dict.fromkeys(symbols))\n",
    "\n",
    "# Create a mapping dataframe using the custom gene symbol extraction\n",
    "mapping_df = pd.DataFrame({\n",
    "    'ID': gene_annotation['ID'],\n",
    "    'Gene': gene_annotation['SPOT_ID.1'].apply(extract_better_gene_symbols)\n",
    "})\n",
    "\n",
    "# Print some statistics on the mapping\n",
    "total_probes = len(mapping_df)\n",
    "mapped_probes = len(mapping_df[mapping_df['Gene'].str.len() > 0])\n",
    "print(f\"Found gene symbols for {mapped_probes}/{total_probes} probes ({mapped_probes/total_probes:.1%})\")\n",
    "\n",
    "# Show some examples of successful mappings\n",
    "if mapped_probes > 0:\n",
    "    print(\"\\nSample of probe to gene mappings:\")\n",
    "    sample_mappings = mapping_df[mapping_df['Gene'].str.len() > 0].head(5)\n",
    "    for _, row in sample_mappings.iterrows():\n",
    "        print(f\"Probe: {row['ID']}, Genes: {row['Gene']}\")\n",
    "\n",
    "# If we still have zero mappings, try an alternative approach using the NetAffx annotation\n",
    "if mapped_probes == 0:\n",
    "    print(\"\\nAttempting alternative mapping using default extraction method...\")\n",
    "    # Try using the standard extract_human_gene_symbols function as fallback\n",
    "    mapping_df = pd.DataFrame({\n",
    "        'ID': gene_annotation['ID'],\n",
    "        'Gene': gene_annotation['SPOT_ID.1'].apply(extract_human_gene_symbols)\n",
    "    })\n",
    "    \n",
    "    # Filter out common non-gene terms that might be captured incorrectly\n",
    "    non_gene_terms = {'ENSEMBL', 'UCSC', 'MGC', 'IMAGE', 'CDS', 'INTERNAL', 'OVCODE', \n",
    "                       'OVERLAPTX', 'OVEXON', 'UTR3', 'NONCODE', 'ANNOTATED', 'ID', \n",
    "                       'CCDS', 'HGNC'}\n",
    "    \n",
    "    # Remove rows with only non-gene terms\n",
    "    for idx, row in mapping_df.iterrows():\n",
    "        mapping_df.at[idx, 'Gene'] = [g for g in row['Gene'] if g not in non_gene_terms]\n",
    "    \n",
    "    # Update statistics\n",
    "    mapped_probes = len(mapping_df[mapping_df['Gene'].str.len() > 0])\n",
    "    print(f\"Found gene symbols for {mapped_probes}/{total_probes} probes ({mapped_probes/total_probes:.1%})\")\n",
    "\n",
    "# Apply the gene mapping to convert probe-level data to gene-level data\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
    "\n",
    "# Normalize gene symbols to standardize case and handle synonyms\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "\n",
    "# Print information about the resulting gene expression matrix\n",
    "print(f\"\\nConverted gene expression data dimensions: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
    "if gene_data.shape[0] > 0:\n",
    "    print(\"\\nFirst 10 gene symbols:\")\n",
    "    print(gene_data.index[:10])\n",
    "else:\n",
    "    print(\"\\nWARNING: No genes were mapped. The gene expression matrix is empty.\")\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\"\\nGene expression data saved to {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4166b142",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "896a475f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:33:51.391074Z",
     "iopub.status.busy": "2025-03-25T08:33:51.390919Z",
     "iopub.status.idle": "2025-03-25T08:33:51.397883Z",
     "shell.execute_reply": "2025-03-25T08:33:51.397593Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Error: Gene expression matrix is empty after mapping.\n",
      "Abnormality detected in the cohort: GSE186963. Preprocessing failed.\n",
      "Dataset deemed not usable due to lack of gene expression data.\n"
     ]
    }
   ],
   "source": [
    "# 1. Check if gene data is available after mapping\n",
    "if gene_data.shape[0] == 0:\n",
    "    print(\"Error: Gene expression matrix is empty after mapping.\")\n",
    "    # Mark the dataset as not usable due to lack of gene expression data\n",
    "    is_usable = validate_and_save_cohort_info(\n",
    "        is_final=True,\n",
    "        cohort=cohort,\n",
    "        info_path=json_path,\n",
    "        is_gene_available=False,  # No usable gene data\n",
    "        is_trait_available=True,\n",
    "        is_biased=True,\n",
    "        df=pd.DataFrame(),\n",
    "        note=\"Failed to map probe IDs to gene symbols. The annotation format may not be compatible with the extraction methods.\"\n",
    "    )\n",
    "    print(\"Dataset deemed not usable due to lack of gene expression data.\")\n",
    "else:\n",
    "    # Only proceed with normalization if we have gene data\n",
    "    print(\"Normalizing gene symbols...\")\n",
    "    gene_data_normalized = normalize_gene_symbols_in_index(gene_data)\n",
    "    print(f\"Gene data shape after normalization: {gene_data_normalized.shape[0]} genes × {gene_data_normalized.shape[1]} samples\")\n",
    "\n",
    "    # Save the normalized gene data\n",
    "    os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "    gene_data_normalized.to_csv(out_gene_data_file)\n",
    "    print(f\"Normalized gene expression data saved to {out_gene_data_file}\")\n",
    "    \n",
    "    # Extract clinical features from the original data source\n",
    "    print(\"Extracting clinical features from the original source...\")\n",
    "    # Get background information and clinical data again\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",
    "    # Extract clinical features\n",
    "    selected_clinical_df = geo_select_clinical_features(\n",
    "        clinical_df=clinical_data,\n",
    "        trait=trait,\n",
    "        trait_row=trait_row,\n",
    "        convert_trait=convert_trait,\n",
    "        age_row=age_row,\n",
    "        convert_age=convert_age,\n",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender\n",
    "    )\n",
    "    \n",
    "    print(\"Extracted clinical features preview:\")\n",
    "    print(preview_df(selected_clinical_df))\n",
    "    print(f\"Clinical data shape: {selected_clinical_df.shape}\")\n",
    "    \n",
    "    # Save the extracted clinical features\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 features saved to {out_clinical_data_file}\")\n",
    "    \n",
    "    # Link clinical and genetic data\n",
    "    print(\"Linking clinical and genetic data...\")\n",
    "    linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data_normalized)\n",
    "    print(f\"Linked data shape: {linked_data.shape}\")\n",
    "    \n",
    "    # Check if the linked data has adequate data\n",
    "    if linked_data.shape[0] == 0 or linked_data.shape[1] <= 4:  # 4 is an arbitrary small number\n",
    "        print(\"Error: Linked data has insufficient samples or features.\")\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=True,\n",
    "            df=linked_data,\n",
    "            note=\"Failed to properly link gene expression data with clinical features.\"\n",
    "        )\n",
    "        print(\"Dataset deemed not usable due to linking failure.\")\n",
    "    else:\n",
    "        # Handle missing values systematically\n",
    "        print(\"Handling missing values...\")\n",
    "        linked_data_clean = handle_missing_values(linked_data, trait_col=trait)\n",
    "        print(f\"Data shape after handling missing values: {linked_data_clean.shape}\")\n",
    "        \n",
    "        # Check if there are still samples after missing value handling\n",
    "        if linked_data_clean.shape[0] == 0:\n",
    "            print(\"Error: No samples remain after handling missing values.\")\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=True,\n",
    "                df=pd.DataFrame(),\n",
    "                note=\"All samples were removed during missing value handling.\"\n",
    "            )\n",
    "            print(\"Dataset deemed not usable as all samples were filtered out.\")\n",
    "        else:\n",
    "            # Check if the dataset is biased\n",
    "            print(\"\\nChecking for bias in feature variables:\")\n",
    "            is_biased, linked_data_final = judge_and_remove_biased_features(linked_data_clean, trait)\n",
    "            \n",
    "            # Conduct final quality validation\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_final,\n",
    "                note=\"Dataset contains gene expression data for Crohn's Disease patients, examining response to Infliximab treatment.\"\n",
    "            )\n",
    "            \n",
    "            # Save linked data if usable\n",
    "            if is_usable:\n",
    "                os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "                linked_data_final.to_csv(out_data_file)\n",
    "                print(f\"Linked data saved to {out_data_file}\")\n",
    "                print(f\"Final dataset shape: {linked_data_final.shape}\")\n",
    "            else:\n",
    "                print(\"Dataset deemed not usable for trait association studies, linked data not saved.\")"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}