File size: 25,214 Bytes
736e4a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "d7f1fba8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:33:24.640787Z",
     "iopub.status.busy": "2025-03-25T06:33:24.640564Z",
     "iopub.status.idle": "2025-03-25T06:33:24.804364Z",
     "shell.execute_reply": "2025-03-25T06:33:24.803941Z"
    }
   },
   "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 = \"Arrhythmia\"\n",
    "cohort = \"GSE143924\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Arrhythmia\"\n",
    "in_cohort_dir = \"../../input/GEO/Arrhythmia/GSE143924\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Arrhythmia/GSE143924.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Arrhythmia/gene_data/GSE143924.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Arrhythmia/clinical_data/GSE143924.csv\"\n",
    "json_path = \"../../output/preprocess/Arrhythmia/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bfc68f17",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "30a6115e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:33:24.805807Z",
     "iopub.status.busy": "2025-03-25T06:33:24.805670Z",
     "iopub.status.idle": "2025-03-25T06:33:24.857583Z",
     "shell.execute_reply": "2025-03-25T06:33:24.857210Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Transcriptome analysis from human epicardial adipose tissue biopsies analyzed according to postoperative atrial fibrillation occurrence after cardiac surgery\"\n",
      "!Series_summary\t\"Introduction: Post-operative atrial fibrillation (POAF) is a frequent complication after cardiac surgery, but its pathophysiology remains incompletely understood. Considering that epicardial adipose tissue (EAT) is in close vicinity with the atrial myocardium, we hypothesized that a specific pre-operative EAT phenotype would be associated to POAF onset following surgery.  Methods: Patients undergoing cardiac surgery prospectively enrolled in the POMI-AF cohort between February 2016 and June 2017 were studied. EAT samples were collected at the beginning of surgery. Whole-tissue gene expression patterns and the stromal and vascular fraction (SVF) cellular composition were explored. Patients were followed after surgery by continuous ECG to detect POAF onset.  Results: Among the 60 patients included in the cohort, 15 POAF and 15 non-POAF patients were matched based on pre-operative characteristics. Gene set enrichment analysis of transcriptomic data from pre-operative EAT samples revealed 40 enriched biological processes in POAF vs non-POAF patients. Most of these processes were related to cellular immune response. Leukocytes (63±15% of total cells), and more specifically lymphocytes (56±13% of total CD45+ cells), represented the major cell subset in the preoperative EAT SVF, with no quantitative differences between POAF and SR patients (76 [52; 84]% vs 56 [50; 64]%, p=0.22). However, POAF patients presented a significantly higher cytotoxic CD8+/helper CD4+ T lymphocyte ratio than SR patients (respectively, 0.69[0.55; 1.19] vs 0.50 [0.31; 0.54], p=0.03) suggesting a cytotoxic shift prior to surgery.  Conclusion: Epicardial fat from patients who develop POAF displays a specific pre-operative transcriptome signature characteristic of cellular immune response and cytotoxic lymphocyte enrichment.\"\n",
      "!Series_overall_design\t\"30 matched samples analyzed (15 POAF vs 15 SR patients)\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['tissue: epicardial adipose tissue'], 1: ['patient diagnosis: sinus rhythm after surgery', 'patient diagnosis: postoperative atrial fibrillation after surgery (POAF)']}\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": "63b2d557",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "42941db0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:33:24.858637Z",
     "iopub.status.busy": "2025-03-25T06:33:24.858533Z",
     "iopub.status.idle": "2025-03-25T06:33:24.863389Z",
     "shell.execute_reply": "2025-03-25T06:33:24.862978Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical data file not found at ../../input/GEO/Arrhythmia/GSE143924/clinical_data.csv\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "import json\n",
    "from typing import Dict, Any, Optional, Callable\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on the series title and summary, this dataset appears to contain transcriptome analysis\n",
    "# which typically includes gene expression data\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# For trait (Arrhythmia/POAF), we can see it's available in row 1 of the sample characteristics\n",
    "trait_row = 1\n",
    "\n",
    "# For age and gender, they don't appear to be explicitly mentioned in the sample characteristics\n",
    "age_row = None\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait values to binary format (0 for sinus rhythm, 1 for POAF)\"\"\"\n",
    "    if isinstance(value, str):\n",
    "        if \"sinus rhythm\" in value.lower():\n",
    "            return 0\n",
    "        elif \"postoperative atrial fibrillation\" in value.lower() or \"poaf\" in value.lower():\n",
    "            return 1\n",
    "    return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age values to continuous format\"\"\"\n",
    "    # Since age data is not available, this function is just a placeholder\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender values to binary format (0 for female, 1 for male)\"\"\"\n",
    "    # Since gender data is not available, this function is just a placeholder\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait data availability\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Conduct initial filtering and save 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",
    "# 4. Clinical Feature Extraction\n",
    "# Only proceed if trait_row is not None\n",
    "if trait_row is not None:\n",
    "    # Load the clinical data\n",
    "    clinical_data_file = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n",
    "    if os.path.exists(clinical_data_file):\n",
    "        clinical_data = pd.read_csv(clinical_data_file)\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",
    "        # Preview the dataframe\n",
    "        preview = preview_df(selected_clinical_df)\n",
    "        print(\"Preview of selected clinical features:\")\n",
    "        print(preview)\n",
    "        \n",
    "        # Create directory if it doesn't exist\n",
    "        os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "        \n",
    "        # Save to CSV\n",
    "        selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
    "        print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "    else:\n",
    "        print(f\"Clinical data file not found at {clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "06ee4598",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "b9008776",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:33:24.864569Z",
     "iopub.status.busy": "2025-03-25T06:33:24.864468Z",
     "iopub.status.idle": "2025-03-25T06:33:24.913883Z",
     "shell.execute_reply": "2025-03-25T06:33:24.913513Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Matrix file found: ../../input/GEO/Arrhythmia/GSE143924/GSE143924_series_matrix.txt.gz\n",
      "Gene data shape: (8596, 30)\n",
      "First 20 gene/probe identifiers:\n",
      "Index(['A2M-AS1', 'AACS', 'AADAC', 'AADACL2', 'AADACP1', 'AAK1', 'AARD',\n",
      "       'AASS', 'ABCA1', 'ABCA10', 'ABCA11P', 'ABCA3', 'ABCA5', 'ABCA9-AS1',\n",
      "       'ABCB1', 'ABCB11', 'ABCB4', 'ABCB7', 'ABCC3', 'ABCC6'],\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": "b2e16ad0",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "b79f9bbf",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:33:24.915015Z",
     "iopub.status.busy": "2025-03-25T06:33:24.914900Z",
     "iopub.status.idle": "2025-03-25T06:33:24.916781Z",
     "shell.execute_reply": "2025-03-25T06:33:24.916456Z"
    }
   },
   "outputs": [],
   "source": [
    "# These identifiers appear to be standard human gene symbols.\n",
    "# Examples like A2M-AS1, AACS, AADAC, etc. are recognized gene symbols\n",
    "# rather than probe identifiers that would need mapping.\n",
    "\n",
    "requires_gene_mapping = False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "335e5d7b",
   "metadata": {},
   "source": [
    "### Step 5: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "00835232",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:33:24.917813Z",
     "iopub.status.busy": "2025-03-25T06:33:24.917708Z",
     "iopub.status.idle": "2025-03-25T06:33:27.168849Z",
     "shell.execute_reply": "2025-03-25T06:33:27.168319Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape before normalization: (8596, 30)\n",
      "Gene data shape after normalization: (7873, 30)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene expression data saved to ../../output/preprocess/Arrhythmia/gene_data/GSE143924.csv\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Original clinical data preview:\n",
      "         !Sample_geo_accession                                     GSM4276706  \\\n",
      "0  !Sample_characteristics_ch1              tissue: epicardial adipose tissue   \n",
      "1  !Sample_characteristics_ch1  patient diagnosis: sinus rhythm after surgery   \n",
      "\n",
      "                                      GSM4276707  \\\n",
      "0              tissue: epicardial adipose tissue   \n",
      "1  patient diagnosis: sinus rhythm after surgery   \n",
      "\n",
      "                                      GSM4276708  \\\n",
      "0              tissue: epicardial adipose tissue   \n",
      "1  patient diagnosis: sinus rhythm after surgery   \n",
      "\n",
      "                                      GSM4276709  \\\n",
      "0              tissue: epicardial adipose tissue   \n",
      "1  patient diagnosis: sinus rhythm after surgery   \n",
      "\n",
      "                                      GSM4276710  \\\n",
      "0              tissue: epicardial adipose tissue   \n",
      "1  patient diagnosis: sinus rhythm after surgery   \n",
      "\n",
      "                                      GSM4276711  \\\n",
      "0              tissue: epicardial adipose tissue   \n",
      "1  patient diagnosis: sinus rhythm after surgery   \n",
      "\n",
      "                                      GSM4276712  \\\n",
      "0              tissue: epicardial adipose tissue   \n",
      "1  patient diagnosis: sinus rhythm after surgery   \n",
      "\n",
      "                                      GSM4276713  \\\n",
      "0              tissue: epicardial adipose tissue   \n",
      "1  patient diagnosis: sinus rhythm after surgery   \n",
      "\n",
      "                                      GSM4276714  ...  \\\n",
      "0              tissue: epicardial adipose tissue  ...   \n",
      "1  patient diagnosis: sinus rhythm after surgery  ...   \n",
      "\n",
      "                                          GSM4276726  \\\n",
      "0                  tissue: epicardial adipose tissue   \n",
      "1  patient diagnosis: postoperative atrial fibril...   \n",
      "\n",
      "                                          GSM4276727  \\\n",
      "0                  tissue: epicardial adipose tissue   \n",
      "1  patient diagnosis: postoperative atrial fibril...   \n",
      "\n",
      "                                          GSM4276728  \\\n",
      "0                  tissue: epicardial adipose tissue   \n",
      "1  patient diagnosis: postoperative atrial fibril...   \n",
      "\n",
      "                                          GSM4276729  \\\n",
      "0                  tissue: epicardial adipose tissue   \n",
      "1  patient diagnosis: postoperative atrial fibril...   \n",
      "\n",
      "                                          GSM4276730  \\\n",
      "0                  tissue: epicardial adipose tissue   \n",
      "1  patient diagnosis: postoperative atrial fibril...   \n",
      "\n",
      "                                          GSM4276731  \\\n",
      "0                  tissue: epicardial adipose tissue   \n",
      "1  patient diagnosis: postoperative atrial fibril...   \n",
      "\n",
      "                                          GSM4276732  \\\n",
      "0                  tissue: epicardial adipose tissue   \n",
      "1  patient diagnosis: postoperative atrial fibril...   \n",
      "\n",
      "                                          GSM4276733  \\\n",
      "0                  tissue: epicardial adipose tissue   \n",
      "1  patient diagnosis: postoperative atrial fibril...   \n",
      "\n",
      "                                          GSM4276734  \\\n",
      "0                  tissue: epicardial adipose tissue   \n",
      "1  patient diagnosis: postoperative atrial fibril...   \n",
      "\n",
      "                                          GSM4276735  \n",
      "0                  tissue: epicardial adipose tissue  \n",
      "1  patient diagnosis: postoperative atrial fibril...  \n",
      "\n",
      "[2 rows x 31 columns]\n",
      "Selected clinical data shape: (1, 30)\n",
      "Clinical data preview:\n",
      "            GSM4276706  GSM4276707  GSM4276708  GSM4276709  GSM4276710  \\\n",
      "Arrhythmia         0.0         0.0         0.0         0.0         0.0   \n",
      "\n",
      "            GSM4276711  GSM4276712  GSM4276713  GSM4276714  GSM4276715  ...  \\\n",
      "Arrhythmia         0.0         0.0         0.0         0.0         0.0  ...   \n",
      "\n",
      "            GSM4276726  GSM4276727  GSM4276728  GSM4276729  GSM4276730  \\\n",
      "Arrhythmia         1.0         1.0         1.0         1.0         1.0   \n",
      "\n",
      "            GSM4276731  GSM4276732  GSM4276733  GSM4276734  GSM4276735  \n",
      "Arrhythmia         1.0         1.0         1.0         1.0         1.0  \n",
      "\n",
      "[1 rows x 30 columns]\n",
      "Linked data shape before processing: (30, 7874)\n",
      "Linked data preview (first 5 rows, 5 columns):\n",
      "            Arrhythmia     A2M-AS1         AACS         AADAC     AADACL2\n",
      "GSM4276706         0.0  508.207839   381.384960    111.908777   69.831635\n",
      "GSM4276707         0.0  892.370816  1172.689215  20000.000000   78.385174\n",
      "GSM4276708         0.0  821.254817   264.082320    384.802720  102.435318\n",
      "GSM4276709         0.0  925.448628   253.827399    209.135691   58.320162\n",
      "GSM4276710         0.0  489.628264   363.278332   3299.517699   64.239732\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Data shape after handling missing values: (30, 7874)\n",
      "For the feature 'Arrhythmia', the least common label is '0.0' with 15 occurrences. This represents 50.00% of the dataset.\n",
      "The distribution of the feature 'Arrhythmia' in this dataset is fine.\n",
      "\n",
      "Data shape after removing biased features: (30, 7874)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Arrhythmia/GSE143924.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "# Use normalize_gene_symbols_in_index to standardize gene symbols\n",
    "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Gene data shape before normalization: {gene_data.shape}\")\n",
    "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
    "\n",
    "# Save the normalized gene data to file\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "normalized_gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Normalized gene expression data saved to {out_gene_data_file}\")\n",
    "\n",
    "# Load the actual clinical data from the matrix file that was previously obtained in Step 1\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n",
    "\n",
    "# Get preview of clinical data to understand its structure\n",
    "print(\"Original clinical data preview:\")\n",
    "print(clinical_data.head())\n",
    "\n",
    "# 2. If we have trait data available, proceed with linking\n",
    "if trait_row is not None:\n",
    "    # Extract clinical features using the original clinical data\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(f\"Selected clinical data shape: {selected_clinical_df.shape}\")\n",
    "    print(\"Clinical data preview:\")\n",
    "    print(selected_clinical_df.head())\n",
    "\n",
    "    # Link the clinical and genetic data\n",
    "    linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n",
    "    print(f\"Linked data shape before processing: {linked_data.shape}\")\n",
    "    print(\"Linked data preview (first 5 rows, 5 columns):\")\n",
    "    print(linked_data.iloc[:5, :5] if not linked_data.empty else \"Empty dataframe\")\n",
    "\n",
    "    # 3. Handle missing values\n",
    "    try:\n",
    "        linked_data = handle_missing_values(linked_data, trait)\n",
    "        print(f\"Data shape after handling missing values: {linked_data.shape}\")\n",
    "    except Exception as e:\n",
    "        print(f\"Error handling missing values: {e}\")\n",
    "        linked_data = pd.DataFrame()  # Create empty dataframe if error occurs\n",
    "\n",
    "    # 4. Check for bias in features\n",
    "    if not linked_data.empty and linked_data.shape[0] > 0:\n",
    "        is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "        print(f\"Data shape after removing biased features: {linked_data.shape}\")\n",
    "    else:\n",
    "        is_biased = True\n",
    "        print(\"Cannot check for bias as dataframe is empty or has no rows after missing value handling\")\n",
    "\n",
    "    # 5. Validate and save cohort information\n",
    "    note = \"\"\n",
    "    if linked_data.empty or linked_data.shape[0] == 0:\n",
    "        note = \"Dataset contains gene expression data related to atrial fibrillation after cardiac surgery, but linking clinical and genetic data failed, possibly due to mismatched sample IDs.\"\n",
    "    else:\n",
    "        note = \"Dataset contains gene expression data for atrial fibrillation after cardiac surgery, which is relevant to arrhythmia research.\"\n",
    "    \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=note\n",
    "    )\n",
    "\n",
    "    # 6. Save the linked data if usable\n",
    "    if is_usable:\n",
    "        os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "        linked_data.to_csv(out_data_file)\n",
    "        print(f\"Linked data saved to {out_data_file}\")\n",
    "    else:\n",
    "        print(\"Dataset is not usable for analysis. No linked data file saved.\")\n",
    "else:\n",
    "    # If no trait data available, validate with trait_available=False\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=False,\n",
    "        is_biased=True,  # Set to True since we can't use data without trait\n",
    "        df=pd.DataFrame(),  # Empty DataFrame\n",
    "        note=\"Dataset contains gene expression data but lacks proper clinical trait information for arrhythmia analysis.\"\n",
    "    )\n",
    "    \n",
    "    print(\"Dataset is not usable for arrhythmia analysis due to lack of clinical trait data. 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
}