File size: 25,594 Bytes
f88156f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "724d13d2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:00:37.902921Z",
     "iopub.status.busy": "2025-03-25T08:00:37.902808Z",
     "iopub.status.idle": "2025-03-25T08:00:38.063723Z",
     "shell.execute_reply": "2025-03-25T08:00:38.063365Z"
    }
   },
   "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 = \"Celiac_Disease\"\n",
    "cohort = \"GSE106260\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Celiac_Disease\"\n",
    "in_cohort_dir = \"../../input/GEO/Celiac_Disease/GSE106260\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Celiac_Disease/GSE106260.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Celiac_Disease/gene_data/GSE106260.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Celiac_Disease/clinical_data/GSE106260.csv\"\n",
    "json_path = \"../../output/preprocess/Celiac_Disease/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ce7b4dce",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "6e818a77",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:00:38.065224Z",
     "iopub.status.busy": "2025-03-25T08:00:38.065086Z",
     "iopub.status.idle": "2025-03-25T08:00:38.207264Z",
     "shell.execute_reply": "2025-03-25T08:00:38.206925Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Immunopathology of childhood celiac disease-Key role of intestinal epithelial cells\"\n",
      "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n",
      "!Series_overall_design\t\"Refer to individual Series\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['cell line: colon carcinoma cell line T84'], 1: ['treatment: CTR', 'treatment: A. graevenitzii', 'treatment: bacteria mix', 'treatment: bacteria mix with gluten', 'treatment: L. umeaense', 'treatment: P. jejuni (isolates CD3:28)', 'treatment: P. jejuni (isolates CD3:27)', 'treatment: Gluten', 'treatment: bacteria mix + Gluten']}\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": "da063225",
   "metadata": {},
   "source": [
    "### Step 2: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "53f626ba",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:00:38.208470Z",
     "iopub.status.busy": "2025-03-25T08:00:38.208355Z",
     "iopub.status.idle": "2025-03-25T08:00:38.396627Z",
     "shell.execute_reply": "2025-03-25T08:00:38.396256Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Matrix file found: ../../input/GEO/Celiac_Disease/GSE106260/GSE106260-GPL10558_series_matrix.txt.gz\n",
      "Gene data shape: (47230, 36)\n",
      "First 20 gene/probe identifiers:\n",
      "Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209',\n",
      "       'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229',\n",
      "       'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236',\n",
      "       'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253',\n",
      "       'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262'],\n",
      "      dtype='object', name='ID')\n"
     ]
    }
   ],
   "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": "5e2bb07f",
   "metadata": {},
   "source": [
    "### Step 3: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "94c2d565",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:00:38.397951Z",
     "iopub.status.busy": "2025-03-25T08:00:38.397834Z",
     "iopub.status.idle": "2025-03-25T08:00:38.399922Z",
     "shell.execute_reply": "2025-03-25T08:00:38.399609Z"
    }
   },
   "outputs": [],
   "source": [
    "# Identifying the gene identifiers\n",
    "# These are ILMN identifiers from Illumina microarray platforms\n",
    "# They are not standard human gene symbols and need to be mapped\n",
    "# ILMN_XXXXXXX is the Illumina BeadChip array ID format that needs mapping to gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "33123198",
   "metadata": {},
   "source": [
    "### Step 4: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "129aca12",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:00:38.401132Z",
     "iopub.status.busy": "2025-03-25T08:00:38.401024Z",
     "iopub.status.idle": "2025-03-25T08:00:43.655212Z",
     "shell.execute_reply": "2025-03-25T08:00:43.654821Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['ILMN_1722532', 'ILMN_1708805', 'ILMN_1672526', 'ILMN_1703284', 'ILMN_2185604'], 'Species': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Source': ['RefSeq', 'RefSeq', 'RefSeq', 'RefSeq', 'RefSeq'], 'Search_Key': ['ILMN_25544', 'ILMN_10519', 'ILMN_17234', 'ILMN_502', 'ILMN_19244'], 'Transcript': ['ILMN_25544', 'ILMN_10519', 'ILMN_17234', 'ILMN_502', 'ILMN_19244'], 'ILMN_Gene': ['JMJD1A', 'NCOA3', 'LOC389834', 'SPIRE2', 'C17ORF77'], 'Source_Reference_ID': ['NM_018433.3', 'NM_006534.2', 'NM_001013655.1', 'NM_032451.1', 'NM_152460.2'], 'RefSeq_ID': ['NM_018433.3', 'NM_006534.2', 'NM_001013655.1', 'NM_032451.1', 'NM_152460.2'], 'Entrez_Gene_ID': [55818.0, 8202.0, 389834.0, 84501.0, 146723.0], 'GI': [46358420.0, 32307123.0, 61966764.0, 55749599.0, 48255961.0], 'Accession': ['NM_018433.3', 'NM_006534.2', 'NM_001013655.1', 'NM_032451.1', 'NM_152460.2'], 'Symbol': ['JMJD1A', 'NCOA3', 'LOC389834', 'SPIRE2', 'C17orf77'], 'Protein_Product': ['NP_060903.2', 'NP_006525.2', 'NP_001013677.1', 'NP_115827.1', 'NP_689673.2'], 'Array_Address_Id': ['1240504', '2760390', '1740239', '6040014', '6550343'], 'Probe_Type': ['S', 'A', 'S', 'S', 'S'], 'Probe_Start': [4359.0, 7834.0, 3938.0, 3080.0, 2372.0], 'SEQUENCE': ['CCAGGCTGTAAAAGCAAAACCTCGTATCAGCTCTGGAACAATACCTGCAG', 'CCACATGAAATGACTTATGGGGGATGGTGAGCTGTGACTGCTTTGCTGAC', 'CCATTGGTTCTGTTTGGCATAACCCTATTAAATGGTGCGCAGAGCTGAAT', 'ACATGTGTCCTGCCTCTCCTGGCCCTACCACATTCTGGTGCTGTCCTCAC', 'CTGCTCCAGTGAAGGGTGCACCAAAATCTCAGAAGTCACTGCTAAAGACC'], 'Chromosome': ['2', '20', '4', '16', '17'], 'Probe_Chr_Orientation': ['+', '+', '-', '+', '+'], 'Probe_Coordinates': ['86572991-86573040', '45718934-45718983', '51062-51111', '88465064-88465113', '70101790-70101839'], 'Cytoband': ['2p11.2e', '20q13.12c', nan, '16q24.3b', '17q25.1b'], 'Definition': ['Homo sapiens jumonji domain containing 1A (JMJD1A), mRNA.', 'Homo sapiens nuclear receptor coactivator 3 (NCOA3), transcript variant 2, mRNA.', 'Homo sapiens hypothetical gene supported by AK123403 (LOC389834), mRNA.', 'Homo sapiens spire homolog 2 (Drosophila) (SPIRE2), mRNA.', 'Homo sapiens chromosome 17 open reading frame 77 (C17orf77), mRNA.'], 'Ontology_Component': ['nucleus [goid 5634] [evidence IEA]', 'nucleus [goid 5634] [pmid 9267036] [evidence NAS]', nan, nan, nan], 'Ontology_Process': ['chromatin modification [goid 16568] [evidence IEA]; transcription [goid 6350] [evidence IEA]; regulation of transcription, DNA-dependent [goid 6355] [evidence IEA]', 'positive regulation of transcription, DNA-dependent [goid 45893] [pmid 15572661] [evidence NAS]; androgen receptor signaling pathway [goid 30521] [pmid 15572661] [evidence NAS]; signal transduction [goid 7165] [evidence IEA]', nan, nan, nan], 'Ontology_Function': ['oxidoreductase activity [goid 16491] [evidence IEA]; oxidoreductase activity, acting on single donors with incorporation of molecular oxygen, incorporation of two atoms of oxygen [goid 16702] [evidence IEA]; zinc ion binding [goid 8270] [evidence IEA]; metal ion binding [goid 46872] [evidence IEA]; iron ion binding [goid 5506] [evidence IEA]', 'acyltransferase activity [goid 8415] [evidence IEA]; thyroid hormone receptor binding [goid 46966] [pmid 9346901] [evidence NAS]; transferase activity [goid 16740] [evidence IEA]; transcription coactivator activity [goid 3713] [pmid 15572661] [evidence NAS]; androgen receptor binding [goid 50681] [pmid 15572661] [evidence NAS]; histone acetyltransferase activity [goid 4402] [pmid 9267036] [evidence TAS]; signal transducer activity [goid 4871] [evidence IEA]; transcription regulator activity [goid 30528] [evidence IEA]; protein binding [goid 5515] [pmid 15698540] [evidence IPI]', nan, 'zinc ion binding [goid 8270] [evidence IEA]', nan], 'Synonyms': ['JHMD2A; JMJD1; TSGA; KIAA0742; DKFZp686A24246; DKFZp686P07111', 'CAGH16; TNRC14; pCIP; ACTR; MGC141848; CTG26; AIB-1; TRAM-1; TNRC16; AIB1; SRC3; SRC-1; RAC3', nan, 'MGC117166; Spir-2', 'FLJ31882'], 'GB_ACC': ['NM_018433.3', 'NM_006534.2', 'NM_001013655.1', 'NM_032451.1', 'NM_152460.2']}\n"
     ]
    }
   ],
   "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. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
    "print(\"Gene annotation preview:\")\n",
    "print(preview_df(gene_annotation))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "285c4621",
   "metadata": {},
   "source": [
    "### Step 5: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "75b6e24e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:00:43.656608Z",
     "iopub.status.busy": "2025-03-25T08:00:43.656483Z",
     "iopub.status.idle": "2025-03-25T08:00:43.907537Z",
     "shell.execute_reply": "2025-03-25T08:00:43.907142Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping dataframe shape: (24526, 2)\n",
      "First 5 rows of gene mapping:\n",
      "             ID       Gene\n",
      "0  ILMN_1722532     JMJD1A\n",
      "1  ILMN_1708805      NCOA3\n",
      "2  ILMN_1672526  LOC389834\n",
      "3  ILMN_1703284     SPIRE2\n",
      "4  ILMN_2185604   C17orf77\n",
      "Mapped gene expression data shape: (17824, 36)\n",
      "First 10 gene symbols in the mapped data:\n",
      "Index(['A1BG', 'A2BP1', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1',\n",
      "       'AAAS', 'AACS'],\n",
      "      dtype='object', name='Gene')\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "After normalization, gene expression data shape: (16856, 36)\n",
      "First 10 normalized gene symbols:\n",
      "Index(['A1BG', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS',\n",
      "       'AACS', 'AADAC'],\n",
      "      dtype='object', name='Gene')\n"
     ]
    }
   ],
   "source": [
    "# 1. Determine the mapping between gene identifiers and gene symbols\n",
    "# From the annotation preview, we can see that:\n",
    "# - The 'ID' column contains the ILMN probe identifiers (which match gene_data.index)\n",
    "# - The 'Symbol' column contains the gene symbols we want to map to\n",
    "\n",
    "# 2. Get the gene mapping dataframe\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n",
    "print(f\"Gene mapping dataframe shape: {gene_mapping.shape}\")\n",
    "print(\"First 5 rows of gene mapping:\")\n",
    "print(gene_mapping.head())\n",
    "\n",
    "# 3. Apply the gene mapping to convert probe-level data to gene-level expression data\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "print(f\"Mapped gene expression data shape: {gene_data.shape}\")\n",
    "print(\"First 10 gene symbols in the mapped data:\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# Normalize the gene symbols to handle synonyms and variants\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"After normalization, gene expression data shape: {gene_data.shape}\")\n",
    "print(\"First 10 normalized gene symbols:\")\n",
    "print(gene_data.index[:10])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d2e3965a",
   "metadata": {},
   "source": [
    "### Step 6: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "438c76cd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:00:43.908887Z",
     "iopub.status.busy": "2025-03-25T08:00:43.908773Z",
     "iopub.status.idle": "2025-03-25T08:00:44.284236Z",
     "shell.execute_reply": "2025-03-25T08:00:44.283797Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Celiac_Disease/gene_data/GSE106260.csv\n",
      "Clinical data from matrix file:\n",
      "         !Sample_geo_accession                                GSM2753759  \\\n",
      "0  !Sample_characteristics_ch1  cell line: colon carcinoma cell line T84   \n",
      "1  !Sample_characteristics_ch1                            treatment: CTR   \n",
      "\n",
      "                                 GSM2753760  \\\n",
      "0  cell line: colon carcinoma cell line T84   \n",
      "1                            treatment: CTR   \n",
      "\n",
      "                                 GSM2753761  \\\n",
      "0  cell line: colon carcinoma cell line T84   \n",
      "1                            treatment: CTR   \n",
      "\n",
      "                                 GSM2753762  \\\n",
      "0  cell line: colon carcinoma cell line T84   \n",
      "1                treatment: A. graevenitzii   \n",
      "\n",
      "                                 GSM2753763  \\\n",
      "0  cell line: colon carcinoma cell line T84   \n",
      "1                treatment: A. graevenitzii   \n",
      "\n",
      "                                 GSM2753764  \\\n",
      "0  cell line: colon carcinoma cell line T84   \n",
      "1                treatment: A. graevenitzii   \n",
      "\n",
      "                                 GSM2753765  \\\n",
      "0  cell line: colon carcinoma cell line T84   \n",
      "1                   treatment: bacteria mix   \n",
      "\n",
      "                                 GSM2753766  \\\n",
      "0  cell line: colon carcinoma cell line T84   \n",
      "1                   treatment: bacteria mix   \n",
      "\n",
      "                                 GSM2753767  ...  \\\n",
      "0  cell line: colon carcinoma cell line T84  ...   \n",
      "1                   treatment: bacteria mix  ...   \n",
      "\n",
      "                                 GSM2769613  \\\n",
      "0  cell line: colon carcinoma cell line T84   \n",
      "1                            treatment: CTR   \n",
      "\n",
      "                                 GSM2769614  \\\n",
      "0  cell line: colon carcinoma cell line T84   \n",
      "1                         treatment: Gluten   \n",
      "\n",
      "                                 GSM2769615  \\\n",
      "0  cell line: colon carcinoma cell line T84   \n",
      "1                         treatment: Gluten   \n",
      "\n",
      "                                 GSM2769616  \\\n",
      "0  cell line: colon carcinoma cell line T84   \n",
      "1                         treatment: Gluten   \n",
      "\n",
      "                                 GSM2769617  \\\n",
      "0  cell line: colon carcinoma cell line T84   \n",
      "1                   treatment: bacteria mix   \n",
      "\n",
      "                                 GSM2769618  \\\n",
      "0  cell line: colon carcinoma cell line T84   \n",
      "1                   treatment: bacteria mix   \n",
      "\n",
      "                                 GSM2769619  \\\n",
      "0  cell line: colon carcinoma cell line T84   \n",
      "1                   treatment: bacteria mix   \n",
      "\n",
      "                                 GSM2769620  \\\n",
      "0  cell line: colon carcinoma cell line T84   \n",
      "1          treatment: bacteria mix + Gluten   \n",
      "\n",
      "                                 GSM2769621  \\\n",
      "0  cell line: colon carcinoma cell line T84   \n",
      "1          treatment: bacteria mix + Gluten   \n",
      "\n",
      "                                 GSM2769622  \n",
      "0  cell line: colon carcinoma cell line T84  \n",
      "1          treatment: bacteria mix + Gluten  \n",
      "\n",
      "[2 rows x 37 columns]\n",
      "No cell type information found in clinical data.\n",
      "Clinical data saved to ../../output/preprocess/Celiac_Disease/clinical_data/GSE106260.csv\n",
      "Linked data shape: (36, 16857)\n",
      "Linked data preview (first 5 rows, 5 columns):\n",
      "            Celiac_Disease       A1BG        A2M      A2ML1   A3GALT2\n",
      "GSM2753759             NaN   1.845881  -8.964532  -7.624859  1.415234\n",
      "GSM2753760             NaN  22.427440  -3.645515  -3.813428 -4.201897\n",
      "GSM2753761             NaN  -0.964384  -5.007949 -10.667450 -1.092120\n",
      "GSM2753762             NaN  15.511400 -10.751940  -6.643857  2.111914\n",
      "GSM2753763             NaN   8.864400  -5.167774 -10.755740  2.743086\n",
      "Data shape after handling missing values: (0, 1)\n",
      "Quartiles for 'Celiac_Disease':\n",
      "  25%: nan\n",
      "  50% (Median): nan\n",
      "  75%: nan\n",
      "Min: nan\n",
      "Max: nan\n",
      "The distribution of the feature 'Celiac_Disease' in this dataset is fine.\n",
      "\n",
      "Abnormality detected in the cohort: GSE106260. Preprocessing failed.\n",
      "A new JSON file was created at: ../../output/preprocess/Celiac_Disease/cohort_info.json\n",
      "Dataset is not usable for analysis. No linked data file saved.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/media/techt/DATA/GenoAgent/tools/preprocess.py:400: FutureWarning: The behavior of DataFrame concatenation with empty or all-NA entries is deprecated. In a future version, this will no longer exclude empty or all-NA columns when determining the result dtypes. To retain the old behavior, exclude the relevant entries before the concat operation.\n",
      "  linked_data = pd.concat([clinical_df, genetic_df], axis=0).T\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene data is already normalized from previous step - no need to normalize again\n",
    "# Save the normalized gene data\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\"Normalized gene data saved to {out_gene_data_file}\")\n",
    "\n",
    "# 2. Process clinical data from the clinical dataframe we obtained in Step 1\n",
    "# From the characteristics dictionary, we know we need to analyze the clinical features in detail\n",
    "print(\"Clinical data from matrix file:\")\n",
    "print(clinical_data.head())\n",
    "\n",
    "# The clinical data is sparse for this dataset as seen in Step 1\n",
    "# Extract information from the sample characteristics for celiac disease analysis\n",
    "# In this case, the cell type information is a proxy for trait - intestinal epithelial cells vs intraepithelial lymphocytes\n",
    "def convert_cell_type(cell_type_str):\n",
    "    if isinstance(cell_type_str, str):\n",
    "        if 'epithelial' in cell_type_str.lower():\n",
    "            return 0  # Control/normal\n",
    "        elif 'lymphocytes' in cell_type_str.lower():\n",
    "            return 1  # Disease/case\n",
    "    return None  # For any other values or missing data\n",
    "\n",
    "# Process the clinical data to extract trait information\n",
    "# Find the row index that contains cell type information\n",
    "cell_type_row = None\n",
    "for idx, row_data in clinical_data.iterrows():\n",
    "    row_values = list(row_data.values)\n",
    "    for val in row_values:\n",
    "        if isinstance(val, str) and 'cell type' in val.lower():\n",
    "            cell_type_row = idx\n",
    "            break\n",
    "    if cell_type_row is not None:\n",
    "        break\n",
    "\n",
    "# If we found the row with cell type info, extract the trait data\n",
    "if cell_type_row is not None:\n",
    "    selected_clinical_data = geo_select_clinical_features(\n",
    "        clinical_data,\n",
    "        trait=trait,\n",
    "        trait_row=cell_type_row,\n",
    "        convert_trait=convert_cell_type\n",
    "    )\n",
    "    print(\"Selected clinical features:\")\n",
    "    print(selected_clinical_data)\n",
    "else:\n",
    "    # If no cell type info is found, we'll need to handle this case\n",
    "    print(\"No cell type information found in clinical data.\")\n",
    "    # Create a dummy clinical dataframe with just the IDs from gene data\n",
    "    selected_clinical_data = pd.DataFrame(\n",
    "        index=[trait], \n",
    "        columns=gene_data.columns,\n",
    "        data=[[None] * len(gene_data.columns)]\n",
    "    )\n",
    "\n",
    "# Save the processed clinical data\n",
    "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "selected_clinical_data.to_csv(out_clinical_data_file)\n",
    "print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "\n",
    "# 3. Link clinical and genetic data\n",
    "linked_data = geo_link_clinical_genetic_data(selected_clinical_data, 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])\n",
    "\n",
    "# 4. Handle missing values\n",
    "linked_data = handle_missing_values(linked_data, trait)\n",
    "print(f\"Data shape after handling missing values: {linked_data.shape}\")\n",
    "\n",
    "# 5. Check for bias in features\n",
    "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "\n",
    "# 6. 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 intestinal epithelial cells vs intraepithelial lymphocytes in Celiac Disease study.\"\n",
    ")\n",
    "\n",
    "# 7. 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": {
  "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
}