File size: 26,540 Bytes
58f02a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "dfc0a692",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:20:53.806659Z",
     "iopub.status.busy": "2025-03-25T06:20:53.806538Z",
     "iopub.status.idle": "2025-03-25T06:20:53.968115Z",
     "shell.execute_reply": "2025-03-25T06:20:53.967769Z"
    }
   },
   "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 = \"GSE143383\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Adrenocortical_Cancer\"\n",
    "in_cohort_dir = \"../../input/GEO/Adrenocortical_Cancer/GSE143383\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Adrenocortical_Cancer/GSE143383.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Adrenocortical_Cancer/gene_data/GSE143383.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Adrenocortical_Cancer/clinical_data/GSE143383.csv\"\n",
    "json_path = \"../../output/preprocess/Adrenocortical_Cancer/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ec7d1466",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "4e3449e1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:20:53.969496Z",
     "iopub.status.busy": "2025-03-25T06:20:53.969362Z",
     "iopub.status.idle": "2025-03-25T06:20:54.123590Z",
     "shell.execute_reply": "2025-03-25T06:20:54.123264Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Gene expression analysis of metastatic adrenocortical tumors\"\n",
      "!Series_summary\t\"Background: Adrenocortical carcinoma (ACC) is a rare, often-aggressive neoplasm of the adrenal cortex, with a 14.5-month median overall survival. We asked whether tumors from patients with advanced or metastatic ACC would offer clues as to putative genes that might have critical roles in disease progression or in more aggressive disease biology.   Methods: We conducted comprehensive genomic and expression analyses of 43 ACCs.  Results: Copy number gains and losses matched that previously reported. We identified a median mutation rate of 3.38 per megabase (Mb), somewhat higher than in a previous study possibly related to the more advanced disease. The mutational signature was characterized by a predominance of C>T, C>A and T>C transitions. As in previously reports, only cancer genes TP53 (26%) and beta-catenin (CTNNB1, 14%) were mutated in more than 10% of samples. The TCGA-identified putative cancer genes MEN1 and PRKAR1A were found in low frequency – 4.7% and 2.3%, respectively. Most of the mutations were in genes not implicated in the etiology or maintenance of cancer. Specifically, amongst the 38 genes that were mutated in more than 9% of samples, only four were represented in Tier 1 of the 576 COSMIC Cancer Gene Census (CCGC). Thus, 82% of genes found to have mutations likely have no role in the etiology or biology of ACC; while the role of the other 18%, if any, remains to be proven. Finally, the transcript length for the 38 most frequently mutated genes in ACC is statistically longer than the average of all coding genes, raising the question of whether transcript length in part determined mutation probability.   Conclusions: We conclude that the mutational and expression profiles of advanced and metastatic tumors is very similar to those from newly diagnosed patients –with very little in the way of genomic aberration to explain it. Our data and that in the previous analyses finds the rate of mutations in ACCs lower than that in other cancers and suggests an epigenetic basis for the disease should be the focus of future studies.\"\n",
      "!Series_summary\t\"The Affymetrix PrimeView platform was used for the gene expression profiling.\"\n",
      "!Series_overall_design\t\"Tumor samples embedded in OCT were sectioned, stained with hematoxylin and eosin and reviewed by a pathologist. RNA was extracted from 50-100 mg of tumor using the Qiagen miRNeasy Kit and then used for cDNA array analyses.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['gender: M', 'gender: F', 'gender: unknown']}\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": "fd4ea54f",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "847ab34d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:20:54.124713Z",
     "iopub.status.busy": "2025-03-25T06:20:54.124610Z",
     "iopub.status.idle": "2025-03-25T06:20:54.144562Z",
     "shell.execute_reply": "2025-03-25T06:20:54.144253Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Error processing clinical data: [Errno 2] No such file or directory: '../../input/GEO/Adrenocortical_Cancer/GSE143383/clinical_data.csv'\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "import json\n",
    "from typing import Callable, Dict, Any, Optional\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# This dataset is about gene expression profiling using Affymetrix PrimeView platform\n",
    "# and the series summary mentions gene expression analysis\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "\n",
    "# 2.1 Data Availability\n",
    "# Looking at the sample characteristics dictionary, we only have gender information\n",
    "# There's no direct key for adrenocortical cancer trait or age\n",
    "trait_row = None\n",
    "age_row = None\n",
    "gender_row = 0  # Gender is available at key 0\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "# Since trait_row is None, we don't need to define convert_trait\n",
    "# But we'll create it with a placeholder function to maintain code structure\n",
    "def convert_trait(value):\n",
    "    return None\n",
    "\n",
    "# Since age_row is None, we don't need to define convert_age\n",
    "# But we'll create it with a placeholder function to maintain code structure\n",
    "def convert_age(value):\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    # Extract value after colon\n",
    "    if ':' in value:\n",
    "        gender = value.split(':', 1)[1].strip().lower()\n",
    "        \n",
    "        if gender == 'f':\n",
    "            return 0  # Female\n",
    "        elif gender == 'm':\n",
    "            return 1  # Male\n",
    "        else:\n",
    "            return None  # Unknown or other\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Trait data availability is determined by whether trait_row is None\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Save the initial filtering 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\n",
    "# Since trait_row is None, we'll skip this substep\n",
    "# However, we can still extract and save gender data if clinical_data is available\n",
    "try:\n",
    "    clinical_data = pd.read_csv(os.path.join(in_cohort_dir, \"clinical_data.csv\"))\n",
    "    \n",
    "    if gender_row is not None:\n",
    "        # We only have gender data\n",
    "        selected_clinical_df = geo_select_clinical_features(\n",
    "            clinical_df=clinical_data,\n",
    "            trait=trait,\n",
    "            trait_row=0,  # Using a placeholder since trait data isn't available\n",
    "            convert_trait=convert_trait,  # Using a placeholder function\n",
    "            gender_row=gender_row,\n",
    "            convert_gender=convert_gender\n",
    "        )\n",
    "        \n",
    "        # Preview the selected clinical data\n",
    "        preview = preview_df(selected_clinical_df)\n",
    "        print(\"Preview of selected clinical data:\")\n",
    "        print(preview)\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, index=False)\n",
    "        print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "    else:\n",
    "        print(\"No clinical features are available to extract.\")\n",
    "except Exception as e:\n",
    "    print(f\"Error processing clinical data: {e}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7b0d2cd0",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "ca3cf239",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:20:54.145674Z",
     "iopub.status.busy": "2025-03-25T06:20:54.145575Z",
     "iopub.status.idle": "2025-03-25T06:20:54.381975Z",
     "shell.execute_reply": "2025-03-25T06:20:54.381542Z"
    }
   },
   "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": "34416ff4",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "41f8d973",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:20:54.383477Z",
     "iopub.status.busy": "2025-03-25T06:20:54.383360Z",
     "iopub.status.idle": "2025-03-25T06:20:54.385238Z",
     "shell.execute_reply": "2025-03-25T06:20:54.384946Z"
    }
   },
   "outputs": [],
   "source": [
    "# Looking at the gene identifiers, these appear to be probe IDs from an Affymetrix microarray\n",
    "# (format like \"11715100_at\", \"11715101_s_at\")\n",
    "# These are not standard human gene symbols (like BRCA1, TP53) and will need to be mapped\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "98f22dff",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "acccd3c9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:20:54.386395Z",
     "iopub.status.busy": "2025-03-25T06:20:54.386291Z",
     "iopub.status.idle": "2025-03-25T06:20:59.879849Z",
     "shell.execute_reply": "2025-03-25T06:20:59.879481Z"
    }
   },
   "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': [40780.0, 40780.0, 40780.0, 40780.0, 40780.0], '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], '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': ['chr6p21.3', 'chr6p21.3', 'chr6p21.3', 'chr19p13.3', 'chr17q25.1'], 'Unigene Cluster Type': ['full length', 'full length', 'full length', 'full length', 'full length'], 'Ensembl': ['ENSG00000248541', 'ENSG00000248541', 'ENSG00000248541', 'ENSG00000185361', 'ENSG00000183034'], 'Entrez Gene': ['8355', '8355', '8355', '126282', '92736'], 'SwissProt': ['P68431', 'P68431', 'P68431', 'Q8WVP5', 'Q7RTS6'], 'OMIM': ['602815', '602815', '602815', '---', '607827'], 'RefSeq Protein ID': ['NP_003525', 'NP_003525', 'NP_003525', 'NP_001161414 /// NP_689575', 'NP_835454'], 'RefSeq Transcript ID': ['NM_003534', 'NM_003534', 'NM_003534', 'NM_001167942 /// NM_152362', 'NM_178160'], '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": "acd6f141",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "34d2c6a4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:20:59.881238Z",
     "iopub.status.busy": "2025-03-25T06:20:59.881116Z",
     "iopub.status.idle": "2025-03-25T06:21:00.175537Z",
     "shell.execute_reply": "2025-03-25T06:21:00.175171Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping dataframe shape: (49372, 2)\n",
      "First few rows of gene mapping:\n",
      "              ID       Gene\n",
      "0    11715100_at   HIST1H3G\n",
      "1  11715101_s_at   HIST1H3G\n",
      "2  11715102_x_at   HIST1H3G\n",
      "3  11715103_x_at  TNFAIP8L1\n",
      "4  11715104_s_at      OTOP2\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data shape after mapping: (19534, 63)\n",
      "First few gene symbols after mapping:\n",
      "Index(['A1BG', 'A1CF', 'A2LD1', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT', 'AAA1',\n",
      "       'AAAS', 'AACS'],\n",
      "      dtype='object', name='Gene')\n",
      "Preview of gene expression data:\n",
      "       GSM4258059  GSM4258060  GSM4258061  GSM4258062  GSM4258063\n",
      "Gene                                                             \n",
      "A1BG      4.86208     5.81829     5.69429     5.99362     6.01689\n",
      "A1CF      8.17809     7.65680     8.57597     9.20387     9.12301\n",
      "A2LD1     4.19459     4.34588     4.45649     3.94573     4.17089\n",
      "A2M      11.48740    10.66540    12.94520    11.30090    12.05390\n",
      "A2ML1     6.95604     6.78831     7.57040     7.79159     7.42280\n"
     ]
    }
   ],
   "source": [
    "# 1. Determine which columns contain probe IDs and gene symbols\n",
    "# From the annotation preview, we can see:\n",
    "# - 'ID' column contains the probe identifiers (e.g., '11715100_at')\n",
    "# - 'Gene Symbol' column contains the gene symbols (e.g., 'HIST1H3G')\n",
    "\n",
    "# 2. Create gene mapping DataFrame\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')\n",
    "print(f\"Gene mapping dataframe shape: {gene_mapping.shape}\")\n",
    "print(\"First few rows of gene mapping:\")\n",
    "print(gene_mapping.head())\n",
    "\n",
    "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n",
    "print(\"First few gene symbols after mapping:\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# Preview the first few rows and columns of the gene expression data\n",
    "print(\"Preview of gene expression data:\")\n",
    "first_genes = gene_data.index[:5]\n",
    "first_samples = gene_data.columns[:5]\n",
    "print(gene_data.loc[first_genes, first_samples])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "815dd5ce",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "45210003",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:21:00.177383Z",
     "iopub.status.busy": "2025-03-25T06:21:00.177267Z",
     "iopub.status.idle": "2025-03-25T06:21:00.914743Z",
     "shell.execute_reply": "2025-03-25T06:21:00.914425Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalizing gene symbols...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape after normalization: (19326, 63)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene expression data saved to ../../output/preprocess/Adrenocortical_Cancer/gene_data/GSE143383.csv\n",
      "Creating clinical data with available gender information...\n",
      "Clinical data shape: (63, 1)\n",
      "Clinical data saved to ../../output/preprocess/Adrenocortical_Cancer/clinical_data/GSE143383.csv\n",
      "This dataset doesn't contain trait information for Adrenocortical_Cancer.\n",
      "Abnormality detected in the cohort: GSE143383. Preprocessing failed.\n",
      "Dataset usability: False\n",
      "Dataset is not usable for trait-gene association studies due to missing trait information.\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "print(\"Normalizing gene symbols...\")\n",
    "try:\n",
    "    # Normalize gene symbols using the NCBI Gene database\n",
    "    normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "    print(f\"Gene data shape after normalization: {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 expression data saved to {out_gene_data_file}\")\n",
    "except Exception as e:\n",
    "    print(f\"Error during gene normalization: {e}\")\n",
    "    # If normalization fails, use the original gene data\n",
    "    print(\"Using original gene expression data...\")\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\"Original gene expression data saved to {out_gene_data_file}\")\n",
    "\n",
    "# 2. Create a basic clinical dataframe with gender information\n",
    "# Since we identified in Step 2 that only gender information is available\n",
    "print(\"Creating clinical data with available gender information...\")\n",
    "# First, get the sample identifiers from gene_data columns\n",
    "sample_ids = gene_data.columns.tolist()\n",
    "\n",
    "# Create a DataFrame for gender using the clinical data we collected earlier\n",
    "gender_row = 0  # As identified in Step 2\n",
    "gender_data = None\n",
    "\n",
    "try:\n",
    "    gender_data = get_feature_data(clinical_data, gender_row, 'Gender', convert_gender)\n",
    "    # Convert to a DataFrame with samples as rows\n",
    "    clinical_df = gender_data.T\n",
    "    print(f\"Clinical data shape: {clinical_df.shape}\")\n",
    "except Exception as e:\n",
    "    print(f\"Error extracting gender data: {e}\")\n",
    "    # Create an empty DataFrame if gender extraction fails\n",
    "    clinical_df = pd.DataFrame(index=sample_ids)\n",
    "    print(\"Created empty clinical dataframe.\")\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",
    "# 3. Since we don't have trait data (trait_row is None as per Step 2), we can't create a proper linked dataset\n",
    "# We'll mark the dataset as not usable for trait-gene association studies\n",
    "print(\"This dataset doesn't contain trait information for Adrenocortical_Cancer.\")\n",
    "\n",
    "# 4. Validate and save cohort information\n",
    "note = \"Dataset contains gene expression data from adrenocortical tumors, but lacks a proper control group \" \\\n",
    "       \"and trait classification. Only gender information is available as a clinical feature.\"\n",
    "\n",
    "is_usable = validate_and_save_cohort_info(\n",
    "    is_final=True, \n",
    "    cohort=cohort, \n",
    "    info_path=json_path, \n",
    "    is_gene_available=is_gene_available, \n",
    "    is_trait_available=is_trait_available,\n",
    "    is_biased=True,  # Set to True since we don't have a trait to analyze\n",
    "    df=clinical_df,  # Just pass the clinical data since we don't have a properly linked dataset\n",
    "    note=note\n",
    ")\n",
    "\n",
    "print(f\"Dataset usability: {is_usable}\")\n",
    "\n",
    "# 5. Since the dataset isn't usable for trait-gene association studies (no trait data),\n",
    "# we won't create or save a linked dataset\n",
    "if is_usable:\n",
    "    # This condition won't be met based on our assessment, but included for completeness\n",
    "    # We would need to transpose gene_data and concatenate with clinical_df\n",
    "    gene_data_t = gene_data.T\n",
    "    linked_data = pd.concat([clinical_df, gene_data_t], axis=1)\n",
    "    \n",
    "    # Handle missing values and check for bias\n",
    "    linked_data = handle_missing_values(linked_data, trait)\n",
    "    is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "    \n",
    "    # Save the linked data\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 due to missing trait information.\")"
   ]
  }
 ],
 "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
}