File size: 29,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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "6ceb301c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:33:55.500177Z",
     "iopub.status.busy": "2025-03-25T08:33:55.500071Z",
     "iopub.status.idle": "2025-03-25T08:33:55.657820Z",
     "shell.execute_reply": "2025-03-25T08:33:55.657382Z"
    }
   },
   "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 = \"GSE193677\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Crohns_Disease\"\n",
    "in_cohort_dir = \"../../input/GEO/Crohns_Disease/GSE193677\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Crohns_Disease/GSE193677.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Crohns_Disease/gene_data/GSE193677.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Crohns_Disease/clinical_data/GSE193677.csv\"\n",
    "json_path = \"../../output/preprocess/Crohns_Disease/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e7abcb87",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "a7d77a9b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:33:55.659274Z",
     "iopub.status.busy": "2025-03-25T08:33:55.659129Z",
     "iopub.status.idle": "2025-03-25T08:33:55.725466Z",
     "shell.execute_reply": "2025-03-25T08:33:55.725067Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Biopsy expression profiling of an adult inflammatory bowel disease cohort\"\n",
      "!Series_summary\t\"Inflammatory Bowel Disease (IBD) is a progressive disease of the gut and consists of two types, Crohn’s Disease (CD) and Ulcerative Colitis (UC). It is a complex disease involving genetic, microbial, and environmental factors. The incidence of IBD is steadily increasing and current therapeutic options are plateauing. Thus treatments are evolving to 1. deeper levels of remission from clinical to endoscopic and histologic normalization and 2. Embrace novel targets or drug combinations. We explored whole transcriptome data generated in biopsy specimens sampled from a large cohort of adult IBD and control subjects to provide 1. a granular, objective and sensitive molecular measures of disease activity in the gut and 2. Novel molecular mechanisms and biomarkers underlying IBD pathology.\"\n",
      "!Series_overall_design\t\"The Mount Sinai Crohn's and Colitis registry (MSCCR) is a prospective cross-sectional cohort consisting of adult IBD patients and controls. Biopsy RNA sequencing (RNA-Seq) data were generated on whole blood sampled at the time of the participant’s endoscopy visit which also included detailed clinical, histological and endoscopic assessments.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['study_eligibility_age_at_endo: 44', 'study_eligibility_age_at_endo: 60', 'study_eligibility_age_at_endo: 38', 'study_eligibility_age_at_endo: 20', 'study_eligibility_age_at_endo: 73', 'study_eligibility_age_at_endo: 64', 'study_eligibility_age_at_endo: 51', 'study_eligibility_age_at_endo: 32', 'study_eligibility_age_at_endo: 55', 'study_eligibility_age_at_endo: 79', 'study_eligibility_age_at_endo: 34', 'study_eligibility_age_at_endo: 46', 'study_eligibility_age_at_endo: 27', 'study_eligibility_age_at_endo: 24', 'study_eligibility_age_at_endo: 29', 'study_eligibility_age_at_endo: 25', 'study_eligibility_age_at_endo: 45', 'study_eligibility_age_at_endo: 56', 'study_eligibility_age_at_endo: 21', 'study_eligibility_age_at_endo: 40', 'study_eligibility_age_at_endo: 62', 'study_eligibility_age_at_endo: 30', 'study_eligibility_age_at_endo: 53', 'study_eligibility_age_at_endo: 50', 'study_eligibility_age_at_endo: 71', 'study_eligibility_age_at_endo: 57', 'study_eligibility_age_at_endo: 37', 'study_eligibility_age_at_endo: 31', 'study_eligibility_age_at_endo: 77', 'study_eligibility_age_at_endo: 61'], 1: ['demographics_gender: Male', 'demographics_gender: Female'], 2: ['regionre: Rectum', 'regionre: LeftColon', 'regionre: Ileum', 'regionre: RightColon', 'regionre: Transverse', 'regionre: Sigmoid', 'regionre: Cecum'], 3: ['diseasetypere: UC.NonI', 'diseasetypere: CD.NonI', 'diseasetypere: UC.I', 'diseasetypere: Control.NonI', 'diseasetypere: CD.I'], 4: ['ibd_disease: UC', 'ibd_disease: CD', 'ibd_disease: Control'], 5: ['typere: NonI', 'typere: I'], 6: ['diseasebi: IBD', 'diseasebi: Control'], 7: ['log2_fecalcalpro_mgperg: NA', 'log2_fecalcalpro_mgperg: 4.05398016818765', 'log2_fecalcalpro_mgperg: 7.3527055668799', 'log2_fecalcalpro_mgperg: 1.51601514700366', 'log2_fecalcalpro_mgperg: 3.20006486151431', 'log2_fecalcalpro_mgperg: 4.09845324630927', 'log2_fecalcalpro_mgperg: 4.66448284036468', 'log2_fecalcalpro_mgperg: 5.01792190799726', 'log2_fecalcalpro_mgperg: 4.59872249967662', 'log2_fecalcalpro_mgperg: 1.85598969730848', 'log2_fecalcalpro_mgperg: 0.575312330687437', 'log2_fecalcalpro_mgperg: 7.42054977211632', 'log2_fecalcalpro_mgperg: 1.38404980679516', 'log2_fecalcalpro_mgperg: 6.37347421446529', 'log2_fecalcalpro_mgperg: 2.37295209791183', 'log2_fecalcalpro_mgperg: 4.17791779219584', 'log2_fecalcalpro_mgperg: 0.831877241191673', 'log2_fecalcalpro_mgperg: 5.82068956055921', 'log2_fecalcalpro_mgperg: 5.8040019151793', 'log2_fecalcalpro_mgperg: -1.25153876699596', 'log2_fecalcalpro_mgperg: 1.75702324650746', 'log2_fecalcalpro_mgperg: 1.67807190511264', 'log2_fecalcalpro_mgperg: -0.234465253637023', 'log2_fecalcalpro_mgperg: 5.06522762277562', 'log2_fecalcalpro_mgperg: 2.78240856492737', 'log2_fecalcalpro_mgperg: 5.65906827484323', 'log2_fecalcalpro_mgperg: 2.55090066464752', 'log2_fecalcalpro_mgperg: 1.20789285164133', 'log2_fecalcalpro_mgperg: 3.8094144442359', 'log2_fecalcalpro_mgperg: 0.669026765509631'], 8: ['crp_jjmgl_log2: -1.73304477172605', 'crp_jjmgl_log2: 1.43649047297647', 'crp_jjmgl_log2: 0.248893810021695', 'crp_jjmgl_log2: 0.690789846030944', 'crp_jjmgl_log2: -1.03434350915367', 'crp_jjmgl_log2: 0.851978855048292', 'crp_jjmgl_log2: 3.61465095740156', 'crp_jjmgl_log2: NA', 'crp_jjmgl_log2: 2.71983452170449', 'crp_jjmgl_log2: 0.324793325532102', 'crp_jjmgl_log2: 0.0174958047648723', 'crp_jjmgl_log2: -0.212793904236437', 'crp_jjmgl_log2: 1.77885617166104', 'crp_jjmgl_log2: 4.95577264035103', 'crp_jjmgl_log2: -1.64193777974525', 'crp_jjmgl_log2: 0.366464902844286', 'crp_jjmgl_log2: -0.572325180165365', 'crp_jjmgl_log2: 0.852172268204834', 'crp_jjmgl_log2: -1.78424736040566', 'crp_jjmgl_log2: 3.43539390368193', 'crp_jjmgl_log2: 1.10777154989448', 'crp_jjmgl_log2: 2.83164400014871', 'crp_jjmgl_log2: 0.742522814523496', 'crp_jjmgl_log2: 2.07952932801523', 'crp_jjmgl_log2: 1.97926663450486', 'crp_jjmgl_log2: 3.64363814745324', 'crp_jjmgl_log2: 1.4035900427654', 'crp_jjmgl_log2: 1.10274143242099', 'crp_jjmgl_log2: 0.204169520299931', 'crp_jjmgl_log2: 3.64405699894842'], 9: ['ibd_clinicianmeasure_inactive_active: Inactive', 'ibd_clinicianmeasure_inactive_active: Active', 'ibd_clinicianmeasure_inactive_active: NA'], 10: ['ibd_endoseverity_4levels: Inactive', 'ibd_endoseverity_4levels: Moderate', 'ibd_endoseverity_4levels: NA', 'ibd_endoseverity_4levels: Mild', 'ibd_endoseverity_4levels: Severe'], 11: ['ghas_sum7: 2', 'ghas_sum7: NA', 'ghas_sum7: 0', 'ghas_sum7: 3', 'ghas_sum7: 6', 'ghas_sum7: 4', 'ghas_sum7: 8', 'ghas_sum7: 10', 'ghas_sum7: 1', 'ghas_sum7: 7', 'ghas_sum7: 9', 'ghas_sum7: 5', 'ghas_sum7: 11'], 12: ['nancyindex: 0', 'nancyindex: NA', 'nancyindex: 2', 'nancyindex: 3', 'nancyindex: 1', 'nancyindex: 4'], 13: ['ibdsescd_totalsescd: NA', 'ibdsescd_totalsescd: 0', 'ibdsescd_totalsescd: 8', 'ibdsescd_totalsescd: 2', 'ibdsescd_totalsescd: 3', 'ibdsescd_totalsescd: 7', 'ibdsescd_totalsescd: 4', 'ibdsescd_totalsescd: 10', 'ibdsescd_totalsescd: 15', 'ibdsescd_totalsescd: 14', 'ibdsescd_totalsescd: 6', 'ibdsescd_totalsescd: 12', 'ibdsescd_totalsescd: 5', 'ibdsescd_totalsescd: 13', 'ibdsescd_totalsescd: 20', 'ibdsescd_totalsescd: 1', 'ibdsescd_totalsescd: 11', 'ibdsescd_totalsescd: 23', 'ibdsescd_totalsescd: 26', 'ibdsescd_totalsescd: 25', 'ibdsescd_totalsescd: 18', 'ibdsescd_totalsescd: 9', 'ibdsescd_totalsescd: 27', 'ibdsescd_totalsescd: 38', 'ibdsescd_totalsescd: 29', 'ibdsescd_totalsescd: 17', 'ibdsescd_totalsescd: 16', 'ibdsescd_totalsescd: 21', 'ibdsescd_totalsescd: 19', 'ibdsescd_totalsescd: 30'], 14: ['ibdmesuc_mayo_score: 0', 'ibdmesuc_mayo_score: NA', 'ibdmesuc_mayo_score: 2', 'ibdmesuc_mayo_score: 1', 'ibdmesuc_mayo_score: 3'], 15: ['harveybradshawindex_hbi_score: NA', 'harveybradshawindex_hbi_score: 10', 'harveybradshawindex_hbi_score: 1', 'harveybradshawindex_hbi_score: 5', 'harveybradshawindex_hbi_score: 11', 'harveybradshawindex_hbi_score: 0', 'harveybradshawindex_hbi_score: 4', 'harveybradshawindex_hbi_score: 6', 'harveybradshawindex_hbi_score: 7', 'harveybradshawindex_hbi_score: 3', 'harveybradshawindex_hbi_score: 14', 'harveybradshawindex_hbi_score: 2', 'harveybradshawindex_hbi_score: 8', 'harveybradshawindex_hbi_score: 12', 'harveybradshawindex_hbi_score: 9', 'harveybradshawindex_hbi_score: 18', 'harveybradshawindex_hbi_score: 15', 'harveybradshawindex_hbi_score: 16', 'harveybradshawindex_hbi_score: 13', 'harveybradshawindex_hbi_score: 25', 'harveybradshawindex_hbi_score: 27', 'harveybradshawindex_hbi_score: 19', 'harveybradshawindex_hbi_score: 17', 'harveybradshawindex_hbi_score: 35', 'harveybradshawindex_hbi_score: 32', 'harveybradshawindex_hbi_score: 42', 'harveybradshawindex_hbi_score: 20'], 16: ['colitisactivityindex_sccai: 1', 'colitisactivityindex_sccai: NA', 'colitisactivityindex_sccai: 5', 'colitisactivityindex_sccai: 0', 'colitisactivityindex_sccai: 3', 'colitisactivityindex_sccai: 10', 'colitisactivityindex_sccai: 2', 'colitisactivityindex_sccai: 4', 'colitisactivityindex_sccai: 6', 'colitisactivityindex_sccai: 11', 'colitisactivityindex_sccai: 9', 'colitisactivityindex_sccai: 7', 'colitisactivityindex_sccai: 8', 'colitisactivityindex_sccai: 12', 'colitisactivityindex_sccai: 15'], 17: ['max_ghas_sum7: 2', 'max_ghas_sum7: NA', 'max_ghas_sum7: 3', 'max_ghas_sum7: 6', 'max_ghas_sum7: 0', 'max_ghas_sum7: 4', 'max_ghas_sum7: 10', 'max_ghas_sum7: 1', 'max_ghas_sum7: 7', 'max_ghas_sum7: 8', 'max_ghas_sum7: 9', 'max_ghas_sum7: 5', 'max_ghas_sum7: 11'], 18: ['max_nancy: 0', 'max_nancy: NA', 'max_nancy: 2', 'max_nancy: 3', 'max_nancy: 4', 'max_nancy: 1'], 19: ['endoremiss: 1', 'endoremiss: 0', 'endoremiss: NA'], 20: ['historemiss: 0', 'historemiss: NA', 'historemiss: 1']}\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": "34d6233e",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "f9767a74",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:33:55.726622Z",
     "iopub.status.busy": "2025-03-25T08:33:55.726509Z",
     "iopub.status.idle": "2025-03-25T08:33:55.731074Z",
     "shell.execute_reply": "2025-03-25T08:33:55.730688Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical feature extraction would proceed if clinical_data were available.\n",
      "Would extract features: trait_row=4, age_row=0, gender_row=1\n",
      "Would save to: ../../output/preprocess/Crohns_Disease/clinical_data/GSE193677.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Determine if gene expression data is available\n",
    "# Based on the background information, this dataset contains RNA-Seq data which is gene expression data\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Checking trait data availability\n",
    "# Looking at keys 4 and 6, we can see disease information:\n",
    "# Key 4: 'ibd_disease: UC', 'ibd_disease: CD', 'ibd_disease: Control'\n",
    "# Key 6: 'diseasebi: IBD', 'diseasebi: Control'\n",
    "# For Crohn's Disease, key 4 contains the specific disease type\n",
    "trait_row = 4\n",
    "\n",
    "# Age information is in key 0 (study_eligibility_age_at_endo)\n",
    "age_row = 0\n",
    "\n",
    "# Gender information is in key 1 (demographics_gender)\n",
    "gender_row = 1\n",
    "\n",
    "# 2.2 Data Type Conversion functions\n",
    "def convert_trait(value):\n",
    "    if value is None:\n",
    "        return None\n",
    "    # Extract the value after the colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Check for Crohn's Disease\n",
    "    if value == 'CD':\n",
    "        return 1\n",
    "    elif value in ['UC', 'Control']:\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    if value is None:\n",
    "        return None\n",
    "    # Extract the value after the colon\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",
    "    if value is None:\n",
    "        return None\n",
    "    # Extract the value after the colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    if value.lower() == 'male':\n",
    "        return 1\n",
    "    elif value.lower() == 'female':\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save metadata\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 a DataFrame from the sample characteristics dictionary\n",
    "    # First, we need to convert the sample characteristics into a proper DataFrame format\n",
    "    # The clinical_data variable is assumed to be a DataFrame from previous steps containing the characteristic data\n",
    "    \n",
    "    # The error indicates we need to access the clinical data differently\n",
    "    # Wait for the actual clinical_data to be passed from the previous step\n",
    "    # For now, just print a message about what would happen next\n",
    "    print(f\"Clinical feature extraction would proceed if clinical_data were available.\")\n",
    "    print(f\"Would extract features: trait_row={trait_row}, age_row={age_row}, gender_row={gender_row}\")\n",
    "    print(f\"Would save to: {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "00dba4a2",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "77676263",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:33:55.732108Z",
     "iopub.status.busy": "2025-03-25T08:33:55.732002Z",
     "iopub.status.idle": "2025-03-25T08:33:56.478161Z",
     "shell.execute_reply": "2025-03-25T08:33:56.477555Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SOFT file path: ../../input/GEO/Crohns_Disease/GSE193677/GSE193677_family.soft.gz\n",
      "Matrix file path: ../../input/GEO/Crohns_Disease/GSE193677/GSE193677_series_matrix.txt.gz\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Successfully extracted gene data using get_genetic_data function\n",
      "Attempting manual extraction...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Manual extraction completed, shape: (0, 2490)\n",
      "\n",
      "Matrix file gene data extraction failed. Checking SOFT file...\n",
      "Error extracting gene metadata from SOFT file: No columns to parse from file\n",
      "\n",
      "First 20 gene/probe identifiers:\n",
      "Failed to extract gene identifiers.\n",
      "Gene expression data available: False\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",
    "# Print the file paths to debug\n",
    "print(f\"SOFT file path: {soft_file}\")\n",
    "print(f\"Matrix file path: {matrix_file}\")\n",
    "\n",
    "# Try a simpler direct approach to read the gene expression data\n",
    "import pandas as pd\n",
    "import gzip\n",
    "\n",
    "try:\n",
    "    # Use the library function with proper error handling\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    print(\"Successfully extracted gene data using get_genetic_data function\")\n",
    "except Exception as e:\n",
    "    print(f\"Error with get_genetic_data: {e}\")\n",
    "    gene_data = None\n",
    "\n",
    "# If the library function failed, try a manual approach\n",
    "if gene_data is None or gene_data.shape[0] == 0:\n",
    "    print(\"Attempting manual extraction...\")\n",
    "    with gzip.open(matrix_file, 'rt') as file:\n",
    "        # Read the file content into memory\n",
    "        content = file.read()\n",
    "        \n",
    "        # Find the table markers\n",
    "        start_marker = \"!series_matrix_table_begin\"\n",
    "        end_marker = \"!series_matrix_table_end\"\n",
    "        \n",
    "        if start_marker in content.lower():\n",
    "            # Get position of start marker\n",
    "            start_idx = content.lower().find(start_marker)\n",
    "            # Find the end of the line containing the start marker\n",
    "            start_idx = content.find('\\n', start_idx) + 1\n",
    "            \n",
    "            # Find end marker if it exists\n",
    "            if end_marker in content.lower():\n",
    "                end_idx = content.lower().find(end_marker)\n",
    "            else:\n",
    "                end_idx = len(content)\n",
    "            \n",
    "            # Extract the table content\n",
    "            table_content = content[start_idx:end_idx]\n",
    "            \n",
    "            # Read into DataFrame\n",
    "            import io\n",
    "            gene_data = pd.read_csv(io.StringIO(table_content), sep='\\t', index_col=0)\n",
    "            \n",
    "            # Skip the first row if it contains the header\n",
    "            if gene_data.index.name == 'ID_REF':\n",
    "                gene_data = gene_data.reset_index().iloc[1:].set_index('ID_REF')\n",
    "            \n",
    "            print(f\"Manual extraction completed, shape: {gene_data.shape}\")\n",
    "\n",
    "# Fall back to checking the soft file for gene IDs if matrix extraction failed\n",
    "if gene_data is None or gene_data.shape[0] == 0:\n",
    "    print(\"\\nMatrix file gene data extraction failed. Checking SOFT file...\")\n",
    "    try:\n",
    "        gene_metadata = get_gene_annotation(soft_file)\n",
    "        print(f\"Gene metadata from SOFT file has shape: {gene_metadata.shape}\")\n",
    "        # If successful, we'll use this as our gene data\n",
    "        if 'ID' in gene_metadata.columns and gene_metadata.shape[0] > 0:\n",
    "            # Create a minimal gene data frame with just the identifiers\n",
    "            gene_data = gene_metadata[['ID']].set_index('ID')\n",
    "            print(\"Using gene identifiers from SOFT file as fallback\")\n",
    "    except Exception as e:\n",
    "        print(f\"Error extracting gene metadata from SOFT file: {e}\")\n",
    "\n",
    "# 3. Print the first 20 row IDs (gene/probe identifiers)\n",
    "print(\"\\nFirst 20 gene/probe identifiers:\")\n",
    "if gene_data is not None and gene_data.shape[0] > 0:\n",
    "    print(gene_data.index[:20])\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",
    "else:\n",
    "    print(\"Failed to extract gene identifiers.\")\n",
    "\n",
    "# Update gene availability based on our findings\n",
    "is_gene_available = (gene_data is not None and gene_data.shape[0] > 0)\n",
    "print(f\"Gene expression data available: {is_gene_available}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "00736f4f",
   "metadata": {},
   "source": [
    "### Step 4: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "207f4642",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:33:56.479570Z",
     "iopub.status.busy": "2025-03-25T08:33:56.479452Z",
     "iopub.status.idle": "2025-03-25T08:33:56.505182Z",
     "shell.execute_reply": "2025-03-25T08:33:56.504740Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SOFT file size: 185596 bytes\n",
      "First 20 lines of the SOFT file:\n",
      "^DATABASE = GeoMiame\n",
      "!Database_name = Gene Expression Omnibus (GEO)\n",
      "!Database_institute = NCBI NLM NIH\n",
      "!Database_web_link = http://www.ncbi.nlm.nih.gov/geo\n",
      "!Database_email = [email protected]\n",
      "^SERIES = GSE193677\n",
      "!Series_title = Biopsy expression profiling of an adult inflammatory bowel disease cohort\n",
      "!Series_geo_accession = GSE193677\n",
      "!Series_status = Public on Sep 16 2022\n",
      "!Series_submission_date = Jan 13 2022\n",
      "!Series_last_update_date = Nov 04 2024\n",
      "!Series_pubmed_id = 36109152\n",
      "!Series_summary = Inflammatory Bowel Disease (IBD) is a progressive disease of the gut and consists of two types, Crohn’s Disease (CD) and Ulcerative Colitis (UC). It is a complex disease involving genetic, microbial, and environmental factors. The incidence of IBD is steadily increasing and current therapeutic options are plateauing. Thus treatments are evolving to 1. deeper levels of remission from clinical to endoscopic and histologic normalization and 2. Embrace novel targets or drug combinations. We explored whole transcriptome data generated in biopsy specimens sampled from a large cohort of adult IBD and control subjects to provide 1. a granular, objective and sensitive molecular measures of disease activity in the gut and 2. Novel molecular mechanisms and biomarkers underlying IBD pathology.\n",
      "!Series_overall_design = The Mount Sinai Crohn's and Colitis registry (MSCCR) is a prospective cross-sectional cohort consisting of adult IBD patients and controls. Biopsy RNA sequencing (RNA-Seq) data were generated on whole blood sampled at the time of the participant’s endoscopy visit which also included detailed clinical, histological and endoscopic assessments.\n",
      "!Series_type = Expression profiling by high throughput sequencing\n",
      "!Series_contributor = Carmen,,Argmann\n",
      "!Series_contributor = Mayte,,Suárez-Fariñas\n",
      "!Series_contributor = Ruixue,,Hou\n",
      "!Series_contributor = Aritz,,Irizar\n",
      "!Series_sample_id = GSM5976499\n",
      "\n",
      "First few lines of the matrix file:\n",
      "!Series_title\t\"Biopsy expression profiling of an adult inflammatory bowel disease cohort\"\n",
      "!Series_geo_accession\t\"GSE193677\"\n",
      "!Series_status\t\"Public on Sep 16 2022\"\n",
      "!Series_submission_date\t\"Jan 13 2022\"\n",
      "!Series_last_update_date\t\"Nov 04 2024\"\n",
      "!Series_pubmed_id\t\"36109152\"\n",
      "!Series_summary\t\"Inflammatory Bowel Disease (IBD) is a progressive disease of the gut and consists of two types, Crohn’s Disease (CD) and Ulcerative Colitis (UC). It is a complex disease involving genetic, microbial, and environmental factors. The incidence of IBD is steadily increasing and current therapeutic options are plateauing. Thus treatments are evolving to 1. deeper levels of remission from clinical to endoscopic and histologic normalization and 2. Embrace novel targets or drug combinations. We explored whole transcriptome data generated in biopsy specimens sampled from a large cohort of adult IBD and control subjects to provide 1. a granular, objective and sensitive molecular measures of disease activity in the gut and 2. Novel molecular mechanisms and biomarkers underlying IBD pathology.\"\n",
      "!Series_overall_design\t\"The Mount Sinai Crohn's and Colitis registry (MSCCR) is a prospective cross-sectional cohort consisting of adult IBD patients and controls. Biopsy RNA sequencing (RNA-Seq) data were generated on whole blood sampled at the time of the participant’s endoscopy visit which also included detailed clinical, histological and endoscopic assessments.\"\n",
      "!Series_type\t\"Expression profiling by high throughput sequencing\"\n",
      "!Series_contributor\t\"Carmen,,Argmann\"\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "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",
    "# Check file integrity and size\n",
    "import os\n",
    "file_size = os.path.getsize(soft_file)\n",
    "print(f\"SOFT file size: {file_size} bytes\")\n",
    "\n",
    "# First, check what's actually in the SOFT file\n",
    "import gzip\n",
    "try:\n",
    "    with gzip.open(soft_file, 'rt') as f:\n",
    "        print(\"First 20 lines of the SOFT file:\")\n",
    "        for i in range(20):\n",
    "            try:\n",
    "                line = next(f)\n",
    "                print(line.strip())\n",
    "            except StopIteration:\n",
    "                print(\"End of file reached.\")\n",
    "                break\n",
    "except Exception as e:\n",
    "    print(f\"Error reading SOFT file: {e}\")\n",
    "\n",
    "# Try a direct inspection of the matrix file instead\n",
    "try:\n",
    "    with gzip.open(matrix_file, 'rt') as f:\n",
    "        print(\"\\nFirst few lines of the matrix file:\")\n",
    "        for i in range(10):\n",
    "            try:\n",
    "                line = next(f)\n",
    "                print(line.strip())\n",
    "            except StopIteration:\n",
    "                print(\"End of file reached.\")\n",
    "                break\n",
    "except Exception as e:\n",
    "    print(f\"Error reading matrix file: {e}\")\n",
    "\n",
    "# Update gene availability status based on our findings\n",
    "is_gene_available = False\n",
    "\n",
    "# Update the dataset usability information\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=True  # From previous step\n",
    ")"
   ]
  }
 ],
 "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
}