File size: 27,878 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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ae0597a5",
   "metadata": {},
   "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 = \"Chronic_kidney_disease\"\n",
    "cohort = \"GSE104954\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Chronic_kidney_disease\"\n",
    "in_cohort_dir = \"../../input/GEO/Chronic_kidney_disease/GSE104954\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Chronic_kidney_disease/GSE104954.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Chronic_kidney_disease/gene_data/GSE104954.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Chronic_kidney_disease/clinical_data/GSE104954.csv\"\n",
    "json_path = \"../../output/preprocess/Chronic_kidney_disease/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ebfe3273",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "356611f7",
   "metadata": {},
   "outputs": [],
   "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": "8bbc8aec",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "606d48e9",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Analyze gene expression availability\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import os\n",
    "\n",
    "is_gene_available = True  # Based on the background information mentioning \"transcriptome\" and \"hybridization on Affymetrix microarrays\"\n",
    "\n",
    "# 2. Variable availability and data type conversion\n",
    "# 2.1 Identify rows in sample characteristics dictionary for each variable\n",
    "trait_row = 1  # diagnosis is in row 1\n",
    "age_row = None  # age not available in the data\n",
    "gender_row = None  # gender not available in the data\n",
    "\n",
    "# 2.2 Define conversion functions for each variable\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert diagnosis values to binary indicating chronic kidney disease status.\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # All diagnoses in the dataset represent forms of chronic kidney disease\n",
    "    # except possibly \"Tumor nephrectomy\" which is a procedure\n",
    "    if value == \"Tumor nephrectomy\":\n",
    "        return 0  # Not CKD\n",
    "    else:\n",
    "        return 1  # CKD condition\n",
    "    \n",
    "def convert_age(value):\n",
    "    \"\"\"Placeholder function for age conversion.\"\"\"\n",
    "    return None  # Age data not available\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Placeholder function for gender conversion.\"\"\"\n",
    "    return None  # Gender data not available\n",
    "\n",
    "# 3. Save metadata about dataset usability\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. If trait data is available, extract clinical features\n",
    "if trait_row is not None:\n",
    "    # Create a proper clinical data DataFrame from the sample characteristics dictionary\n",
    "    # Using a format that matches what geo_select_clinical_features expects\n",
    "    \n",
    "    # Initialize an empty dataframe\n",
    "    clinical_data = pd.DataFrame()\n",
    "    \n",
    "    # Add the sample characteristics as columns\n",
    "    clinical_data[0] = ['tissue: Tubulointerstitium from kidney biopsy']\n",
    "    clinical_data[1] = ['diagnosis: Diabetic nephropathy']  # We'll add one value and update later\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 data\n",
    "    preview = preview_df(selected_clinical_df)\n",
    "    print(\"Clinical data preview:\", preview)\n",
    "    \n",
    "    # Save clinical data to CSV\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\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": "ee2d4ef7",
   "metadata": {},
   "source": [
    "### Step 3: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4ba964d6",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import json\n",
    "from typing import Callable, Optional, Dict, Any\n",
    "\n",
    "# First, we need to load the needed data\n",
    "# Let's assume the clinical_data DataFrame was already loaded in a previous step\n",
    "# If not available, we need to load it first\n",
    "try:\n",
    "    clinical_data\n",
    "except NameError:\n",
    "    # Load the clinical data if not already loaded\n",
    "    clinical_data_path = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n",
    "    if os.path.exists(clinical_data_path):\n",
    "        clinical_data = pd.read_csv(clinical_data_path)\n",
    "    else:\n",
    "        # Try alternative location\n",
    "        clinical_data_path = os.path.join(in_cohort_dir, \"sample_characteristics.csv\")\n",
    "        if os.path.exists(clinical_data_path):\n",
    "            clinical_data = pd.read_csv(clinical_data_path)\n",
    "        else:\n",
    "            raise FileNotFoundError(f\"Clinical data file not found at {clinical_data_path}\")\n",
    "\n",
    "# Check if we have gene expression data (not miRNA or methylation)\n",
    "# This requires examining the available data files\n",
    "gene_files = [f for f in os.listdir(in_cohort_dir) if f.endswith('.txt') or f.endswith('.csv') or f.endswith('.tsv')]\n",
    "gene_expression_patterns = ['expr', 'gene', 'rna', 'expression']\n",
    "has_gene_files = any(any(pattern in f.lower() for pattern in gene_expression_patterns) for f in gene_files)\n",
    "\n",
    "is_gene_available = has_gene_files  # Set based on file examination\n",
    "if not is_gene_available:\n",
    "    # If we couldn't find evidence from filenames, let's check if we have any matrix files that might contain gene data\n",
    "    matrix_files = [f for f in os.listdir(in_cohort_dir) if 'matrix' in f.lower()]\n",
    "    is_gene_available = len(matrix_files) > 0\n",
    "\n",
    "# Inspect the clinical data to understand what's available\n",
    "print(\"Clinical data columns:\", clinical_data.columns.tolist())\n",
    "print(\"Clinical data shape:\", clinical_data.shape)\n",
    "print(\"First few rows of clinical data:\")\n",
    "print(clinical_data.head())\n",
    "\n",
    "# Let's examine unique values in each row to identify relevant rows\n",
    "unique_values = {}\n",
    "for i in range(len(clinical_data)):\n",
    "    row_values = clinical_data.iloc[i, 1:].unique()\n",
    "    if len(row_values) > 1:  # Only consider rows with multiple values\n",
    "        print(f\"Row {i}: {clinical_data.iloc[i, 0]} - Unique values: {row_values}\")\n",
    "        unique_values[i] = row_values\n",
    "\n",
    "# Based on the examination, determine key rows for trait, age, and gender\n",
    "# For CKD, we're looking for rows related to kidney disease status, patient age, and gender/sex\n",
    "\n",
    "# For trait (CKD), look for keywords like \"disease\", \"status\", \"CKD\", \"kidney\", etc.\n",
    "trait_keywords = [\"kidney\", \"ckd\", \"disease\", \"status\", \"diagnosis\", \"patient\", \"healthy\", \"control\"]\n",
    "trait_row = None\n",
    "for i, values in unique_values.items():\n",
    "    row_name = str(clinical_data.iloc[i, 0]).lower()\n",
    "    if any(keyword in row_name for keyword in trait_keywords):\n",
    "        if len(unique_values[i]) > 1:  # Ensure it's not a constant feature\n",
    "            trait_row = i\n",
    "            print(f\"Trait row identified: {i} - {clinical_data.iloc[i, 0]}\")\n",
    "            break\n",
    "\n",
    "# For age, look for \"age\" in the row name\n",
    "age_row = None\n",
    "for i, values in unique_values.items():\n",
    "    row_name = str(clinical_data.iloc[i, 0]).lower()\n",
    "    if \"age\" in row_name:\n",
    "        if len(unique_values[i]) > 1:  # Ensure it's not a constant feature\n",
    "            age_row = i\n",
    "            print(f\"Age row identified: {i} - {clinical_data.iloc[i, 0]}\")\n",
    "            break\n",
    "\n",
    "# For gender, look for \"gender\", \"sex\", \"male\", \"female\" in the row name\n",
    "gender_row = None\n",
    "gender_keywords = [\"gender\", \"sex\", \"male\", \"female\"]\n",
    "for i, values in unique_values.items():\n",
    "    row_name = str(clinical_data.iloc[i, 0]).lower()\n",
    "    if any(keyword in row_name for keyword in gender_keywords):\n",
    "        if len(unique_values[i]) > 1:  # Ensure it's not a constant feature\n",
    "            gender_row = i\n",
    "            print(f\"Gender row identified: {i} - {clinical_data.iloc[i, 0]}\")\n",
    "            break\n",
    "\n",
    "# Define conversion functions for each variable\n",
    "def convert_trait(value):\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    value = str(value).lower()\n",
    "    # Extract value after colon if present\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary based on common CKD terminology\n",
    "    if any(term in value for term in [\"ckd\", \"chronic kidney disease\", \"patient\", \"disease\", \"positive\", \"yes\"]):\n",
    "        return 1\n",
    "    elif any(term in value for term in [\"control\", \"healthy\", \"normal\", \"negative\", \"no\"]):\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    value = str(value)\n",
    "    # Extract value after colon if present\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Try to extract age value\n",
    "    import re\n",
    "    age_match = re.search(r'(\\d+)', value)\n",
    "    if age_match:\n",
    "        return float(age_match.group(1))\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    value = str(value).lower()\n",
    "    # Extract value after colon if present\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary: female = 0, male = 1\n",
    "    if any(term in value for term in [\"female\", \"f\", \"woman\", \"women\"]):\n",
    "        return 0\n",
    "    elif any(term in value for term in [\"male\", \"m\", \"man\", \"men\"]):\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# Determine if trait data is available\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Save initial 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",
    "# Extract clinical features if trait data is available\n",
    "if is_trait_available:\n",
    "    # Extract features using the library function\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 extracted data\n",
    "    print(\"Preview of extracted clinical features:\")\n",
    "    print(preview_df(selected_clinical_df.T))\n",
    "    \n",
    "    # Save the extracted clinical data\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    selected_clinical_df.T.to_csv(out_clinical_data_file, index=True)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "78de8406",
   "metadata": {},
   "source": [
    "### Step 4: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0eeacca8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 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",
    "print(f\"SOFT file: {soft_file}\")\n",
    "print(f\"Matrix file: {matrix_file}\")\n",
    "\n",
    "# Set gene availability flag\n",
    "is_gene_available = True  # Initially assume gene data is available\n",
    "\n",
    "# First check if the matrix file contains the expected marker\n",
    "found_marker = False\n",
    "try:\n",
    "    with gzip.open(matrix_file, 'rt') as file:\n",
    "        for line in file:\n",
    "            if \"!series_matrix_table_begin\" in line:\n",
    "                found_marker = True\n",
    "                break\n",
    "    \n",
    "    if found_marker:\n",
    "        print(\"Found the matrix table marker in the file.\")\n",
    "    else:\n",
    "        print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
    "        \n",
    "    # Try to extract gene data from the matrix file\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    \n",
    "    if gene_data.shape[0] == 0:\n",
    "        print(\"Warning: Extracted gene data has 0 rows.\")\n",
    "        is_gene_available = False\n",
    "    else:\n",
    "        print(f\"Gene data shape: {gene_data.shape}\")\n",
    "        # Print the first 20 gene/probe identifiers\n",
    "        print(\"First 20 gene/probe identifiers:\")\n",
    "        print(gene_data.index[:20].tolist())\n",
    "        \n",
    "except Exception as e:\n",
    "    print(f\"Error extracting gene data: {e}\")\n",
    "    is_gene_available = False\n",
    "    \n",
    "    # Try to diagnose the file format\n",
    "    print(\"Examining file content to diagnose the issue:\")\n",
    "    try:\n",
    "        with gzip.open(matrix_file, 'rt') as file:\n",
    "            for i, line in enumerate(file):\n",
    "                if i < 10:  # Print first 10 lines to diagnose\n",
    "                    print(f\"Line {i}: {line.strip()[:100]}...\")  # Print first 100 chars of each line\n",
    "                else:\n",
    "                    break\n",
    "    except Exception as e2:\n",
    "        print(f\"Error examining file: {e2}\")\n",
    "\n",
    "if not is_gene_available:\n",
    "    print(\"Gene expression data could not be successfully extracted from this dataset.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d94373df",
   "metadata": {},
   "source": [
    "### Step 5: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b3732419",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Reviewing gene identifiers \n",
    "# The pattern \"10000_at\", \"10001_at\" suggests these are probe IDs from an Affymetrix microarray\n",
    "# These are not standard human gene symbols and will need to be mapped to gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3eb878c0",
   "metadata": {},
   "source": [
    "### Step 6: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "501aa0ee",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "\n",
    "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
    "print(\"\\nGene annotation preview:\")\n",
    "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
    "print(preview_df(gene_annotation, n=5))\n",
    "\n",
    "# Get a more complete view to understand the annotation structure\n",
    "print(\"\\nComplete sample of a few rows:\")\n",
    "print(gene_annotation.iloc[:3].to_string())\n",
    "\n",
    "# Check if there are any columns that might contain gene information beyond what we've seen\n",
    "potential_gene_columns = [col for col in gene_annotation.columns if \n",
    "                          any(term in col.upper() for term in [\"GENE\", \"SYMBOL\", \"NAME\", \"ID\"])]\n",
    "print(f\"\\nPotential gene-related columns: {potential_gene_columns}\")\n",
    "\n",
    "# Look for additional columns that might contain gene symbols\n",
    "# Since we only have 'ID' and 'ENTREZ_GENE_ID', check if we need to use Entrez IDs for mapping\n",
    "gene_id_col = 'ID'\n",
    "gene_symbol_col = None\n",
    "\n",
    "# Check various potential column names for gene symbols\n",
    "for col_name in ['GENE_SYMBOL', 'SYMBOL', 'GENE', 'GENE_NAME', 'GB_ACC']:\n",
    "    if col_name in gene_annotation.columns:\n",
    "        gene_symbol_col = col_name\n",
    "        break\n",
    "\n",
    "# If no dedicated symbol column is found, we'll need to use ENTREZ_GENE_ID\n",
    "if gene_symbol_col is None and 'ENTREZ_GENE_ID' in gene_annotation.columns:\n",
    "    gene_symbol_col = 'ENTREZ_GENE_ID'\n",
    "    print(\"\\nNo direct gene symbol column found. Will use Entrez Gene IDs for mapping.\")\n",
    "\n",
    "if gene_id_col in gene_annotation.columns and gene_symbol_col is not None:\n",
    "    print(f\"\\nSample mappings from '{gene_id_col}' to '{gene_symbol_col}':\")\n",
    "    sample_mappings = gene_annotation[[gene_id_col, gene_symbol_col]].head(10)\n",
    "    print(sample_mappings)\n",
    "    \n",
    "    # Check for non-null mappings to confirm data quality\n",
    "    non_null_mappings = gene_annotation[[gene_id_col, gene_symbol_col]].dropna(subset=[gene_symbol_col])\n",
    "    print(f\"\\nNumber of probes with gene ID mappings: {len(non_null_mappings)}\")\n",
    "    print(f\"Sample of valid mappings:\")\n",
    "    print(non_null_mappings.head(5))\n",
    "else:\n",
    "    print(\"Required mapping columns not found in the annotation data. Will need to explore alternative mapping approaches.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "50d9d7bc",
   "metadata": {},
   "source": [
    "### Step 7: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "93bf9b92",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Determine which columns contain the gene identifiers and gene symbols\n",
    "gene_id_col = 'ID'  # This matches the identifiers seen in gene_data.index\n",
    "gene_symbol_col = 'Symbol'  # This contains the human gene symbols\n",
    "\n",
    "# 2. Create gene mapping dataframe using the identified columns\n",
    "mapping_df = get_gene_mapping(gene_annotation, gene_id_col, gene_symbol_col)\n",
    "print(f\"Created mapping dataframe with shape: {mapping_df.shape}\")\n",
    "print(\"Sample of mapping data:\")\n",
    "print(mapping_df.head())\n",
    "\n",
    "# 3. Apply gene mapping to convert probe-level measurements to gene-level expression data\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
    "print(f\"Converted gene expression data shape: {gene_data.shape}\")\n",
    "print(\"First few gene symbols after mapping:\")\n",
    "print(gene_data.index[:10].tolist())\n",
    "\n",
    "# Check for genes with highest expression to verify successful mapping\n",
    "print(\"\\nSample of genes with highest mean expression:\")\n",
    "mean_expr = gene_data.mean(axis=1)\n",
    "high_expr_genes = mean_expr.nlargest(5)\n",
    "print(high_expr_genes)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e86d0e7a",
   "metadata": {},
   "source": [
    "### Step 8: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a531181d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. First, load the genetic data from the matrix file again\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "gene_data = get_genetic_data(matrix_file)\n",
    "print(f\"Loaded gene data shape: {gene_data.shape}\")\n",
    "\n",
    "# Get the gene annotation data for mapping\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "gene_id_col = 'ID'\n",
    "gene_symbol_col = 'Symbol'\n",
    "mapping_df = get_gene_mapping(gene_annotation, gene_id_col, gene_symbol_col)\n",
    "print(f\"Created mapping dataframe with shape: {mapping_df.shape}\")\n",
    "\n",
    "# Apply gene mapping to convert probe-level measurements to gene-level expression data\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
    "print(f\"Converted gene expression data shape: {gene_data.shape}\")\n",
    "\n",
    "# Normalize gene symbols in the gene expression data\n",
    "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n",
    "\n",
    "# Save the normalized gene data\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 data saved to {out_gene_data_file}\")\n",
    "\n",
    "# 2. Extract trait information from the clinical_data\n",
    "# Re-extract the clinical data from the matrix file\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",
    "# Get unique values from clinical data to understand the structure\n",
    "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
    "print(\"Sample Characteristics Dictionary:\")\n",
    "print(sample_characteristics_dict)\n",
    "\n",
    "# Define the trait row and conversion function\n",
    "trait_row = 1  # diagnosis is in row 1\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert diagnosis values to binary indicating chronic kidney disease status.\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # All diagnoses in the dataset represent forms of chronic kidney disease\n",
    "    # except possibly \"Tumor nephrectomy\" which is a procedure\n",
    "    if value == \"Tumor nephrectomy\":\n",
    "        return 0  # Not CKD\n",
    "    else:\n",
    "        return 1  # CKD condition\n",
    "\n",
    "# Create the clinical dataframe\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=None,  # No age data\n",
    "    convert_age=None,\n",
    "    gender_row=None,  # No gender data\n",
    "    convert_gender=None\n",
    ")\n",
    "\n",
    "# Save the clinical data\n",
    "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "selected_clinical_df.to_csv(out_clinical_data_file)\n",
    "print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "print(\"Clinical data preview:\")\n",
    "print(preview_df(selected_clinical_df))\n",
    "\n",
    "# 3. Link clinical and genetic data\n",
    "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "\n",
    "# Handle missing values\n",
    "linked_data = handle_missing_values(linked_data, trait)\n",
    "print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
    "\n",
    "# 4. Check for bias in trait and demographic features\n",
    "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "\n",
    "# 5. Validate the data quality and save cohort info\n",
    "note = \"Dataset contains kidney tubulointerstitial gene expression data from patients with various forms of chronic kidney disease.\"\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 it's 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(\"Data not usable for the trait study - not saving final linked data.\")"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}