File size: 22,900 Bytes
82732bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "809cf3ea",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:48:13.627321Z",
     "iopub.status.busy": "2025-03-25T03:48:13.626781Z",
     "iopub.status.idle": "2025-03-25T03:48:13.791610Z",
     "shell.execute_reply": "2025-03-25T03:48:13.791266Z"
    }
   },
   "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 = \"Red_Hair\"\n",
    "cohort = \"GSE207744\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Red_Hair\"\n",
    "in_cohort_dir = \"../../input/GEO/Red_Hair/GSE207744\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Red_Hair/GSE207744.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Red_Hair/gene_data/GSE207744.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Red_Hair/clinical_data/GSE207744.csv\"\n",
    "json_path = \"../../output/preprocess/Red_Hair/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f18c2367",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "21821550",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:48:13.793039Z",
     "iopub.status.busy": "2025-03-25T03:48:13.792892Z",
     "iopub.status.idle": "2025-03-25T03:48:14.044591Z",
     "shell.execute_reply": "2025-03-25T03:48:14.044251Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Transcriptomic study on human skin samples: identification of actinic keratoses two risk classes.\"\n",
      "!Series_summary\t\"Gene expression profile analysis allowed to identify 2 classes of AK.\"\n",
      "!Series_overall_design\t\"A total of 72 tissue samples (24 NL, 23 L, 4 PL and 21 AK) were isolated from 24 patients. For each patient, samples were acquired on the lesion (L or AK), on the perilesional (PL) i.e. safety surgical margin area (often containing AK) and/or on the non-lesional (NL) parts of the elliptical surgical excision.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['patient number: 001', 'patient number: 006', 'patient number: 016', 'patient number: 017', 'patient number: 018=026=045', 'patient number: 028', 'patient number: 029', 'patient number: 035=041', 'patient number: 048', 'patient number: 056', 'patient number: 057', 'patient number: 074', 'patient number: 075', 'patient number: 077', 'patient number: 082', 'patient number: 090', 'patient number: 091', 'patient number: 109', 'patient number: 110', 'patient number: 115', 'patient number: 119', 'patient number: 122', 'patient number: 123', 'patient number: 125'], 1: ['sample localisation: Temple', 'sample localisation: Vertex', 'sample localisation: Forehead', 'sample localisation: Ear', 'sample localisation: Cheek', 'sample localisation: Neck anterior surface', 'sample localisation: Hand dorsum', 'sample localisation: Leg anterior surface', 'sample localisation: Shoulder'], 2: ['lesion type: Actinic Keratosis', 'lesion type: Lesion', 'lesion type: Non Lesion', 'lesion type: Peri Lesion'], 3: [nan, 'lesion number (if applicable): 1', 'lesion number (if applicable): 2', 'lesion number (if applicable): 3']}\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": "244319f9",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c930cf20",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:48:14.045875Z",
     "iopub.status.busy": "2025-03-25T03:48:14.045765Z",
     "iopub.status.idle": "2025-03-25T03:48:14.050292Z",
     "shell.execute_reply": "2025-03-25T03:48:14.050007Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "A new JSON file was created at: ../../output/preprocess/Red_Hair/cohort_info.json\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import os\n",
    "\n",
    "# 1. Determine if gene expression data is available\n",
    "# Based on the background information, this is a transcriptomic study on human skin samples\n",
    "# Therefore gene expression data should be available\n",
    "is_gene_available = True\n",
    "\n",
    "# 2.1 Data Availability for trait, age, and gender\n",
    "# Looking at the sample characteristics dictionary:\n",
    "# The dataset is about actinic keratosis skin lesions, not red hair.\n",
    "# No information about red hair is available in this dataset.\n",
    "# No age information is available in the sample characteristics\n",
    "# No gender information is available in the sample characteristics\n",
    "\n",
    "trait_row = None  # No red hair information in this dataset\n",
    "age_row = None  # No age information available\n",
    "gender_row = None  # No gender information available\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait information to binary values.\"\"\"\n",
    "    # Since there's no red hair data, this function is defined for completeness\n",
    "    return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age information to continuous values.\"\"\"\n",
    "    # No age information in this dataset, function defined for completeness\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender information to binary values.\"\"\"\n",
    "    # No gender information in this dataset, function defined for completeness\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait data availability\n",
    "is_trait_available = trait_row is not None  # Will be False\n",
    "\n",
    "# Save the cohort information\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. Clinical Feature Extraction (if trait_row is not None)\n",
    "# Since trait_row is None, we'll skip this step\n",
    "if trait_row is not None:\n",
    "    # Load the actual clinical data that should be available from previous steps\n",
    "    # Extract clinical features\n",
    "    selected_clinical_df = geo_select_clinical_features(\n",
    "        clinical_df=clinical_data,  # This would be the actual data from previous steps\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 selected clinical features\n",
    "    preview = preview_df(selected_clinical_df)\n",
    "    print(\"Preview of selected clinical features:\", preview)\n",
    "    \n",
    "    # Save the selected clinical features 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"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "17f8d75c",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "cc1d4ce2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:48:14.051466Z",
     "iopub.status.busy": "2025-03-25T03:48:14.051218Z",
     "iopub.status.idle": "2025-03-25T03:48:14.512884Z",
     "shell.execute_reply": "2025-03-25T03:48:14.512407Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107',\n",
      "       '(+)E1A_r60_a135', '(+)E1A_r60_a20', '(+)E1A_r60_a22', '(+)E1A_r60_a97',\n",
      "       '(+)E1A_r60_n11', '(+)E1A_r60_n9', '3xSLv1', 'A_19_P00315452',\n",
      "       'A_19_P00315492', 'A_19_P00315493', 'A_19_P00315502', 'A_19_P00315506',\n",
      "       'A_19_P00315518', 'A_19_P00315519', 'A_19_P00315529', 'A_19_P00315541'],\n",
      "      dtype='object', name='ID')\n"
     ]
    }
   ],
   "source": [
    "# 1. First get the file paths\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. Use the get_genetic_data function from the library to get the gene_data\n",
    "gene_data = get_genetic_data(matrix_file)\n",
    "\n",
    "# 3. Print the first 20 row IDs (gene or probe identifiers) for future observation\n",
    "print(gene_data.index[:20])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0aec9301",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c85e0aac",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:48:14.514526Z",
     "iopub.status.busy": "2025-03-25T03:48:14.514414Z",
     "iopub.status.idle": "2025-03-25T03:48:14.516264Z",
     "shell.execute_reply": "2025-03-25T03:48:14.515987Z"
    }
   },
   "outputs": [],
   "source": [
    "# Based on my biomedical knowledge, these identifiers don't appear to be standard human gene symbols\n",
    "# The identifiers that start with \"A_19_P\" look like Agilent microarray probe IDs\n",
    "# Others like \"(+)E1A_r60_1\" and \"3xSLv1\" are not standard gene symbols either\n",
    "# These will need to be mapped to standard gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b76b08c0",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "a316740b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:48:14.517195Z",
     "iopub.status.busy": "2025-03-25T03:48:14.517097Z",
     "iopub.status.idle": "2025-03-25T03:48:22.125271Z",
     "shell.execute_reply": "2025-03-25T03:48:22.124944Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['GE_BrightCorner', 'DarkCorner', 'A_21_P0014386', 'A_33_P3396872', 'A_33_P3267760'], 'CONTROL_TYPE': ['pos', 'pos', 'FALSE', 'FALSE', 'FALSE'], 'REFSEQ': [nan, nan, nan, 'NM_001105533', nan], 'GB_ACC': [nan, nan, nan, 'NM_001105533', nan], 'LOCUSLINK_ID': [nan, nan, nan, 79974.0, 54880.0], 'GENE_SYMBOL': [nan, nan, nan, 'CPED1', 'BCOR'], 'GENE_NAME': [nan, nan, nan, 'cadherin-like and PC-esterase domain containing 1', 'BCL6 corepressor'], 'UNIGENE_ID': [nan, nan, nan, 'Hs.189652', nan], 'ENSEMBL_ID': [nan, nan, nan, nan, 'ENST00000378463'], 'ACCESSION_STRING': [nan, nan, nan, 'ref|NM_001105533|gb|AK025639|gb|BC030538|tc|THC2601673', 'ens|ENST00000378463'], 'CHROMOSOMAL_LOCATION': [nan, nan, 'unmapped', 'chr7:120901888-120901947', 'chrX:39909128-39909069'], 'CYTOBAND': [nan, nan, nan, 'hs|7q31.31', 'hs|Xp11.4'], 'DESCRIPTION': [nan, nan, nan, 'Homo sapiens cadherin-like and PC-esterase domain containing 1 (CPED1), transcript variant 2, mRNA [NM_001105533]', 'BCL6 corepressor [Source:HGNC Symbol;Acc:HGNC:20893] [ENST00000378463]'], 'GO_ID': [nan, nan, nan, 'GO:0005783(endoplasmic reticulum)', 'GO:0000122(negative regulation of transcription from RNA polymerase II promoter)|GO:0000415(negative regulation of histone H3-K36 methylation)|GO:0003714(transcription corepressor activity)|GO:0004842(ubiquitin-protein ligase activity)|GO:0005515(protein binding)|GO:0005634(nucleus)|GO:0006351(transcription, DNA-dependent)|GO:0007507(heart development)|GO:0008134(transcription factor binding)|GO:0030502(negative regulation of bone mineralization)|GO:0031072(heat shock protein binding)|GO:0031519(PcG protein complex)|GO:0035518(histone H2A monoubiquitination)|GO:0042476(odontogenesis)|GO:0042826(histone deacetylase binding)|GO:0044212(transcription regulatory region DNA binding)|GO:0045892(negative regulation of transcription, DNA-dependent)|GO:0051572(negative regulation of histone H3-K4 methylation)|GO:0060021(palate development)|GO:0065001(specification of axis polarity)|GO:0070171(negative regulation of tooth mineralization)'], 'SEQUENCE': [nan, nan, 'AATACATGTTTTGGTAAACACTCGGTCAGAGCACCCTCTTTCTGTGGAATCAGACTGGCA', 'GCTTATCTCACCTAATACAGGGACTATGCAACCAAGAAACTGGAAATAAAAACAAAGATA', 'CATCAAAGCTACGAGAGATCCTACACACCCAGATTTAAAAAATAATAAAAACTTAAGGGC'], 'SPOT_ID': ['GE_BrightCorner', 'DarkCorner', 'A_21_P0014386', 'A_33_P3396872', 'A_33_P3267760']}\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": "7671a9a7",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "bad0d998",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:48:22.126668Z",
     "iopub.status.busy": "2025-03-25T03:48:22.126544Z",
     "iopub.status.idle": "2025-03-25T03:48:22.500078Z",
     "shell.execute_reply": "2025-03-25T03:48:22.499699Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping dataframe preview:\n",
      "{'ID': ['A_33_P3396872', 'A_33_P3267760', 'A_32_P194264', 'A_23_P153745', 'A_21_P0014180'], 'Gene': ['CPED1', 'BCOR', 'CHAC2', 'IFI30', 'GPR146']}\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "First 20 gene symbols after mapping:\n",
      "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A1CF-2', 'A1CF-3', 'A2M', 'A2M-1',\n",
      "       'A2M-AS1', 'A2ML1', 'A2MP1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AA06',\n",
      "       'AAAS', 'AAAS-1', 'AACS', 'AACS-2', 'AACS-3', 'AACSP1'],\n",
      "      dtype='object', name='Gene')\n",
      "Gene data shape after mapping: (29222, 72)\n"
     ]
    }
   ],
   "source": [
    "# 1. Determine which columns in gene_annotation contain gene identifiers and gene symbols\n",
    "# Based on the preview, the column 'ID' appears to match the gene identifiers in gene_expression data\n",
    "# The column 'GENE_SYMBOL' contains the gene symbols\n",
    "\n",
    "# 2. Extract the gene mapping using the get_gene_mapping function from the library\n",
    "gene_mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')\n",
    "\n",
    "# Examine the mapping dataframe\n",
    "print(\"Gene mapping dataframe preview:\")\n",
    "print(preview_df(gene_mapping_df))\n",
    "\n",
    "# 3. Apply the gene mapping to convert probe-level measurements to gene-level expression\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping_df)\n",
    "\n",
    "# Print the first 20 gene symbols after mapping to verify the process\n",
    "print(\"First 20 gene symbols after mapping:\")\n",
    "print(gene_data.index[:20])\n",
    "\n",
    "# Print the shape of the gene data after mapping\n",
    "print(f\"Gene data shape after mapping: {gene_data.shape}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3ec6db3f",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "11be82cf",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:48:22.501513Z",
     "iopub.status.busy": "2025-03-25T03:48:22.501401Z",
     "iopub.status.idle": "2025-03-25T03:48:23.475623Z",
     "shell.execute_reply": "2025-03-25T03:48:23.475215Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data shape: (20778, 72)\n",
      "First few normalized gene symbols: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2M-AS1', 'A2ML1', 'A2MP1', 'A3GALT2', 'A4GALT', 'A4GNT']\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Red_Hair/gene_data/GSE207744.csv\n",
      "No Red_Hair trait data available for cohort GSE207744. Cannot link clinical and genetic data.\n",
      "Abnormality detected in the cohort: GSE207744. Preprocessing failed.\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the obtained 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",
    "print(f\"First few normalized gene symbols: {list(normalized_gene_data.index[:10])}\")\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",
    "# Check if trait data is available by reading the JSON metadata\n",
    "import json\n",
    "with open(json_path, \"r\") as file:\n",
    "    metadata = json.load(file)\n",
    "    \n",
    "is_trait_available = False\n",
    "if cohort in metadata:\n",
    "    is_trait_available = metadata[cohort].get(\"is_trait_available\", False)\n",
    "\n",
    "# Only proceed with clinical data processing if trait is available\n",
    "if is_trait_available:\n",
    "    # Load the clinical features from the saved file\n",
    "    clinical_file_path = out_clinical_data_file\n",
    "    if os.path.exists(clinical_file_path):\n",
    "        clinical_features = pd.read_csv(clinical_file_path)\n",
    "        print(f\"Clinical features loaded from {clinical_file_path}\")\n",
    "        print(f\"Clinical features shape: {clinical_features.shape}\")\n",
    "    \n",
    "    # 2. Link the clinical and genetic data\n",
    "    linked_data = geo_link_clinical_genetic_data(clinical_features.T, normalized_gene_data)\n",
    "    print(f\"Linked data shape: {linked_data.shape}\")\n",
    "    print(f\"First few columns: {list(linked_data.columns[:5])}\")\n",
    "    \n",
    "    # 3. Handle missing values in the linked data\n",
    "    trait_column = linked_data.columns[0]  # First column should be the trait\n",
    "    print(f\"Using trait column: {trait_column}\")\n",
    "    \n",
    "    linked_data_processed = handle_missing_values(linked_data, trait_column)\n",
    "    print(f\"Shape after handling missing values: {linked_data_processed.shape}\")\n",
    "    \n",
    "    # 4. Determine whether the trait and demographic features are severely biased\n",
    "    is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data_processed, trait_column)\n",
    "    \n",
    "    # 5. Conduct quality check and save the 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_trait_biased, \n",
    "        df=unbiased_linked_data,\n",
    "        note=\"Dataset contains gene expression data but was processed and found unsuitable for Red_Hair analysis.\"\n",
    "    )\n",
    "    \n",
    "    # 6. Save the data if it's usable\n",
    "    if is_usable:\n",
    "        # Create directory if it doesn't exist\n",
    "        os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "        # Save the data\n",
    "        unbiased_linked_data.to_csv(out_data_file)\n",
    "        print(f\"Linked data saved to {out_data_file}\")\n",
    "    else:\n",
    "        print(f\"Data quality check failed. The dataset is not suitable for association studies.\")\n",
    "else:\n",
    "    print(f\"No Red_Hair trait data available for cohort {cohort}. Cannot link clinical and genetic data.\")\n",
    "    # Create empty DataFrame with appropriate structure for validation\n",
    "    empty_df = pd.DataFrame(columns=[trait])\n",
    "    \n",
    "    # Mark as unusable in final validation - using False for is_biased instead of None\n",
    "    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=False,  # Using False instead of None to satisfy function requirements\n",
    "        df=empty_df,\n",
    "        note=\"No Red_Hair trait information available in this cohort.\"\n",
    "    )"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}