File size: 24,541 Bytes
f88156f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "dfc96712",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:15:10.705502Z",
     "iopub.status.busy": "2025-03-25T08:15:10.705088Z",
     "iopub.status.idle": "2025-03-25T08:15:10.869182Z",
     "shell.execute_reply": "2025-03-25T08:15:10.868841Z"
    }
   },
   "outputs": [],
   "source": [
    "import sys\n",
    "import os\n",
    "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
    "\n",
    "# Path Configuration\n",
    "from tools.preprocess import *\n",
    "\n",
    "# Processing context\n",
    "trait = \"Chronic_Fatigue_Syndrome\"\n",
    "cohort = \"GSE39684\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Chronic_Fatigue_Syndrome\"\n",
    "in_cohort_dir = \"../../input/GEO/Chronic_Fatigue_Syndrome/GSE39684\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Chronic_Fatigue_Syndrome/GSE39684.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Chronic_Fatigue_Syndrome/gene_data/GSE39684.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Chronic_Fatigue_Syndrome/clinical_data/GSE39684.csv\"\n",
    "json_path = \"../../output/preprocess/Chronic_Fatigue_Syndrome/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c9f4db94",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "57cfcae4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:15:10.870552Z",
     "iopub.status.busy": "2025-03-25T08:15:10.870417Z",
     "iopub.status.idle": "2025-03-25T08:15:10.886645Z",
     "shell.execute_reply": "2025-03-25T08:15:10.886360Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Comprehensive Investigation of Archival and Prospectively Collected Samples Reveals No Association of the XMRV Gammaretrovirus with Prostate Cancer\"\n",
      "!Series_summary\t\"XMRV, or xenotropic murine leukemia virus (MLV)-related virus, is a novel gammaretrovirus originally identified in studies that analyzed tissue from prostate cancer patients in 2006 and blood from patients with chronic fatigue syndrome (CFS) in 2009. However, a large number of subsequent studies failed to confirm a link between XMRV infection and CFS or prostate cancer. On the contrary, recent evidence indicates that XMRV is a contaminant originating from the recombination of two mouse endogenous retroviruses during passaging of a prostate tumor xenograft (CWR22) in mice, generating laboratory-derived cell lines that are XMRV-infected. To confirm or refute an association between XMRV and prostate cancer, we analyzed prostate cancer tissues and plasma from a prospectively collected cohort of 39 patients as well as archival RNA and prostate tissue from the original 2006 study. Despite comprehensive microarray, PCR, FISH, and serological testing, XMRV was not detected in any of the newly collected samples or in archival tissue, although archival RNA remained XMRV-positive. Notably, archival VP62 prostate tissue, from which the prototype XMRV strain is derived, tested negative for XMRV on re-analysis. Analysis of viral genomic and human mitochondrial sequences revealed that all previously characterized XMRV strains are identical and that the archival RNA had been contaminated by an XMRV-infected laboratory cell line. These findings reveal no association between XMRV and prostate cancer, and underscore the conclusion that XMRV is not a naturally acquired human infection.\"\n",
      "!Series_overall_design\t\"The Virochip microarray (version 5.0, Viro5AGL-60K platform) was used to screen RNA extracts from prostate tissue for XMRV to determine whether there is an association between the virus and prostate cancer.\"\n",
      "!Series_overall_design\t\"\"\n",
      "!Series_overall_design\t\"We used the ViroChip microarray to screen 22 archived prostate biopsies extracted in 2006 and 39 prospectively collected prostate biopsies for the virus, Xenotropic Murine Leukemia Virus-Related Virus (XMRV). We used custom-commercial microarrays from Agilent Technologies. The microarray platform GPL11662 consists of 62,976 probes [PMID 21779173], including all of the viral probes from the previous v2.0 (MV), v3.0 (V3) and v4.0 (V4) designs [PMIDs 18768820, 16983602, 16609730, 12429852, 9843981].\"\n",
      "!Series_overall_design\t\"\"\n",
      "!Series_overall_design\t\"For this study, 61 experimental ViroChip microarrays derived from prospectively collected RNA extracted prostate tissue and frozen RNA from archived prostate from a 2006 study were analyzed. Additionally, two XMRV-positive control microarrays from the cell line, 22Rv1, were hybridized, for a total of 63 ViroChip microarrays. Some RNA extracts were enriched for polyadenylated (polyA) transcripts prior to hybridization.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['cell line: 22Rv1', 'tissue: prostate biopsy'], 1: ['polya enrichment: yes', 'polya enrichment: no', 'cohort: 2006', 'cohort: 2012'], 2: [nan, 'polya enrichment: yes', 'polya enrichment: no']}\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": "70118de6",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "195be938",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:15:10.887600Z",
     "iopub.status.busy": "2025-03-25T08:15:10.887498Z",
     "iopub.status.idle": "2025-03-25T08:15:10.892409Z",
     "shell.execute_reply": "2025-03-25T08:15:10.892131Z"
    }
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "import json\n",
    "from typing import Callable, Optional, Dict, Any, List\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on background info, this is a microarray study looking for XMRV virus\n",
    "# It's using the Virochip microarray which contains viral probes, not gene expression data\n",
    "is_gene_available = False\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# From the sample characteristics, we need to identify which rows contain our variables\n",
    "\n",
    "# 2.1 Data Availability\n",
    "# Looking at the sample characteristics dictionary:\n",
    "# Row 0 has 'cell line: 22Rv1', 'tissue: prostate biopsy'\n",
    "# Row 1 has 'polya enrichment: yes', 'polya enrichment: no', 'cohort: 2006', 'cohort: 2012'\n",
    "# Row 2 has [nan, 'polya enrichment: yes', 'polya enrichment: no']\n",
    "\n",
    "# For the trait (Chronic Fatigue Syndrome):\n",
    "# The background information mentions studying chronic fatigue syndrome (CFS) but no specific row \n",
    "# in the sample characteristics identifies CFS status. The study is about analyzing XMRV virus \n",
    "# in prostate cancer tissue, not about CFS.\n",
    "trait_row = None  # No data available for Chronic Fatigue Syndrome\n",
    "\n",
    "# For age:\n",
    "# No age information is provided in the sample characteristics\n",
    "age_row = None\n",
    "\n",
    "# For gender:\n",
    "# Since this is a prostate cancer study, all subjects are male.\n",
    "# This is a constant feature (all subjects have the same value), so we consider it not available\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "# Define conversion functions for each variable\n",
    "def convert_trait(value: str) -> Optional[int]:\n",
    "    \"\"\"Convert trait values to binary format (0 or 1).\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    value_part = value.split(':')[-1].strip().lower() if ':' in value else value.lower().strip()\n",
    "    \n",
    "    # For Chronic Fatigue Syndrome, but since trait_row is None, this function won't be used\n",
    "    if 'cfs' in value_part or 'chronic fatigue' in value_part:\n",
    "        return 1\n",
    "    elif 'control' in value_part or 'healthy' in value_part:\n",
    "        return 0\n",
    "    return None\n",
    "\n",
    "def convert_age(value: str) -> Optional[float]:\n",
    "    \"\"\"Convert age values to continuous format.\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    value_part = value.split(':')[-1].strip() if ':' in value else value.strip()\n",
    "    \n",
    "    try:\n",
    "        return float(value_part)\n",
    "    except:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value: str) -> Optional[int]:\n",
    "    \"\"\"Convert gender values to binary format (0 for female, 1 for male).\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    value_part = value.split(':')[-1].strip().lower() if ':' in value else value.lower().strip()\n",
    "    \n",
    "    if 'female' in value_part or 'f' == value_part:\n",
    "        return 0\n",
    "    elif 'male' in value_part or 'm' == value_part:\n",
    "        return 1\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait availability based on trait_row\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Use the validate_and_save_cohort_info function to save information\n",
    "# Since this is not the final validation, we use is_final=False\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",
    "# Skip this step since trait_row is None, indicating clinical data is not available\n",
    "# If trait_row is not None, we would have done:\n",
    "# clinical_data = pd.read_csv(...)  # Load clinical data\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",
    "# preview = preview_df(clinical_df)\n",
    "# print(preview)\n",
    "# clinical_df.to_csv(out_clinical_data_file, index=False)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "89626c6b",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "b571d4ef",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:15:10.893285Z",
     "iopub.status.busy": "2025-03-25T08:15:10.893185Z",
     "iopub.status.idle": "2025-03-25T08:15:10.928503Z",
     "shell.execute_reply": "2025-03-25T08:15:10.928209Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found data marker at line 74\n",
      "Header line: \"ID_REF\"\t\"GSM977688\"\t\"GSM977689\"\t\"GSM977690\"\t\"GSM977691\"\t\"GSM977692\"\t\"GSM977693\"\t\"GSM977694\"\t\"GSM977695\"\t\"GSM977696\"\t\"GSM977697\"\t\"GSM977698\"\t\"GSM977699\"\t\"GSM977700\"\t\"GSM977701\"\t\"GSM977702\"\t\"GSM977703\"\t\"GSM977704\"\t\"GSM977705\"\t\"GSM977706\"\t\"GSM977707\"\t\"GSM977708\"\t\"GSM977709\"\t\"GSM977710\"\t\"GSM977711\"\t\"GSM977712\"\t\"GSM977713\"\t\"GSM977714\"\t\"GSM977715\"\t\"GSM977716\"\t\"GSM977717\"\t\"GSM977718\"\t\"GSM977719\"\t\"GSM977720\"\t\"GSM977721\"\t\"GSM977722\"\t\"GSM977723\"\t\"GSM977724\"\t\"GSM977725\"\t\"GSM977726\"\t\"GSM977727\"\t\"GSM977728\"\t\"GSM977729\"\t\"GSM977730\"\t\"GSM977731\"\t\"GSM977732\"\t\"GSM977733\"\t\"GSM977734\"\t\"GSM977735\"\t\"GSM977736\"\t\"GSM977737\"\t\"GSM977738\"\t\"GSM977739\"\t\"GSM977740\"\t\"GSM977741\"\t\"GSM977742\"\t\"GSM977743\"\t\"GSM977744\"\t\"GSM977745\"\t\"GSM977746\"\t\"GSM977747\"\t\"GSM977748\"\t\"GSM977749\"\t\"GSM977750\"\n",
      "First data line: \"10000-V3-70mer-rc\"\t0.0001741\t0.0103851\t0.0018561\t0.0001921\t0.0000011\t-0.0000001\t0.0173041\t0.0000021\t0.0000031\t0.0000141\t0.0000021\t0.0000001\t0.0105871\t0.0224131\t0.0129061\t-0.0000011\t0.0000041\t0.0000041\t0.0000191\t0.0000071\t0.0000051\t0.0000391\t-0.0000011\t0.0102451\t0.0000021\t0.0000001\t0.0000011\t-0.0000011\t0.0000051\t0.0000021\t0.0000401\t0.0207431\t0.0000041\t0.0000041\t0.0000321\t0.0000811\t0.0000111\t0.0000021\t0.0000611\t0.0099881\t-0.0000021\t-0.0000041\t0.0000891\t-0.0000031\t0.0000621\t0.0000001\t0.0000001\t0.0001101\t0.0000011\t0.0000001\t0.0000011\t0.0000011\t0.0000111\t0.0000031\t0.0000141\t0.0000101\t0.0000031\t0.0000261\t0.0000161\t0.0000111\t0.0000161\t0.0000171\t0.0000081\n",
      "Index(['10000-V3-70mer-rc', '10001-V3-70mer-rc', '10002-V3-70mer-rc',\n",
      "       '10003-V3-70mer-rc', '10004-V3-70mer-rc', '10005-V3-70mer-rc',\n",
      "       '10006-V3-70mer-rc', '10007-V3-70mer-rc', '10008-V3-70mer-rc',\n",
      "       '10009-V3-70mer-rc', '10010-V3-70mer-rc', '10011-V3-70mer-rc',\n",
      "       '10012-V3-70mer-rc', '10013-V3-70mer-rc', '10014-V3-70mer-rc',\n",
      "       '10015-V3-70mer-rc', '10016-V3-70mer-rc', '10017-V3-70mer-rc',\n",
      "       '10018-V3-70mer-rc', '10019-V3-70mer-rc'],\n",
      "      dtype='object', name='ID')\n"
     ]
    }
   ],
   "source": [
    "# 1. Get the file paths for the SOFT file and matrix file\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. First, let's examine the structure of the matrix file to understand its format\n",
    "import gzip\n",
    "\n",
    "# Peek at the first few lines of the file to understand its structure\n",
    "with gzip.open(matrix_file, 'rt') as file:\n",
    "    # Read first 100 lines to find the header structure\n",
    "    for i, line in enumerate(file):\n",
    "        if '!series_matrix_table_begin' in line:\n",
    "            print(f\"Found data marker at line {i}\")\n",
    "            # Read the next line which should be the header\n",
    "            header_line = next(file)\n",
    "            print(f\"Header line: {header_line.strip()}\")\n",
    "            # And the first data line\n",
    "            first_data_line = next(file)\n",
    "            print(f\"First data line: {first_data_line.strip()}\")\n",
    "            break\n",
    "        if i > 100:  # Limit search to first 100 lines\n",
    "            print(\"Matrix table marker not found in first 100 lines\")\n",
    "            break\n",
    "\n",
    "# 3. Now try to get the genetic data with better error handling\n",
    "try:\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    print(gene_data.index[:20])\n",
    "except KeyError as e:\n",
    "    print(f\"KeyError: {e}\")\n",
    "    \n",
    "    # Alternative approach: manually extract the data\n",
    "    print(\"\\nTrying alternative approach to read the gene data:\")\n",
    "    with gzip.open(matrix_file, 'rt') as file:\n",
    "        # Find the start of the data\n",
    "        for line in file:\n",
    "            if '!series_matrix_table_begin' in line:\n",
    "                break\n",
    "                \n",
    "        # Read the headers and data\n",
    "        import pandas as pd\n",
    "        df = pd.read_csv(file, sep='\\t', index_col=0)\n",
    "        print(f\"Column names: {df.columns[:5]}\")\n",
    "        print(f\"First 20 row IDs: {df.index[:20]}\")\n",
    "        gene_data = df\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "22c9a9af",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "e6939683",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:15:10.929502Z",
     "iopub.status.busy": "2025-03-25T08:15:10.929402Z",
     "iopub.status.idle": "2025-03-25T08:15:10.931115Z",
     "shell.execute_reply": "2025-03-25T08:15:10.930832Z"
    }
   },
   "outputs": [],
   "source": [
    "# Based on the gene identifiers examined from the provided data, \n",
    "# these appear to be custom microarray probe IDs (\"10000-V3-70mer-rc\", \"10001-V3-70mer-rc\", etc.)\n",
    "# rather than standard human gene symbols like BRCA1, TP53, etc.\n",
    "# These identifiers need to be mapped to human gene symbols for proper interpretation.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0f14346f",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "ecc4ed22",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:15:10.932032Z",
     "iopub.status.busy": "2025-03-25T08:15:10.931927Z",
     "iopub.status.idle": "2025-03-25T08:15:11.363595Z",
     "shell.execute_reply": "2025-03-25T08:15:11.363216Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['1-V3-70mer', '10-V3-70mer', '100-V3-70mer', '1000-V3-70mer', '10000-V3-70mer-rc'], 'SEQUENCE': ['ATTGCGGTCAATCAAGAGATTGGATTCAAAGACTTGGTCTAGAGCTCCATCTAATAAGCATACATTTTTA', 'AAACTAACAGATCACGACCCTATAGTAAAGAAGCCTAAATTATCTGAAAAAACTCTCCTTCACCTAGTAA', 'ATTAATTTCTCGTAAAAGTAGAAAATATATTCTAATTATTGCACGGTAAGGAAGTAGATCATAAAGAACA', 'GCATAAGTGCTCGCAATGATGTAGCTGCTTACGCTTGCTTACTCCGCCCTGAAACGCCTACCTTAAACGC', 'GCAAAAAGCGCGTTAACAGAAGCGAGAAGCGAGCTGATTGGTTAGTTTAAATAAGGCTTGGGGTTTTTCC'], 'ProbeName': ['1-V3-70mer', '10-V3-70mer', '100-V3-70mer', '1000-V3-70mer', '10000-V3-70mer-rc'], 'GeneName': ['V3-6063472_104-70mer-Parvo-like-virus-Parvoviridae-Parvovirus', 'V3-1113784_116-70mer-Muscovy-duck-parvovirus-Parvoviridae-Dependovirus', 'V3-297378_9-70mer-Vaccinia-virus-Poxviridae-Orthopoxvirus', 'V3-210706_327-70mer-Bovine-immunodeficiency-virus-Retroviridae-Lentivirus', 'V3-9628654_322_rc-70mer-Murine-type-C-retrovirus-Retroviridae-Gammaretrovirus']}\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": "e801032c",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "64e88bf5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T08:15:11.364937Z",
     "iopub.status.busy": "2025-03-25T08:15:11.364817Z",
     "iopub.status.idle": "2025-03-25T08:15:11.425384Z",
     "shell.execute_reply": "2025-03-25T08:15:11.425016Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene mapping preview:\n",
      "{'ID': ['1-V3-70mer', '10-V3-70mer', '100-V3-70mer', '1000-V3-70mer', '10000-V3-70mer-rc'], 'Gene': ['V3-6063472_104-70mer-Parvo-like-virus-Parvoviridae-Parvovirus', 'V3-1113784_116-70mer-Muscovy-duck-parvovirus-Parvoviridae-Dependovirus', 'V3-297378_9-70mer-Vaccinia-virus-Poxviridae-Orthopoxvirus', 'V3-210706_327-70mer-Bovine-immunodeficiency-virus-Retroviridae-Lentivirus', 'V3-9628654_322_rc-70mer-Murine-type-C-retrovirus-Retroviridae-Gammaretrovirus']}\n",
      "Mapped gene expression data preview (first 5 genes, first 5 samples):\n",
      "       GSM977688  GSM977689  GSM977690  GSM977691  GSM977692\n",
      "Gene                                                        \n",
      "A-      0.001185   0.005649   0.019542   0.028514   0.037372\n",
      "A118-   0.000032   0.000058   0.000126   0.000071   0.000055\n",
      "A59-    0.000014   0.000142   0.000321   0.000595   0.000247\n",
      "B-      0.000694   0.006662   0.011163   0.015327   0.007441\n",
      "B19-    0.000125   0.000253   0.002043   0.001312   0.000592\n"
     ]
    }
   ],
   "source": [
    "# Examining the gene identifiers and annotations\n",
    "# The gene expression data has identifiers like '10000-V3-70mer-rc'\n",
    "# The gene annotation has columns 'ID' (with values like '10000-V3-70mer-rc') and 'GeneName' with virus names\n",
    "\n",
    "# 1. Identify the columns for mapping\n",
    "# The column 'ID' in gene_annotation corresponds to probe identifiers in gene_data\n",
    "# The 'GeneName' column contains information about viral sequences, not human gene symbols\n",
    "\n",
    "# Looking at the data: these are viral microarray probes (Virochip) - not human gene expression\n",
    "# This is consistent with the study design which is about detecting XMRV virus, not human gene expression\n",
    "\n",
    "# 2. Create gene mapping dataframe - we'll use 'ID' and 'GeneName' columns\n",
    "# However, we should note that this dataset doesn't actually contain human gene expression data\n",
    "mapping_data = get_gene_mapping(gene_annotation, 'ID', 'GeneName')\n",
    "print(\"Gene mapping preview:\")\n",
    "print(preview_df(mapping_data))\n",
    "\n",
    "# 3. Apply gene mapping to convert probe-level measurements to gene expression\n",
    "# Note: This will map viral probes to viral genes, not human genes\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_data)\n",
    "print(\"Mapped gene expression data preview (first 5 genes, first 5 samples):\")\n",
    "gene_data_preview = gene_data.iloc[:5, :5]\n",
    "print(gene_data_preview)\n",
    "\n",
    "# Save the gene data for completeness, though this is viral sequence data, not human gene expression\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "gene_data.to_csv(out_gene_data_file)\n",
    "\n",
    "# Final validation\n",
    "# Since we've confirmed this isn't human gene expression data, we should update our records\n",
    "is_gene_available = False\n",
    "is_trait_available = trait_row is not None\n",
    "is_biased = True  # Dataset is biased/not suitable as it contains viral data not human gene expression\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=is_biased,  # Set to True to indicate dataset is not suitable\n",
    "    df=gene_data,  # Use actual dataframe to preserve sample size info\n",
    "    note=\"Dataset contains viral probe data (Virochip) for XMRV virus detection, not human gene expression data.\"\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
}