File size: 38,779 Bytes
6bc7e45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "43c2f837",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:22:30.324399Z",
     "iopub.status.busy": "2025-03-25T06:22:30.324287Z",
     "iopub.status.idle": "2025-03-25T06:22:30.481690Z",
     "shell.execute_reply": "2025-03-25T06:22:30.481357Z"
    }
   },
   "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 = \"Adrenocortical_Cancer\"\n",
    "cohort = \"GSE90713\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Adrenocortical_Cancer\"\n",
    "in_cohort_dir = \"../../input/GEO/Adrenocortical_Cancer/GSE90713\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Adrenocortical_Cancer/GSE90713.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Adrenocortical_Cancer/gene_data/GSE90713.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Adrenocortical_Cancer/clinical_data/GSE90713.csv\"\n",
    "json_path = \"../../output/preprocess/Adrenocortical_Cancer/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2e0ebc68",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "aa74cd86",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:22:30.483079Z",
     "iopub.status.busy": "2025-03-25T06:22:30.482935Z",
     "iopub.status.idle": "2025-03-25T06:22:30.646133Z",
     "shell.execute_reply": "2025-03-25T06:22:30.645709Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Expression data from human metastatic adrenocortical carcinoma\"\n",
      "!Series_summary\t\"CXCR4 expression by metastatic adrenocortical carcinoma is heterogeneous among patients and among lesions\"\n",
      "!Series_summary\t\"We used microarrays for 57 ACC metastases from 42 patients to evaluate gene expression in different lesions from same patients and over time, focusing on CXCR4 expression and other genes correlating with CXCR4 expression\"\n",
      "!Series_overall_design\t\"57 ACC metastases from 42 patients were used for RNA extraction and hybridization on Affymetrix microarrays. We sought to obtain data on CXCR4 expression by ACC metastases. Multiple lesion samples were aquired for 9 of the patients, labeled a thru i. Single samples were aquired from the other subjects.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['tissue: adrenocortical carcinoma', 'tissue: normal adrenal'], 1: ['study: 426', 'study: 920'], 2: ['condition: tumor', 'condition: normal'], 3: ['acc_num: 1', 'acc_num: 6', 'acc_num: 7', 'acc_num: 8', 'acc_num: 9', 'acc_num: 11', 'acc_num: 13', 'acc_num: 14', 'acc_num: 15', 'acc_num: 16', 'acc_num: 17', 'acc_num: 20', 'acc_num: 22', 'acc_num: 25', 'acc_num: 26', 'acc_num: 27', 'acc_num: 28', 'acc_num: 29', 'acc_num: 30', 'acc_num: 31', 'acc_num: 32', 'acc_num: 33', 'acc_num: 34', 'acc_num: 35', 'acc_num: 36', 'acc_num: 37', 'acc_num: 38', 'acc_num: 39', 'acc_num: 41', 'acc_num: NA1'], 4: ['patient: a', 'patient: b', 'patient: c', 'patient: d', 'patient: A_16', 'patient: A_17', 'patient: A_20', 'patient: A_22', 'patient: A_26', 'patient: A_27', 'patient: A_29', 'patient: e', 'patient: A_31', 'patient: A_32', 'patient: A_33', 'patient: A_34', 'patient: f', 'patient: A_38', 'patient: A_39', 'patient: A_41', 'patient: g', 'patient: A_9', 'patient: A_NA1', 'patient: A_NA18', 'patient: A_NA19', 'patient: A_NA2', 'patient: A_NA4', 'patient: B_1', 'patient: B_10', 'patient: B_11_1']}\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": "3eef9334",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "19eaa325",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:22:30.647649Z",
     "iopub.status.busy": "2025-03-25T06:22:30.647540Z",
     "iopub.status.idle": "2025-03-25T06:22:30.667672Z",
     "shell.execute_reply": "2025-03-25T06:22:30.667400Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical Data Preview:\n",
      "{'GSM2411058': [1.0], 'GSM2411059': [1.0], 'GSM2411060': [1.0], 'GSM2411061': [1.0], 'GSM2411062': [1.0], 'GSM2411063': [1.0], 'GSM2411064': [1.0], 'GSM2411065': [1.0], 'GSM2411066': [1.0], 'GSM2411067': [1.0], 'GSM2411068': [1.0], 'GSM2411069': [1.0], 'GSM2411070': [1.0], 'GSM2411071': [1.0], 'GSM2411072': [1.0], 'GSM2411073': [1.0], 'GSM2411074': [1.0], 'GSM2411075': [1.0], 'GSM2411076': [1.0], 'GSM2411077': [1.0], 'GSM2411078': [1.0], 'GSM2411079': [1.0], 'GSM2411080': [1.0], 'GSM2411081': [1.0], 'GSM2411082': [1.0], 'GSM2411083': [1.0], 'GSM2411084': [1.0], 'GSM2411085': [1.0], 'GSM2411086': [1.0], 'GSM2411087': [0.0], 'GSM2411088': [0.0], 'GSM2411089': [0.0], 'GSM2411090': [0.0], 'GSM2411091': [0.0], 'GSM2411092': [1.0], 'GSM2411093': [1.0], 'GSM2411094': [1.0], 'GSM2411095': [1.0], 'GSM2411096': [1.0], 'GSM2411097': [1.0], 'GSM2411098': [1.0], 'GSM2411099': [1.0], 'GSM2411100': [1.0], 'GSM2411101': [1.0], 'GSM2411102': [1.0], 'GSM2411103': [1.0], 'GSM2411104': [1.0], 'GSM2411105': [1.0], 'GSM2411106': [1.0], 'GSM2411107': [1.0], 'GSM2411108': [1.0], 'GSM2411109': [1.0], 'GSM2411110': [1.0], 'GSM2411111': [1.0], 'GSM2411112': [1.0], 'GSM2411113': [1.0], 'GSM2411114': [1.0], 'GSM2411115': [1.0], 'GSM2411116': [1.0], 'GSM2411117': [1.0], 'GSM2411118': [1.0], 'GSM2411119': [1.0], 'GSM2411120': [1.0]}\n",
      "Clinical data saved to ../../output/preprocess/Adrenocortical_Cancer/clinical_data/GSE90713.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Determine gene expression data availability\n",
    "# Based on the background information, this dataset contains microarray data from ACC metastases\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Trait data: condition (tumor vs normal)\n",
    "trait_row = 2  # From the sample characteristics dictionary key 2: ['condition: tumor', 'condition: normal']\n",
    "\n",
    "# Function to convert trait values\n",
    "def convert_trait(value):\n",
    "    if isinstance(value, str):\n",
    "        value = value.strip().lower()\n",
    "        if \"tumor\" in value:\n",
    "            return 1\n",
    "        elif \"normal\" in value:\n",
    "            return 0\n",
    "    return None\n",
    "\n",
    "# 2.2 Age data: Not available in the sample characteristics\n",
    "age_row = None\n",
    "\n",
    "def convert_age(value):\n",
    "    return None  # Not used but defined for completeness\n",
    "\n",
    "# 2.3 Gender data: Not available in the sample characteristics\n",
    "gender_row = None\n",
    "\n",
    "def convert_gender(value):\n",
    "    return None  # Not used but defined for completeness\n",
    "\n",
    "# 3. Save metadata\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",
    "    # Extract clinical features\n",
    "    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 clinical data\n",
    "    print(\"Clinical Data Preview:\")\n",
    "    print(preview_df(clinical_df))\n",
    "    \n",
    "    # Save the clinical data to CSV\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    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": "8afbd72f",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "e6a0ca4a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:22:30.668780Z",
     "iopub.status.busy": "2025-03-25T06:22:30.668680Z",
     "iopub.status.idle": "2025-03-25T06:22:30.947385Z",
     "shell.execute_reply": "2025-03-25T06:22:30.947011Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "First 20 gene/probe identifiers:\n",
      "Index(['11715100_at', '11715101_s_at', '11715102_x_at', '11715103_x_at',\n",
      "       '11715104_s_at', '11715105_at', '11715106_x_at', '11715107_s_at',\n",
      "       '11715108_x_at', '11715109_at', '11715110_at', '11715111_s_at',\n",
      "       '11715112_at', '11715113_x_at', '11715114_x_at', '11715115_s_at',\n",
      "       '11715116_s_at', '11715117_x_at', '11715118_s_at', '11715119_s_at'],\n",
      "      dtype='object', name='ID')\n"
     ]
    }
   ],
   "source": [
    "# 1. First get the file paths again to access the matrix file\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 from the matrix_file\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(\"First 20 gene/probe identifiers:\")\n",
    "print(gene_data.index[:20])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "48cac1ad",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "72b9f945",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:22:30.948751Z",
     "iopub.status.busy": "2025-03-25T06:22:30.948631Z",
     "iopub.status.idle": "2025-03-25T06:22:30.950484Z",
     "shell.execute_reply": "2025-03-25T06:22:30.950205Z"
    }
   },
   "outputs": [],
   "source": [
    "# The gene identifiers in the data are in the format '11715100_at', '11715101_s_at', etc.\n",
    "# These appear to be Affymetrix probe IDs, not human gene symbols.\n",
    "# Affymetrix probe IDs need to be mapped to standard gene symbols.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a271b1a3",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "9ad89107",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:22:30.951672Z",
     "iopub.status.busy": "2025-03-25T06:22:30.951574Z",
     "iopub.status.idle": "2025-03-25T06:22:39.853742Z",
     "shell.execute_reply": "2025-03-25T06:22:39.853255Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['11715100_at', '11715101_s_at', '11715102_x_at', '11715103_x_at', '11715104_s_at'], 'GeneChip Array': ['Human Genome PrimeView Array', 'Human Genome PrimeView Array', 'Human Genome PrimeView Array', 'Human Genome PrimeView Array', 'Human Genome PrimeView Array'], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['30-Mar-16', '30-Mar-16', '30-Mar-16', '30-Mar-16', '30-Mar-16'], 'Sequence Type': ['Consensus sequence', 'Consensus sequence', 'Consensus sequence', 'Consensus sequence', 'Consensus sequence'], 'Sequence Source': ['Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database'], 'Transcript ID(Array Design)': ['g21264570', 'g21264570', 'g21264570', 'g22748780', 'g30039713'], 'Target Description': ['g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g22748780 /TID=g22748780 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g22748780 /REP_ORG=Homo sapiens', 'g30039713 /TID=g30039713 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g30039713 /REP_ORG=Homo sapiens'], 'GB_ACC': [nan, nan, nan, nan, nan], 'GI': [21264570.0, 21264570.0, 21264570.0, 22748780.0, 30039713.0], 'Representative Public ID': ['g21264570', 'g21264570', 'g21264570', 'g22748780', 'g30039713'], 'Archival UniGene Cluster': ['---', '---', '---', '---', '---'], 'UniGene ID': ['Hs.247813', 'Hs.247813', 'Hs.247813', 'Hs.465643', 'Hs.352515'], 'Genome Version': ['February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)'], 'Alignments': ['chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr19:4639529-5145579 (+) // 48.53 // p13.3', 'chr17:72920369-72929640 (+) // 100.0 // q25.1'], 'Gene Title': ['histone cluster 1, H3g', 'histone cluster 1, H3g', 'histone cluster 1, H3g', 'tumor necrosis factor, alpha-induced protein 8-like 1', 'otopetrin 2'], 'Gene Symbol': ['HIST1H3G', 'HIST1H3G', 'HIST1H3G', 'TNFAIP8L1', 'OTOP2'], 'Chromosomal Location': ['chr6p22.2', 'chr6p22.2', 'chr6p22.2', 'chr19p13.3', 'chr17q25.1'], 'Unigene Cluster Type': ['full length', 'full length', 'full length', 'full length', 'full length'], 'Ensembl': ['ENSG00000273983 /// OTTHUMG00000014436', 'ENSG00000273983 /// OTTHUMG00000014436', 'ENSG00000273983 /// OTTHUMG00000014436', 'ENSG00000185361 /// OTTHUMG00000182013', 'ENSG00000183034 /// OTTHUMG00000179215'], 'Entrez Gene': ['8355', '8355', '8355', '126282', '92736'], 'SwissProt': ['P68431', 'P68431', 'P68431', 'Q8WVP5', 'Q7RTS6'], 'EC': ['---', '---', '---', '---', '---'], 'OMIM': ['602815', '602815', '602815', '615869', '607827'], 'RefSeq Protein ID': ['NP_003525', 'NP_003525', 'NP_003525', 'NP_001161414 /// NP_689575 /// XP_005259544 /// XP_011525982', 'NP_835454 /// XP_011523781'], 'RefSeq Transcript ID': ['NM_003534', 'NM_003534', 'NM_003534', 'NM_001167942 /// NM_152362 /// XM_005259487 /// XM_011527680', 'NM_178160 /// XM_011525479'], 'Gene Ontology Biological Process': ['0000183 // chromatin silencing at rDNA // traceable author statement /// 0002230 // positive regulation of defense response to virus by host // inferred from mutant phenotype /// 0006325 // chromatin organization // traceable author statement /// 0006334 // nucleosome assembly // inferred from direct assay /// 0006334 // nucleosome assembly // inferred from mutant phenotype /// 0006335 // DNA replication-dependent nucleosome assembly // inferred from direct assay /// 0007264 // small GTPase mediated signal transduction // traceable author statement /// 0007596 // blood coagulation // traceable author statement /// 0010467 // gene expression // traceable author statement /// 0031047 // gene silencing by RNA // traceable author statement /// 0032776 // DNA methylation on cytosine // traceable author statement /// 0040029 // regulation of gene expression, epigenetic // traceable author statement /// 0044267 // cellular protein metabolic process // traceable author statement /// 0045814 // negative regulation of gene expression, epigenetic // traceable author statement /// 0051290 // protein heterotetramerization // inferred from direct assay /// 0060968 // regulation of gene silencing // inferred from direct assay /// 0098792 // xenophagy // inferred from mutant phenotype', '0000183 // chromatin silencing at rDNA // traceable author statement /// 0002230 // positive regulation of defense response to virus by host // inferred from mutant phenotype /// 0006325 // chromatin organization // traceable author statement /// 0006334 // nucleosome assembly // inferred from direct assay /// 0006334 // nucleosome assembly // inferred from mutant phenotype /// 0006335 // DNA replication-dependent nucleosome assembly // inferred from direct assay /// 0007264 // small GTPase mediated signal transduction // traceable author statement /// 0007596 // blood coagulation // traceable author statement /// 0010467 // gene expression // traceable author statement /// 0031047 // gene silencing by RNA // traceable author statement /// 0032776 // DNA methylation on cytosine // traceable author statement /// 0040029 // regulation of gene expression, epigenetic // traceable author statement /// 0044267 // cellular protein metabolic process // traceable author statement /// 0045814 // negative regulation of gene expression, epigenetic // traceable author statement /// 0051290 // protein heterotetramerization // inferred from direct assay /// 0060968 // regulation of gene silencing // inferred from direct assay /// 0098792 // xenophagy // inferred from mutant phenotype', '0000183 // chromatin silencing at rDNA // traceable author statement /// 0002230 // positive regulation of defense response to virus by host // inferred from mutant phenotype /// 0006325 // chromatin organization // traceable author statement /// 0006334 // nucleosome assembly // inferred from direct assay /// 0006334 // nucleosome assembly // inferred from mutant phenotype /// 0006335 // DNA replication-dependent nucleosome assembly // inferred from direct assay /// 0007264 // small GTPase mediated signal transduction // traceable author statement /// 0007596 // blood coagulation // traceable author statement /// 0010467 // gene expression // traceable author statement /// 0031047 // gene silencing by RNA // traceable author statement /// 0032776 // DNA methylation on cytosine // traceable author statement /// 0040029 // regulation of gene expression, epigenetic // traceable author statement /// 0044267 // cellular protein metabolic process // traceable author statement /// 0045814 // negative regulation of gene expression, epigenetic // traceable author statement /// 0051290 // protein heterotetramerization // inferred from direct assay /// 0060968 // regulation of gene silencing // inferred from direct assay /// 0098792 // xenophagy // inferred from mutant phenotype', '0032007 // negative regulation of TOR signaling // not recorded /// 0032007 // negative regulation of TOR signaling // inferred from sequence or structural similarity', '---'], 'Gene Ontology Cellular Component': ['0000228 // nuclear chromosome // inferred from direct assay /// 0000786 // nucleosome // inferred from direct assay /// 0000788 // nuclear nucleosome // inferred from direct assay /// 0005576 // extracellular region // traceable author statement /// 0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // traceable author statement /// 0005694 // chromosome // inferred from electronic annotation /// 0016020 // membrane // inferred from direct assay /// 0043234 // protein complex // inferred from direct assay /// 0070062 // extracellular exosome // inferred from direct assay', '0000228 // nuclear chromosome // inferred from direct assay /// 0000786 // nucleosome // inferred from direct assay /// 0000788 // nuclear nucleosome // inferred from direct assay /// 0005576 // extracellular region // traceable author statement /// 0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // traceable author statement /// 0005694 // chromosome // inferred from electronic annotation /// 0016020 // membrane // inferred from direct assay /// 0043234 // protein complex // inferred from direct assay /// 0070062 // extracellular exosome // inferred from direct assay', '0000228 // nuclear chromosome // inferred from direct assay /// 0000786 // nucleosome // inferred from direct assay /// 0000788 // nuclear nucleosome // inferred from direct assay /// 0005576 // extracellular region // traceable author statement /// 0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // traceable author statement /// 0005694 // chromosome // inferred from electronic annotation /// 0016020 // membrane // inferred from direct assay /// 0043234 // protein complex // inferred from direct assay /// 0070062 // extracellular exosome // inferred from direct assay', '0005737 // cytoplasm // not recorded /// 0005737 // cytoplasm // inferred from sequence or structural similarity', '0016020 // membrane // inferred from electronic annotation /// 0016021 // integral component of membrane // inferred from electronic annotation'], 'Gene Ontology Molecular Function': ['0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0042393 // histone binding // inferred from physical interaction /// 0046982 // protein heterodimerization activity // inferred from electronic annotation', '0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0042393 // histone binding // inferred from physical interaction /// 0046982 // protein heterodimerization activity // inferred from electronic annotation', '0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0042393 // histone binding // inferred from physical interaction /// 0046982 // protein heterodimerization activity // inferred from electronic annotation', '0005515 // protein binding // inferred from physical interaction', '---'], 'Pathway': ['---', '---', '---', '---', '---'], 'InterPro': ['IPR007125 // Histone H2A/H2B/H3 // 9.3E-34 /// IPR007125 // Histone H2A/H2B/H3 // 1.7E-37', 'IPR007125 // Histone H2A/H2B/H3 // 9.3E-34 /// IPR007125 // Histone H2A/H2B/H3 // 1.7E-37', 'IPR007125 // Histone H2A/H2B/H3 // 9.3E-34 /// IPR007125 // Histone H2A/H2B/H3 // 1.7E-37', 'IPR008477 // Protein of unknown function DUF758 // 8.4E-86 /// IPR008477 // Protein of unknown function DUF758 // 6.8E-90', 'IPR004878 // Otopetrin // 9.4E-43 /// IPR004878 // Otopetrin // 9.4E-43 /// IPR004878 // Otopetrin // 9.4E-43 /// IPR004878 // Otopetrin // 3.9E-18 /// IPR004878 // Otopetrin // 3.8E-20 /// IPR004878 // Otopetrin // 5.2E-16'], 'Annotation Description': ['This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 4 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 4 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 4 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 9 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 6 transcripts. // false // Matching Probes // A'], 'Annotation Transcript Cluster': ['ENST00000614378(11),NM_003534(11),OTTHUMT00000040099(11),uc003nhi.3', 'ENST00000614378(11),NM_003534(11),OTTHUMT00000040099(11),uc003nhi.3', 'ENST00000614378(11),NM_003534(11),OTTHUMT00000040099(11),uc003nhi.3', 'BC017672(11),BC044250(9),ENST00000327473(11),ENST00000536716(11),NM_001167942(11),NM_152362(11),OTTHUMT00000458662(11),uc002max.3,uc021une.1', 'ENST00000331427(11),ENST00000580223(11),NM_178160(11),OTTHUMT00000445306(11),uc010wrp.2,XM_011525479(11)'], 'Transcript Assignments': ['ENST00000614378 // ensembl_havana_transcript:known chromosome:GRCh38:6:26269405:26271815:-1 gene:ENSG00000273983 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // --- /// OTTHUMT00000040099 // otter:known chromosome:VEGA61:6:26269405:26271815:-1 gene:OTTHUMG00000014436 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc003nhi.3 // --- // ucsc_genes // 11 // ---', 'ENST00000614378 // ensembl_havana_transcript:known chromosome:GRCh38:6:26269405:26271815:-1 gene:ENSG00000273983 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// GENSCAN00000029819 // cdna:genscan chromosome:GRCh38:6:26270974:26271384:-1 transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // --- /// OTTHUMT00000040099 // otter:known chromosome:VEGA61:6:26269405:26271815:-1 gene:OTTHUMG00000014436 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc003nhi.3 // --- // ucsc_genes // 11 // ---', 'ENST00000614378 // ensembl_havana_transcript:known chromosome:GRCh38:6:26269405:26271815:-1 gene:ENSG00000273983 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // --- /// OTTHUMT00000040099 // otter:known chromosome:VEGA61:6:26269405:26271815:-1 gene:OTTHUMG00000014436 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc003nhi.3 // --- // ucsc_genes // 11 // ---', 'BC017672 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1, mRNA (cDNA clone MGC:17791 IMAGE:3885999), complete cds. // gb // 11 // --- /// BC044250 // accn=BC044250 class=mRNAlike lncRNA name=Human lncRNA ref=JounralRNA transcriptId=673 cpcScore=-0.1526100 cnci=-0.1238602 // noncode // 9 // --- /// BC044250 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1, mRNA (cDNA clone IMAGE:5784807). // gb // 9 // --- /// ENST00000327473 // ensembl_havana_transcript:known chromosome:GRCh38:19:4639518:4655568:1 gene:ENSG00000185361 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// ENST00000536716 // ensembl:known chromosome:GRCh38:19:4640017:4655568:1 gene:ENSG00000185361 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_001167942 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1 (TNFAIP8L1), transcript variant 1, mRNA. // refseq // 11 // --- /// NM_152362 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1 (TNFAIP8L1), transcript variant 2, mRNA. // refseq // 11 // --- /// NONHSAT060631 // Non-coding transcript identified by NONCODE: Exonic // noncode // 9 // --- /// OTTHUMT00000458662 // otter:known chromosome:VEGA61:19:4639518:4655568:1 gene:OTTHUMG00000182013 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc002max.3 // --- // ucsc_genes // 11 // --- /// uc021une.1 // --- // ucsc_genes // 11 // ---', 'ENST00000331427 // ensembl:known chromosome:GRCh38:17:74924275:74933911:1 gene:ENSG00000183034 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// ENST00000580223 // havana:known chromosome:GRCh38:17:74924603:74933912:1 gene:ENSG00000183034 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// GENSCAN00000013715 // cdna:genscan chromosome:GRCh38:17:74924633:74933545:1 transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_178160 // Homo sapiens otopetrin 2 (OTOP2), mRNA. // refseq // 11 // --- /// OTTHUMT00000445306 // otter:known chromosome:VEGA61:17:74924603:74933912:1 gene:OTTHUMG00000179215 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc010wrp.2 // --- // ucsc_genes // 11 // --- /// XM_011525479 // PREDICTED: Homo sapiens otopetrin 2 (OTOP2), transcript variant X1, mRNA. // refseq // 11 // ---'], 'Annotation Notes': ['---', '---', 'GENSCAN00000029819 // ensembl // 4 // Cross Hyb Matching Probes', '---', '---'], 'SPOT_ID': [nan, nan, nan, nan, nan]}\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": "62fc3fc1",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "32853f69",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:22:39.855113Z",
     "iopub.status.busy": "2025-03-25T06:22:39.854987Z",
     "iopub.status.idle": "2025-03-25T06:22:40.134002Z",
     "shell.execute_reply": "2025-03-25T06:22:40.133619Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data after mapping:\n",
      "Shape: (19963, 63)\n",
      "First 5 genes:\n",
      "Index(['A1BG', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2'], dtype='object', name='Gene')\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the key columns in the gene annotation dataframe\n",
    "# 'ID' contains the Affymetrix probe IDs (like '11715100_at')\n",
    "# 'Gene Symbol' contains the gene symbols (like 'HIST1H3G')\n",
    "prob_col = 'ID'\n",
    "gene_col = 'Gene Symbol'\n",
    "\n",
    "# 2. Get the mapping dataframe using the function from the library\n",
    "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n",
    "\n",
    "# 3. Apply gene mapping to convert probe-level measurements to gene expression\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
    "\n",
    "# 4. Preview the result to verify\n",
    "print(\"Gene expression data after mapping:\")\n",
    "print(f\"Shape: {gene_data.shape}\")\n",
    "print(\"First 5 genes:\")\n",
    "print(gene_data.index[:5])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0941fc27",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "3adfebbb",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:22:40.135340Z",
     "iopub.status.busy": "2025-03-25T06:22:40.135220Z",
     "iopub.status.idle": "2025-03-25T06:22:52.131217Z",
     "shell.execute_reply": "2025-03-25T06:22:52.130736Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracted clinical data with shape: (1, 63)\n",
      "Clinical data preview:\n",
      "{'GSM2411058': [1.0], 'GSM2411059': [1.0], 'GSM2411060': [1.0], 'GSM2411061': [1.0], 'GSM2411062': [1.0], 'GSM2411063': [1.0], 'GSM2411064': [1.0], 'GSM2411065': [1.0], 'GSM2411066': [1.0], 'GSM2411067': [1.0], 'GSM2411068': [1.0], 'GSM2411069': [1.0], 'GSM2411070': [1.0], 'GSM2411071': [1.0], 'GSM2411072': [1.0], 'GSM2411073': [1.0], 'GSM2411074': [1.0], 'GSM2411075': [1.0], 'GSM2411076': [1.0], 'GSM2411077': [1.0], 'GSM2411078': [1.0], 'GSM2411079': [1.0], 'GSM2411080': [1.0], 'GSM2411081': [1.0], 'GSM2411082': [1.0], 'GSM2411083': [1.0], 'GSM2411084': [1.0], 'GSM2411085': [1.0], 'GSM2411086': [1.0], 'GSM2411087': [0.0], 'GSM2411088': [0.0], 'GSM2411089': [0.0], 'GSM2411090': [0.0], 'GSM2411091': [0.0], 'GSM2411092': [1.0], 'GSM2411093': [1.0], 'GSM2411094': [1.0], 'GSM2411095': [1.0], 'GSM2411096': [1.0], 'GSM2411097': [1.0], 'GSM2411098': [1.0], 'GSM2411099': [1.0], 'GSM2411100': [1.0], 'GSM2411101': [1.0], 'GSM2411102': [1.0], 'GSM2411103': [1.0], 'GSM2411104': [1.0], 'GSM2411105': [1.0], 'GSM2411106': [1.0], 'GSM2411107': [1.0], 'GSM2411108': [1.0], 'GSM2411109': [1.0], 'GSM2411110': [1.0], 'GSM2411111': [1.0], 'GSM2411112': [1.0], 'GSM2411113': [1.0], 'GSM2411114': [1.0], 'GSM2411115': [1.0], 'GSM2411116': [1.0], 'GSM2411117': [1.0], 'GSM2411118': [1.0], 'GSM2411119': [1.0], 'GSM2411120': [1.0]}\n",
      "Clinical data saved to ../../output/preprocess/Adrenocortical_Cancer/clinical_data/GSE90713.csv\n",
      "\n",
      "Checking gene mapping results...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to ../../output/preprocess/Adrenocortical_Cancer/gene_data/GSE90713.csv\n",
      "Linked data shape: (63, 19964)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "After handling missing values, linked data shape: (63, 19964)\n",
      "For the feature 'Adrenocortical_Cancer', the least common label is '0.0' with 5 occurrences. This represents 7.94% of the dataset.\n",
      "The distribution of the feature 'Adrenocortical_Cancer' in this dataset is fine.\n",
      "\n",
      "Is trait biased: False\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Adrenocortical_Cancer/GSE90713.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Clinical Data Extraction (which was skipped in Step 2)\n",
    "# Use the geo_select_clinical_features function to extract clinical features\n",
    "clinical_df = geo_select_clinical_features(\n",
    "    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\"Extracted clinical data with shape: {clinical_df.shape}\")\n",
    "print(\"Clinical data preview:\")\n",
    "print(preview_df(clinical_df))\n",
    "\n",
    "# Save the clinical data\n",
    "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "clinical_df.to_csv(out_clinical_data_file)\n",
    "print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "\n",
    "# Deal with the gene mapping issue\n",
    "print(\"\\nChecking gene mapping results...\")\n",
    "is_gene_available = True\n",
    "\n",
    "# Since mapping with Entrez IDs didn't work in Step 6, \n",
    "# we'll try to use the original gene IDs directly\n",
    "if gene_data.shape[0] > 0:\n",
    "    # Save the gene data with original identifiers\n",
    "    os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "    gene_data.to_csv(out_gene_data_file)\n",
    "    print(f\"Gene expression data saved to {out_gene_data_file}\")\n",
    "else:\n",
    "    is_gene_available = False\n",
    "    print(\"No valid gene expression data found.\")\n",
    "\n",
    "# 3. Link the clinical and genetic data\n",
    "if is_gene_available:\n",
    "    linked_data = geo_link_clinical_genetic_data(clinical_df, gene_data)\n",
    "    print(f\"Linked data shape: {linked_data.shape}\")\n",
    "\n",
    "    # 4. Handle missing values in the linked data systematically\n",
    "    linked_data = handle_missing_values(linked_data, trait)\n",
    "    print(f\"After handling missing values, linked data shape: {linked_data.shape}\")\n",
    "\n",
    "    # 5. Determine whether the trait and demographic features are severely biased\n",
    "    is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "    print(f\"Is trait biased: {is_biased}\")\n",
    "else:\n",
    "    linked_data = pd.DataFrame()\n",
    "    is_biased = True\n",
    "    print(\"Cannot link data as gene expression data is not available.\")\n",
    "\n",
    "# 6. Conduct final quality validation and save cohort information\n",
    "note = \"SuperSeries with multiple disease conditions. Gene mapping approach using Entrez IDs was unsuccessful. The dataset includes obesity samples but may lack proper gene annotations.\"\n",
    "is_usable = validate_and_save_cohort_info(\n",
    "    is_final=True, \n",
    "    cohort=cohort, \n",
    "    info_path=json_path, \n",
    "    is_gene_available=is_gene_available, \n",
    "    is_trait_available=is_trait_available,\n",
    "    is_biased=is_biased,\n",
    "    df=linked_data,\n",
    "    note=note\n",
    ")\n",
    "\n",
    "# 7. If the linked data is usable, save it\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 trait-gene association studies.\")"
   ]
  }
 ],
 "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
}