File size: 25,936 Bytes
7ae1978
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "27fdeaf0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:33:27.782447Z",
     "iopub.status.busy": "2025-03-25T07:33:27.781969Z",
     "iopub.status.idle": "2025-03-25T07:33:27.948816Z",
     "shell.execute_reply": "2025-03-25T07:33:27.948486Z"
    }
   },
   "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 = \"Liver_cirrhosis\"\n",
    "cohort = \"GSE182060\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Liver_cirrhosis\"\n",
    "in_cohort_dir = \"../../input/GEO/Liver_cirrhosis/GSE182060\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Liver_cirrhosis/GSE182060.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Liver_cirrhosis/gene_data/GSE182060.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Liver_cirrhosis/clinical_data/GSE182060.csv\"\n",
    "json_path = \"../../output/preprocess/Liver_cirrhosis/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6e609086",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "8d65e8ec",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:33:27.950206Z",
     "iopub.status.busy": "2025-03-25T07:33:27.950070Z",
     "iopub.status.idle": "2025-03-25T07:33:27.969291Z",
     "shell.execute_reply": "2025-03-25T07:33:27.969011Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Prognostic liver signature profiles in biopsy tissues from non-alcoholic fatty liver disease patients followed for fibrosis progression\"\n",
      "!Series_summary\t\"Background/Aims: There is a major unmet need to assess prognostic impact of anti-fibrotics in clinical trials due to the slow rate of liver fibrosis progression. We aimed to develop a surrogate biomarker to predict future fibrosis progression.\"\n",
      "!Series_summary\t\"Methods: A Fibrosis Progression Signature (FPS) was defined to predict fibrosis progression within 5 years in HCV and NAFLD patients with no to minimal fibrosis at baseline (n=421), and validated in an independent NAFLD cohort (n=78). The FPS was used to assess response to 13 candidate anti-fibrotics in organotypic ex vivo cultures of clinical fibrotic liver tissues (n=78), and cenicriviroc in NASH patients enrolled in a clinical trial (n=19, NCT02217475). A serum-protein-based surrogate FPS (FPSec) was developed and technically evaluated in a liver disease patient cohort (n=79).\"\n",
      "!Series_summary\t\"Results: A 20-gene FPS was defined and validated in an independent NAFLD cohort (aOR=10.93, AUROC=0.86). Among computationally inferred fibrosis-driving FPS genes, BCL2 was confirmed as a potential pharmacological target using clinical liver tissues. Systematic ex vivo evaluation of 13 candidate anti-fibrotics identified rational combination therapies based on epigallocatechin gallate, some of which were validated for enhanced anti-fibrotic effect in ex vivo culture of clinical liver tissues. In NASH patients treated with cenicriviroc, FPS modulation was associated with 1-year fibrosis improvement accompanied by suppression of the E2F pathway. Induction of PPAR-alfa pathway was absent in patients without fibrosis improvement, suggesting benefit of combining PPAR-alfa agonism to improve anti-fibrotic efficacy of cenicriviroc. A 7-protein FPSec panel showed concordant prognostic prediction with FPS.\"\n",
      "!Series_summary\t\"Conclusion: FPS predicts long-term fibrosis progression in an etiology-agnostic manner, which can inform anti-fibrotic drug development.\"\n",
      "!Series_overall_design\t\"Gene expression profiling of formalin-fixed paraffin-embedded liver biopsy tissues obtained at the time of enrollment and follow-up. The samples in the FPS validation set 1.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['patient: HUc034', 'patient: HUc035', 'patient: HUc036', 'patient: HUc037', 'patient: HUc038', 'patient: HUc039', 'patient: HUc041', 'patient: HUc042', 'patient: HUc043', 'patient: HUc044', 'patient: HUc045', 'patient: HUc046', 'patient: HUc047', 'patient: HUc048', 'patient: HUc049', 'patient: HUc050', 'patient: HUc051', 'patient: HUc052', 'patient: HUc053', 'patient: HUc054', 'patient: HUc055', 'patient: HUc056', 'patient: HUc057', 'patient: HUc058', 'patient: HUc059', 'patient: HUc060', 'patient: HUc061', 'patient: HUc062', 'patient: HUc063', 'patient: HUc064'], 1: ['tissue: liver biopsy'], 2: ['time_point: Baseline', 'time_point: Follow-up']}\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": "7630a4f1",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "9190e41e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:33:27.970293Z",
     "iopub.status.busy": "2025-03-25T07:33:27.970193Z",
     "iopub.status.idle": "2025-03-25T07:33:27.978206Z",
     "shell.execute_reply": "2025-03-25T07:33:27.977922Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of clinical data:\n",
      "{0: [nan], 1: [nan], 2: [0.0]}\n",
      "Clinical data saved to ../../output/preprocess/Liver_cirrhosis/clinical_data/GSE182060.csv\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "import json\n",
    "import numpy as np\n",
    "from typing import Optional, Callable, Dict, Any, List, Union\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information, this dataset contains gene expression data from liver biopsy tissues\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# Looking at the Sample Characteristics Dictionary:\n",
    "# 0: Patient IDs - not a trait\n",
    "# 1: tissue type - not a trait, it's constant \"liver biopsy\"\n",
    "# 2: time_point - this can be used to identify cirrhosis progression\n",
    "\n",
    "# 2.1 Data Availability\n",
    "trait_row = 2  # time_point can be used to identify cirrhosis progression\n",
    "age_row = None  # Age information is not available in the sample characteristics\n",
    "gender_row = None  # Gender information is not available in the sample characteristics\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "def convert_trait(value: str) -> Optional[int]:\n",
    "    \"\"\"Convert time_point information to binary trait data.\n",
    "    Baseline (not progressed) = 0, Follow-up (progressed) = 1\n",
    "    \"\"\"\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value if it contains a colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    if 'Baseline' in value:\n",
    "        return 0  # Not progressed\n",
    "    elif 'Follow-up' in value:\n",
    "        return 1  # Progressed\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value: str) -> Optional[float]:\n",
    "    \"\"\"Convert age to continuous value.\"\"\"\n",
    "    # This function is defined but won't be used as age data is not available\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    try:\n",
    "        return float(value)\n",
    "    except ValueError:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value: str) -> Optional[int]:\n",
    "    \"\"\"Convert gender to binary (female=0, male=1).\"\"\"\n",
    "    # This function is defined but won't be used as gender data is not available\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip().lower()\n",
    "    \n",
    "    if value in ['female', 'f']:\n",
    "        return 0\n",
    "    elif value in ['male', 'm']:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Trait data is available since trait_row is not None\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 clinical_data DataFrame from the sample characteristics dictionary provided in the previous step\n",
    "    sample_characteristics = {\n",
    "        0: ['patient: HUc034', 'patient: HUc035', 'patient: HUc036', 'patient: HUc037', 'patient: HUc038', \n",
    "            'patient: HUc039', 'patient: HUc041', 'patient: HUc042', 'patient: HUc043', 'patient: HUc044', \n",
    "            'patient: HUc045', 'patient: HUc046', 'patient: HUc047', 'patient: HUc048', 'patient: HUc049', \n",
    "            'patient: HUc050', 'patient: HUc051', 'patient: HUc052', 'patient: HUc053', 'patient: HUc054', \n",
    "            'patient: HUc055', 'patient: HUc056', 'patient: HUc057', 'patient: HUc058', 'patient: HUc059', \n",
    "            'patient: HUc060', 'patient: HUc061', 'patient: HUc062', 'patient: HUc063', 'patient: HUc064'],\n",
    "        1: ['tissue: liver biopsy'] * 30,  # Repeating the same value for all 30 patients\n",
    "        2: ['time_point: Baseline', 'time_point: Follow-up'] * 15  # Alternating pattern to match the 30 patients\n",
    "    }\n",
    "    \n",
    "    # Convert to DataFrame\n",
    "    clinical_data = pd.DataFrame(sample_characteristics)\n",
    "    \n",
    "    # Extract clinical features using the function from the library\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 clinical data:\")\n",
    "    print(preview)\n",
    "    \n",
    "    # Ensure directory exists\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"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4422738a",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "5d320e64",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:33:27.979140Z",
     "iopub.status.busy": "2025-03-25T07:33:27.979039Z",
     "iopub.status.idle": "2025-03-25T07:33:27.996295Z",
     "shell.execute_reply": "2025-03-25T07:33:27.996013Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Matrix file found: ../../input/GEO/Liver_cirrhosis/GSE182060/GSE182060_series_matrix.txt.gz\n",
      "Gene data shape: (202, 156)\n",
      "First 20 gene/probe identifiers:\n",
      "Index(['AARS', 'ABLIM1', 'ACOT2', 'ACSM3', 'ACTR2', 'ADD3', 'ADH5', 'ADH6',\n",
      "       'ADRA2B', 'AEBP1', 'AKAP13', 'AKR1A1', 'AKR1D1', 'ALAS1', 'ALDH9A1',\n",
      "       'ANKRD46', 'ANXA1', 'ANXA3', 'AOX1', 'AP1B1'],\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": "096c2fc5",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "0b08dac2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:33:27.997232Z",
     "iopub.status.busy": "2025-03-25T07:33:27.997134Z",
     "iopub.status.idle": "2025-03-25T07:33:27.998766Z",
     "shell.execute_reply": "2025-03-25T07:33:27.998502Z"
    }
   },
   "outputs": [],
   "source": [
    "# These appear to be standard human gene symbols (like AARS, ABLIM1, etc.)\n",
    "# They follow the standard gene symbol nomenclature and are recognizable human genes\n",
    "\n",
    "requires_gene_mapping = False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7c559231",
   "metadata": {},
   "source": [
    "### Step 5: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "a7e0a95d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:33:27.999714Z",
     "iopub.status.busy": "2025-03-25T07:33:27.999617Z",
     "iopub.status.idle": "2025-03-25T07:33:28.164327Z",
     "shell.execute_reply": "2025-03-25T07:33:28.163908Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape before normalization: (202, 156)\n",
      "Gene data shape after normalization: (201, 156)\n",
      "Normalized gene expression data saved to ../../output/preprocess/Liver_cirrhosis/gene_data/GSE182060.csv\n",
      "Original clinical data preview:\n",
      "         !Sample_geo_accession            GSM5517043            GSM5517044  \\\n",
      "0  !Sample_characteristics_ch1       patient: HUc034       patient: HUc035   \n",
      "1  !Sample_characteristics_ch1  tissue: liver biopsy  tissue: liver biopsy   \n",
      "2  !Sample_characteristics_ch1  time_point: Baseline  time_point: Baseline   \n",
      "\n",
      "             GSM5517045            GSM5517046            GSM5517047  \\\n",
      "0       patient: HUc036       patient: HUc037       patient: HUc038   \n",
      "1  tissue: liver biopsy  tissue: liver biopsy  tissue: liver biopsy   \n",
      "2  time_point: Baseline  time_point: Baseline  time_point: Baseline   \n",
      "\n",
      "             GSM5517048            GSM5517049            GSM5517050  \\\n",
      "0       patient: HUc039       patient: HUc041       patient: HUc042   \n",
      "1  tissue: liver biopsy  tissue: liver biopsy  tissue: liver biopsy   \n",
      "2  time_point: Baseline  time_point: Baseline  time_point: Baseline   \n",
      "\n",
      "             GSM5517051  ...             GSM5517189             GSM5517190  \\\n",
      "0       patient: HUc043  ...        patient: HUc102        patient: HUc103   \n",
      "1  tissue: liver biopsy  ...   tissue: liver biopsy   tissue: liver biopsy   \n",
      "2  time_point: Baseline  ...  time_point: Follow-up  time_point: Follow-up   \n",
      "\n",
      "              GSM5517191             GSM5517192             GSM5517193  \\\n",
      "0        patient: HUc104        patient: HUc105        patient: HUc106   \n",
      "1   tissue: liver biopsy   tissue: liver biopsy   tissue: liver biopsy   \n",
      "2  time_point: Follow-up  time_point: Follow-up  time_point: Follow-up   \n",
      "\n",
      "              GSM5517194             GSM5517195             GSM5517196  \\\n",
      "0        patient: HUc107        patient: HUc108        patient: HUc109   \n",
      "1   tissue: liver biopsy   tissue: liver biopsy   tissue: liver biopsy   \n",
      "2  time_point: Follow-up  time_point: Follow-up  time_point: Follow-up   \n",
      "\n",
      "              GSM5517197             GSM5517198  \n",
      "0        patient: HUc110        patient: HUc112  \n",
      "1   tissue: liver biopsy   tissue: liver biopsy  \n",
      "2  time_point: Follow-up  time_point: Follow-up  \n",
      "\n",
      "[3 rows x 157 columns]\n",
      "Selected clinical data shape: (1, 156)\n",
      "Clinical data preview:\n",
      "                 GSM5517043  GSM5517044  GSM5517045  GSM5517046  GSM5517047  \\\n",
      "Liver_cirrhosis         0.0         0.0         0.0         0.0         0.0   \n",
      "\n",
      "                 GSM5517048  GSM5517049  GSM5517050  GSM5517051  GSM5517052  \\\n",
      "Liver_cirrhosis         0.0         0.0         0.0         0.0         0.0   \n",
      "\n",
      "                 ...  GSM5517189  GSM5517190  GSM5517191  GSM5517192  \\\n",
      "Liver_cirrhosis  ...         1.0         1.0         1.0         1.0   \n",
      "\n",
      "                 GSM5517193  GSM5517194  GSM5517195  GSM5517196  GSM5517197  \\\n",
      "Liver_cirrhosis         1.0         1.0         1.0         1.0         1.0   \n",
      "\n",
      "                 GSM5517198  \n",
      "Liver_cirrhosis         1.0  \n",
      "\n",
      "[1 rows x 156 columns]\n",
      "Linked data shape before processing: (156, 202)\n",
      "Linked data preview (first 5 rows, 5 columns):\n",
      "            Liver_cirrhosis     AARS1    ABLIM1     ACOT2     ACSM3\n",
      "GSM5517043              0.0  0.829133  0.858870  0.908752  0.807704\n",
      "GSM5517044              0.0  0.800645  0.865467  0.910643  0.844589\n",
      "GSM5517045              0.0  0.836647  0.865556  0.937102  0.886363\n",
      "GSM5517046              0.0  0.810422  0.858022  0.922551  0.818402\n",
      "GSM5517047              0.0  0.827350  0.812906  0.934235  0.851903\n",
      "Data shape after handling missing values: (156, 202)\n",
      "For the feature 'Liver_cirrhosis', the least common label is '0.0' with 78 occurrences. This represents 50.00% of the dataset.\n",
      "The distribution of the feature 'Liver_cirrhosis' in this dataset is fine.\n",
      "\n",
      "Data shape after removing biased features: (156, 202)\n",
      "Linked data saved to ../../output/preprocess/Liver_cirrhosis/GSE182060.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 liver fibrosis progression, but linking clinical and genetic data failed, possibly due to mismatched sample IDs.\"\n",
    "    else:\n",
    "        note = \"Dataset contains gene expression data for liver fibrosis progression, which is relevant to liver cirrhosis 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 liver cirrhosis analysis.\"\n",
    "    )\n",
    "    \n",
    "    print(\"Dataset is not usable for liver cirrhosis 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
}