File size: 26,164 Bytes
92d2f89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "93f80fd4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:51:33.314127Z",
     "iopub.status.busy": "2025-03-25T06:51:33.313892Z",
     "iopub.status.idle": "2025-03-25T06:51:33.478424Z",
     "shell.execute_reply": "2025-03-25T06:51:33.478082Z"
    }
   },
   "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 = \"Autism_spectrum_disorder_(ASD)\"\n",
    "cohort = \"GSE113842\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Autism_spectrum_disorder_(ASD)\"\n",
    "in_cohort_dir = \"../../input/GEO/Autism_spectrum_disorder_(ASD)/GSE113842\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Autism_spectrum_disorder_(ASD)/GSE113842.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Autism_spectrum_disorder_(ASD)/gene_data/GSE113842.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Autism_spectrum_disorder_(ASD)/clinical_data/GSE113842.csv\"\n",
    "json_path = \"../../output/preprocess/Autism_spectrum_disorder_(ASD)/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "98cc760e",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "d8abbb2e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:51:33.479751Z",
     "iopub.status.busy": "2025-03-25T06:51:33.479612Z",
     "iopub.status.idle": "2025-03-25T06:51:33.637429Z",
     "shell.execute_reply": "2025-03-25T06:51:33.637085Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Autism-like phenotype and risk gene-RNA deadenylation by CPEB4 mis-splicing\"\n",
      "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n",
      "!Series_overall_design\t\"Refer to individual Series\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['genotype: WT', 'genotype: HD', 'genotype: CPEB4 GT/+', 'genotype: CPEB4 KO', 'genotype: CTRL', 'genotype: TgCPEB4{delta}4'], 1: ['condition: CPEB1 RIP', 'condition: none', 'condition: CPEB4 RIP', 'condition: IgG RIP', 'group: INPUT', 'group: WASH', 'group: ELUTED'], 2: [nan, 'replicate: 1', 'replicate: 2', 'replicate: 3'], 3: [nan, 'tissue: Cortex/Striatum'], 4: [nan, 'age: 6 week-old'], 5: [nan, 'rna fraction: total RNA', 'rna fraction: Enriched in short poly(A)-tail RNA', 'rna fraction: Enriched in long poly(A)-tail RNA']}\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": "a10dc099",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "19bacd37",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:51:33.638694Z",
     "iopub.status.busy": "2025-03-25T06:51:33.638585Z",
     "iopub.status.idle": "2025-03-25T06:51:33.647246Z",
     "shell.execute_reply": "2025-03-25T06:51:33.646923Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of selected clinical features:\n",
      "{0: [0.0, nan]}\n",
      "Clinical data saved to ../../output/preprocess/Autism_spectrum_disorder_(ASD)/clinical_data/GSE113842.csv\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "from typing import Optional, Callable\n",
    "\n",
    "# Define the sample characteristics dictionary from the previous output\n",
    "sample_characteristics_dict = {\n",
    "    0: ['group: CTRL', 'group: ASD'], \n",
    "    1: ['material: INPUT', 'material: WASH', 'material: ELUTED'], \n",
    "    2: ['age: 7', 'age: 9', 'age: 5', 'age: 13', 'age: 20/21', 'age: 11', 'age: 12', 'age: 21/23'], \n",
    "    3: ['postmorten interval (h): 16', 'postmorten interval (h): 12', 'postmorten interval (h): 21', 'postmorten interval (h): 3', 'postmorten interval (h): 28', 'postmorten interval (h): 11/19', 'postmorten interval (h): 27', 'postmorten interval (h): 22', 'postmorten interval (h): 14/18'], \n",
    "    4: ['hybridization batch: A', 'hybridization batch: B'], \n",
    "    5: ['tissue: Prefrontal Cortex BA9', 'tissue: Prefrontal Cortex BA8/9', 'tissue: Prefrontal Cortex BA8'], \n",
    "    6: ['rna fraction: total RNA', 'rna fraction: Enriched in short poly(A)-tail RNA', 'rna fraction: Enriched in long poly(A)-tail RNA']\n",
    "}\n",
    "\n",
    "# 1. Check Gene Expression Data Availability\n",
    "# Based on series title and summary, it appears to be RNA expression data\n",
    "is_gene_available = True  # RNA data from deadenylation by CPEB4 mis-splicing\n",
    "\n",
    "# 2.1 Data Availability\n",
    "trait_row = 0  # 'group: CTRL', 'group: ASD' indicates trait (ASD) status\n",
    "age_row = 2  # 'age: 7', 'age: 9', etc. indicates age information\n",
    "gender_row = None  # Gender information is not provided in the sample characteristics\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait data to binary format (0 for control, 1 for ASD).\"\"\"\n",
    "    if value is None or ':' not in value:\n",
    "        return None\n",
    "    \n",
    "    value = value.split(':', 1)[1].strip().upper()\n",
    "    if value == 'CTRL' or value == 'CONTROL':\n",
    "        return 0\n",
    "    elif value == 'ASD':\n",
    "        return 1\n",
    "    return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age data to continuous format.\"\"\"\n",
    "    if value is None or ':' not in value:\n",
    "        return None\n",
    "    \n",
    "    value = value.split(':', 1)[1].strip()\n",
    "    # Handle cases like \"20/21\" or \"21/23\" by averaging\n",
    "    if '/' in value:\n",
    "        ages = [int(age) for age in value.split('/')]\n",
    "        return sum(ages) / len(ages)\n",
    "    try:\n",
    "        return float(value)\n",
    "    except ValueError:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender data to binary format (0 for female, 1 for male).\"\"\"\n",
    "    # This function is defined but not used as gender data is not available\n",
    "    if value is None or ':' not in value:\n",
    "        return None\n",
    "    \n",
    "    value = value.split(':', 1)[1].strip().lower()\n",
    "    if value in ['female', 'f']:\n",
    "        return 0\n",
    "    elif value in ['male', 'm']:\n",
    "        return 1\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata (Initial Filtering)\n",
    "# Determine is_trait_available based on whether trait_row is None\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Validate and save cohort information\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. Clinical Feature Extraction (if trait_row is not None)\n",
    "if trait_row is not None:\n",
    "    # Create a DataFrame with sample characteristics in a row-wise format\n",
    "    data = []\n",
    "    for key, values in sample_characteristics_dict.items():\n",
    "        for value in values:\n",
    "            data.append([value])\n",
    "    clinical_data = pd.DataFrame(data)\n",
    "    \n",
    "    # Use geo_select_clinical_features to extract clinical features\n",
    "    selected_clinical_df = geo_select_clinical_features(\n",
    "        clinical_df=clinical_data,\n",
    "        trait=trait,\n",
    "        trait_row=trait_row,\n",
    "        convert_trait=convert_trait,\n",
    "        age_row=age_row,\n",
    "        convert_age=convert_age,\n",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender\n",
    "    )\n",
    "    \n",
    "    # Preview the dataframe\n",
    "    preview = preview_df(selected_clinical_df)\n",
    "    print(\"Preview of selected clinical features:\")\n",
    "    print(preview)\n",
    "    \n",
    "    # Ensure the directory exists\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    \n",
    "    # Save the clinical data to CSV\n",
    "    selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f7352292",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "62a6b707",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:51:33.648381Z",
     "iopub.status.busy": "2025-03-25T06:51:33.648275Z",
     "iopub.status.idle": "2025-03-25T06:51:33.866022Z",
     "shell.execute_reply": "2025-03-25T06:51:33.865655Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['1415670_PM_at', '1415671_PM_at', '1415672_PM_at', '1415673_PM_at',\n",
      "       '1415674_PM_a_at', '1415675_PM_at', '1415676_PM_a_at', '1415677_PM_at',\n",
      "       '1415678_PM_at', '1415679_PM_at', '1415680_PM_at', '1415681_PM_at',\n",
      "       '1415682_PM_at', '1415683_PM_at', '1415684_PM_at', '1415685_PM_at',\n",
      "       '1415686_PM_at', '1415687_PM_a_at', '1415688_PM_at', '1415689_PM_s_at'],\n",
      "      dtype='object', name='ID')\n"
     ]
    }
   ],
   "source": [
    "# 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.\n",
    "gene_data = get_genetic_data(matrix_file)\n",
    "\n",
    "# 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.\n",
    "print(gene_data.index[:20])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eec2ef4f",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "f47f99c4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:51:33.867285Z",
     "iopub.status.busy": "2025-03-25T06:51:33.867174Z",
     "iopub.status.idle": "2025-03-25T06:51:33.869135Z",
     "shell.execute_reply": "2025-03-25T06:51:33.868821Z"
    }
   },
   "outputs": [],
   "source": [
    "# These identifiers appear to be Affymetrix probeset IDs (format with \"_at\", \"_s_at\", \"_x_at\" suffix patterns)\n",
    "# rather than standard human gene symbols like BRCA1, TP53, etc.\n",
    "# These probesets would need to be mapped to gene symbols for biological interpretation.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d28ea07b",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "f5df1f1b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:51:33.870219Z",
     "iopub.status.busy": "2025-03-25T06:51:33.870119Z",
     "iopub.status.idle": "2025-03-25T06:51:41.351090Z",
     "shell.execute_reply": "2025-03-25T06:51:41.350657Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['1415670_PM_at', '1415671_PM_at', '1415672_PM_at', '1415673_PM_at', '1415674_PM_a_at'], 'GB_ACC': ['BC024686', 'NM_013477', 'NM_020585', 'NM_133900', 'NM_021789'], 'SPOT_ID': [nan, nan, nan, nan, nan], 'Species Scientific Name': ['Mus musculus', 'Mus musculus', 'Mus musculus', 'Mus musculus', 'Mus musculus'], 'Annotation Date': ['Aug 10, 2010', 'Aug 10, 2010', 'Aug 10, 2010', 'Aug 10, 2010', 'Aug 10, 2010'], 'Sequence Type': ['Consensus sequence', 'Consensus sequence', 'Consensus sequence', 'Consensus sequence', 'Consensus sequence'], 'Sequence Source': ['GenBank', 'GenBank', 'GenBank', 'GenBank', 'GenBank'], 'Target Description': ['gb:BC024686.1 /DB_XREF=gi:19354080 /FEA=FLmRNA /CNT=416 /TID=Mm.26422.1 /TIER=FL+Stack /STK=110 /UG=Mm.26422 /LL=54161 /UG_GENE=Copg1 /DEF=Mus musculus, coatomer protein complex, subunit gamma 1, clone MGC:30335 IMAGE:3992144, mRNA, complete cds. /PROD=coatomer protein complex, subunit gamma 1 /FL=gb:AF187079.1 gb:BC024686.1 gb:NM_017477.1 gb:BC024896.1', 'gb:NM_013477.1 /DB_XREF=gi:7304908 /GEN=Atp6v0d1 /FEA=FLmRNA /CNT=197 /TID=Mm.1081.1 /TIER=FL+Stack /STK=114 /UG=Mm.1081 /LL=11972 /DEF=Mus musculus ATPase, H+ transporting, lysosomal 38kDa, V0 subunit D isoform 1 (Atp6v0d1), mRNA. /PROD=ATPase, H+ transporting, lysosomal 38kDa, V0subunit D isoform 1 /FL=gb:U21549.1 gb:U13840.1 gb:BC011075.1 gb:NM_013477.1', 'gb:NM_020585.1 /DB_XREF=gi:10181207 /GEN=AB041568 /FEA=FLmRNA /CNT=213 /TID=Mm.17035.1 /TIER=FL+Stack /STK=102 /UG=Mm.17035 /LL=57437 /DEF=Mus musculus hypothetical protein, MNCb-1213 (AB041568), mRNA. /PROD=hypothetical protein, MNCb-1213 /FL=gb:BC016894.1 gb:NM_020585.1', 'gb:NM_133900.1 /DB_XREF=gi:19527115 /GEN=AI480570 /FEA=FLmRNA /CNT=139 /TID=Mm.10623.1 /TIER=FL+Stack /STK=96 /UG=Mm.10623 /LL=100678 /DEF=Mus musculus expressed sequence AI480570 (AI480570), mRNA. /PROD=expressed sequence AI480570 /FL=gb:BC002251.1 gb:NM_133900.1', 'gb:NM_021789.1 /DB_XREF=gi:11140824 /GEN=Sbdn /FEA=FLmRNA /CNT=163 /TID=Mm.29814.1 /TIER=FL+Stack /STK=95 /UG=Mm.29814 /LL=60409 /DEF=Mus musculus synbindin (Sbdn), mRNA. /PROD=synbindin /FL=gb:NM_021789.1 gb:AF233340.1'], 'Representative Public ID': ['BC024686', 'NM_013477', 'NM_020585', 'NM_133900', 'NM_021789'], 'Gene Title': ['coatomer protein complex, subunit gamma', 'ATPase, H+ transporting, lysosomal V0 subunit D1', 'golgi autoantigen, golgin subfamily a, 7', 'phosphoserine phosphatase', 'trafficking protein particle complex 4'], 'Gene Symbol': ['Copg', 'Atp6v0d1', 'Golga7', 'Psph', 'Trappc4'], 'Entrez Gene': ['54161', '11972', '57437', '100678', '60409'], 'RefSeq Transcript ID': ['NM_017477 /// NM_201244', 'NM_013477', 'NM_001042484 /// NM_020585', 'NM_133900', 'NM_021789'], 'Gene Ontology Biological Process': ['0006810 // transport // inferred from electronic annotation /// 0006886 // intracellular protein transport // inferred from electronic annotation /// 0015031 // protein transport // inferred from electronic annotation /// 0016192 // vesicle-mediated transport // inferred from electronic annotation', '0006810 // transport // inferred from electronic annotation /// 0006811 // ion transport // inferred from electronic annotation /// 0007420 // brain development // inferred from electronic annotation /// 0015986 // ATP synthesis coupled proton transport // inferred from electronic annotation /// 0015992 // proton transport // inferred from electronic annotation', '0006893 // Golgi to plasma membrane transport // not recorded', '0006564 // L-serine biosynthetic process // inferred from electronic annotation /// 0008152 // metabolic process // inferred from electronic annotation /// 0008652 // cellular amino acid biosynthetic process // inferred from electronic annotation /// 0009612 // response to mechanical stimulus // inferred from electronic annotation /// 0031667 // response to nutrient levels // inferred from electronic annotation /// 0033574 // response to testosterone stimulus // inferred from electronic annotation', '0006810 // transport // inferred from electronic annotation /// 0006888 // ER to Golgi vesicle-mediated transport // inferred from electronic annotation /// 0016192 // vesicle-mediated transport // traceable author statement /// 0016192 // vesicle-mediated transport // inferred from electronic annotation /// 0016358 // dendrite development // inferred from direct assay /// 0045212 // neurotransmitter receptor biosynthetic process // traceable author statement'], 'Gene Ontology Cellular Component': ['0000139 // Golgi membrane // inferred from electronic annotation /// 0005737 // cytoplasm // inferred from electronic annotation /// 0005794 // Golgi apparatus // inferred from electronic annotation /// 0005798 // Golgi-associated vesicle // inferred from electronic annotation /// 0016020 // membrane // inferred from electronic annotation /// 0030117 // membrane coat // inferred from electronic annotation /// 0030126 // COPI vesicle coat // inferred from electronic annotation /// 0030663 // COPI coated vesicle membrane // inferred from electronic annotation /// 0031410 // cytoplasmic vesicle // inferred from electronic annotation', '0005769 // early endosome // inferred from direct assay /// 0008021 // synaptic vesicle // not recorded /// 0008021 // synaptic vesicle // inferred from electronic annotation /// 0016020 // membrane // inferred from electronic annotation /// 0016324 // apical plasma membrane // not recorded /// 0016324 // apical plasma membrane // inferred from electronic annotation /// 0019717 // synaptosome // not recorded /// 0019717 // synaptosome // inferred from electronic annotation /// 0033177 // proton-transporting two-sector ATPase complex, proton-transporting domain // inferred from electronic annotation /// 0033179 // proton-transporting V-type ATPase, V0 domain // inferred from electronic annotation /// 0043234 // protein complex // not recorded /// 0043679 // axon terminus // not recorded /// 0043679 // axon terminus // inferred from electronic annotation', '0000139 // Golgi membrane // not recorded /// 0000139 // Golgi membrane // inferred from electronic annotation /// 0005794 // Golgi apparatus // inferred from electronic annotation /// 0016020 // membrane // inferred from electronic annotation', '0019717 // synaptosome // not recorded /// 0019717 // synaptosome // inferred from electronic annotation', '0005783 // endoplasmic reticulum // inferred from electronic annotation /// 0005794 // Golgi apparatus // inferred from electronic annotation /// 0005795 // Golgi stack // inferred from direct assay /// 0005801 // cis-Golgi network // inferred from electronic annotation /// 0005886 // plasma membrane // inferred from electronic annotation /// 0008021 // synaptic vesicle // inferred from direct assay /// 0016020 // membrane // inferred from electronic annotation /// 0030008 // TRAPP complex // inferred from direct assay /// 0030054 // cell junction // inferred from electronic annotation /// 0030425 // dendrite // inferred from direct assay /// 0045202 // synapse // inferred from direct assay /// 0045202 // synapse // inferred from electronic annotation /// 0045211 // postsynaptic membrane // inferred from electronic annotation'], 'Gene Ontology Molecular Function': ['0005198 // structural molecule activity // inferred from electronic annotation /// 0005488 // binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from electronic annotation', '0008553 // hydrogen-exporting ATPase activity, phosphorylative mechanism // inferred from direct assay /// 0015078 // hydrogen ion transmembrane transporter activity // inferred from electronic annotation /// 0032403 // protein complex binding // not recorded /// 0032403 // protein complex binding // inferred from electronic annotation', nan, '0003824 // catalytic activity // inferred from electronic annotation /// 0004647 // phosphoserine phosphatase activity // inferred from electronic annotation /// 0005515 // protein binding // inferred from electronic annotation /// 0016787 // hydrolase activity // inferred from electronic annotation /// 0016791 // phosphatase activity // inferred from electronic annotation', '0005515 // protein binding // inferred from physical interaction /// 0005515 // protein binding // inferred from electronic annotation']}\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": "ed43878a",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "a2744369",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:51:41.352417Z",
     "iopub.status.busy": "2025-03-25T06:51:41.352298Z",
     "iopub.status.idle": "2025-03-25T06:51:41.572042Z",
     "shell.execute_reply": "2025-03-25T06:51:41.571678Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data after mapping to gene symbols:\n",
      "            GSM3120892  GSM3120893  GSM3120894  GSM3120895  GSM3120896  \\\n",
      "Gene                                                                     \n",
      "A130033P14    4.039066    4.192930    4.128634    3.988778    3.336130   \n",
      "A430075N02    4.264285    4.319175    4.591880    4.228277    3.879057   \n",
      "A630043P06    3.667454    4.484825    4.563515    4.573879    3.933827   \n",
      "A730034C02   12.692358   11.214867    9.627281    8.557741   15.380640   \n",
      "A830091E24    3.606027    3.780010    4.225027    3.949768    3.420589   \n",
      "\n",
      "            GSM3120897  GSM3120898  GSM3120899  GSM3120964  GSM3120965  ...  \\\n",
      "Gene                                                                    ...   \n",
      "A130033P14    3.814148    4.979083    4.338055    4.626518    4.631608  ...   \n",
      "A430075N02    3.999499    4.272288    3.856207    4.751322    4.695923  ...   \n",
      "A630043P06    4.060068    4.100830    4.268562    6.168188    6.319480  ...   \n",
      "A730034C02   12.898844   10.628091   11.304317   19.737081   19.225753  ...   \n",
      "A830091E24    3.749105    3.702691    3.922714    7.779632    6.323384  ...   \n",
      "\n",
      "            GSM3121096  GSM3121097  GSM3121098  GSM3121099  GSM3121100  \\\n",
      "Gene                                                                     \n",
      "A130033P14    5.072450    4.603705    4.603528    4.934665    4.713400   \n",
      "A430075N02    5.162419    4.674936    4.596325    4.824838    4.605254   \n",
      "A630043P06    6.300151    6.366614    6.018211    6.077133    6.134430   \n",
      "A730034C02   19.154467   20.151631   19.415156   18.511080   20.518194   \n",
      "A830091E24    7.309921    7.182640    5.956179    7.284793    7.121327   \n",
      "\n",
      "            GSM3121101  GSM3121102  GSM3121103  GSM3121104  GSM3121105  \n",
      "Gene                                                                    \n",
      "A130033P14    4.574106    5.004884    4.785717    4.524453    4.823034  \n",
      "A430075N02    4.753700    5.095664    4.854732    4.816047    4.762050  \n",
      "A630043P06    6.025884    6.209419    6.137426    6.138736    6.081797  \n",
      "A730034C02   19.852528   18.760226   19.691923   19.047606   18.295848  \n",
      "A830091E24    5.895475    7.338838    7.184301    6.041828    7.085319  \n",
      "\n",
      "[5 rows x 44 columns]\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the columns in the annotation data that contain probe IDs and gene symbols\n",
    "# Looking at the gene_annotation preview, I can see:\n",
    "# - 'ID' column contains probe IDs (like '1415670_PM_at')\n",
    "# - 'Gene Symbol' column contains the corresponding gene symbols (like 'Copg')\n",
    "\n",
    "# 2. Extract these two columns from the gene annotation dataframe to create the mapping\n",
    "mapping_df = get_gene_mapping(gene_annotation, 'ID', 'Gene Symbol')\n",
    "\n",
    "# 3. Apply the gene mapping to convert probe-level measurements to gene expression\n",
    "# This function will split expression values for probes that map to multiple genes\n",
    "# and then sum values for each gene from all contributing probes\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
    "\n",
    "# Preview the first few rows of the mapped gene data\n",
    "print(\"Gene data after mapping to gene symbols:\")\n",
    "print(gene_data.head())"
   ]
  }
 ],
 "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
}