File size: 23,311 Bytes
82732bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "97565195",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:51:17.491567Z",
     "iopub.status.busy": "2025-03-25T03:51:17.491459Z",
     "iopub.status.idle": "2025-03-25T03:51:17.650548Z",
     "shell.execute_reply": "2025-03-25T03:51:17.650232Z"
    }
   },
   "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 = \"Rheumatoid_Arthritis\"\n",
    "cohort = \"GSE176440\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Rheumatoid_Arthritis\"\n",
    "in_cohort_dir = \"../../input/GEO/Rheumatoid_Arthritis/GSE176440\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Rheumatoid_Arthritis/GSE176440.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Rheumatoid_Arthritis/gene_data/GSE176440.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Rheumatoid_Arthritis/clinical_data/GSE176440.csv\"\n",
    "json_path = \"../../output/preprocess/Rheumatoid_Arthritis/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "475a35f1",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "1b633e93",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:51:17.651936Z",
     "iopub.status.busy": "2025-03-25T03:51:17.651796Z",
     "iopub.status.idle": "2025-03-25T03:51:17.854215Z",
     "shell.execute_reply": "2025-03-25T03:51:17.853873Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Gene expression profiles of CD4+ T cells before and after methotrexate treatment in rheumatoid arthritis patients [Microarray]\"\n",
      "!Series_summary\t\"To understand the molecular mechanisms by which methotraxate improves the disease activity in rheumatoid arthritis, CD4+ T cells were obtained before and 3month after methotrexate treatment.\"\n",
      "!Series_overall_design\t\"28 treatment naïve rheumatoid arthritis patients participated in the study. Blood samples were obtained before and 3 months after methotrexate treatment. CD4+ T cells were magnetically purified and subjected the DNA microarray analyses.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['individual: A29', 'individual: A30', 'individual: A34', 'individual: C14', 'individual: C16', 'individual: C19', 'individual: C43', 'individual: C49', 'individual: C71', 'individual: C80', 'individual: C85', 'individual: C87', 'individual: C91', 'individual: C92', 'individual: C93', 'individual: C95', 'individual: C96', 'individual: C100', 'individual: C102', 'individual: C103', 'individual: C107', 'individual: C108', 'individual: C109', 'individual: C111', 'individual: C115', 'individual: C116', 'individual: C117', 'individual: K20'], 1: ['disease state: rheumatoid arthritis patient'], 2: ['treatment: before methotrexate', 'treatment: 3 months after  methotrexate'], 3: ['cell type: CD4+ T cells']}\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": "3a650c57",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "e67176c5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:51:17.855444Z",
     "iopub.status.busy": "2025-03-25T03:51:17.855338Z",
     "iopub.status.idle": "2025-03-25T03:51:17.862265Z",
     "shell.execute_reply": "2025-03-25T03:51:17.862013Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of selected clinical data:\n",
      "{0: [nan], 1: [1.0], 2: [nan], 3: [nan]}\n",
      "Clinical data saved to ../../output/preprocess/Rheumatoid_Arthritis/clinical_data/GSE176440.csv\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "import json\n",
    "from typing import Optional, Callable, Dict, Any, List\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information, this dataset contains microarray data of CD4+ T cells\n",
    "# which implies gene expression data, not just miRNA or methylation\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Identify keys in the sample characteristics dictionary\n",
    "\n",
    "# Trait (Rheumatoid Arthritis)\n",
    "# From the sample characteristics, all samples are from RA patients (key 1)\n",
    "trait_row = 1  # \"disease state: rheumatoid arthritis patient\"\n",
    "\n",
    "# Treatment status (before/after methotrexate) at key 2 - this could be useful clinical information\n",
    "# but it's not age or gender\n",
    "\n",
    "# Age - Not available in the sample characteristics\n",
    "age_row = None\n",
    "\n",
    "# Gender - Not available in the sample characteristics\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "def convert_trait(value: str) -> int:\n",
    "    \"\"\"Convert trait value to binary (0 for control, 1 for RA).\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon if present\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # All samples are RA patients based on the data\n",
    "    if \"rheumatoid arthritis\" in value.lower():\n",
    "        return 1\n",
    "    return None  # Default case for unknown values\n",
    "\n",
    "def convert_age(value: str) -> Optional[float]:\n",
    "    \"\"\"Convert age value to continuous numeric.\"\"\"\n",
    "    # Not used since age data is not available\n",
    "    return None\n",
    "\n",
    "def convert_gender(value: str) -> Optional[int]:\n",
    "    \"\"\"Convert gender value to binary (0 for female, 1 for male).\"\"\"\n",
    "    # Not used since gender data is not available\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine if trait data is available\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\n",
    "# Since trait_row is not None, we need to extract clinical features\n",
    "if trait_row is not None:\n",
    "    # Load the clinical data (assuming it was saved from a previous step)\n",
    "    clinical_data = pd.DataFrame(\n",
    "        {0: ['individual: A29', 'individual: A30', 'individual: A34', 'individual: C14', 'individual: C16', 'individual: C19', 'individual: C43', 'individual: C49', 'individual: C71', 'individual: C80', 'individual: C85', 'individual: C87', 'individual: C91', 'individual: C92', 'individual: C93', 'individual: C95', 'individual: C96', 'individual: C100', 'individual: C102', 'individual: C103', 'individual: C107', 'individual: C108', 'individual: C109', 'individual: C111', 'individual: C115', 'individual: C116', 'individual: C117', 'individual: K20'], \n",
    "         1: ['disease state: rheumatoid arthritis patient'] * 28,\n",
    "         2: ['treatment: before methotrexate', 'treatment: 3 months after  methotrexate'] * 14,\n",
    "         3: ['cell type: CD4+ T cells'] * 28}\n",
    "    )\n",
    "    \n",
    "    # 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 selected clinical data\n",
    "    print(\"Preview of selected clinical data:\")\n",
    "    print(preview_df(selected_clinical_df))\n",
    "    \n",
    "    # Create directory if it doesn't exist\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    \n",
    "    # Save the selected 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": "35fea9d6",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "f227655b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:51:17.863298Z",
     "iopub.status.busy": "2025-03-25T03:51:17.863201Z",
     "iopub.status.idle": "2025-03-25T03:51:18.129568Z",
     "shell.execute_reply": "2025-03-25T03:51:18.129204Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056',\n",
      "       'A_23_P100074', 'A_23_P100092', 'A_23_P100103', 'A_23_P100111',\n",
      "       'A_23_P100127', 'A_23_P100133', 'A_23_P100141', 'A_23_P100156',\n",
      "       'A_23_P100177', 'A_23_P100189', 'A_23_P100196', 'A_23_P100203',\n",
      "       'A_23_P100220', 'A_23_P100240', 'A_23_P10025', 'A_23_P100263'],\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": "54573b79",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "b6cecc13",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:51:18.130841Z",
     "iopub.status.busy": "2025-03-25T03:51:18.130718Z",
     "iopub.status.idle": "2025-03-25T03:51:18.132626Z",
     "shell.execute_reply": "2025-03-25T03:51:18.132346Z"
    }
   },
   "outputs": [],
   "source": [
    "# The identifiers in the gene expression data (A_23_P100001, A_23_P100011, etc.) are Agilent microarray \n",
    "# probe identifiers, not human gene symbols.\n",
    "# These are probe IDs from an Agilent microarray platform and need to be mapped to human gene symbols.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5ccddc43",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "825dcac6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:51:18.133704Z",
     "iopub.status.busy": "2025-03-25T03:51:18.133605Z",
     "iopub.status.idle": "2025-03-25T03:51:22.153557Z",
     "shell.execute_reply": "2025-03-25T03:51:22.153192Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene annotation preview:\n",
      "{'ID': ['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074'], 'SPOT_ID': ['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074'], 'CONTROL_TYPE': ['FALSE', 'FALSE', 'FALSE', 'FALSE', 'FALSE'], 'REFSEQ': ['NM_207446', 'NM_005829', 'NM_014848', 'NM_194272', 'NM_020371'], 'GB_ACC': ['NM_207446', 'NM_005829', 'NM_014848', 'NM_194272', 'NM_020371'], 'GENE': [400451.0, 10239.0, 9899.0, 348093.0, 57099.0], 'GENE_SYMBOL': ['FAM174B', 'AP3S2', 'SV2B', 'RBPMS2', 'AVEN'], 'GENE_NAME': ['family with sequence similarity 174, member B', 'adaptor-related protein complex 3, sigma 2 subunit', 'synaptic vesicle glycoprotein 2B', 'RNA binding protein with multiple splicing 2', 'apoptosis, caspase activation inhibitor'], 'UNIGENE_ID': ['Hs.27373', 'Hs.632161', 'Hs.21754', 'Hs.436518', 'Hs.555966'], 'ENSEMBL_ID': ['ENST00000557398', nan, 'ENST00000557410', 'ENST00000300069', 'ENST00000306730'], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': ['ref|NM_207446|ens|ENST00000557398|ens|ENST00000553393|ens|ENST00000327355', 'ref|NM_005829|ref|NM_001199058|ref|NR_023361|ref|NR_037582', 'ref|NM_014848|ref|NM_001167580|ens|ENST00000557410|ens|ENST00000330276', 'ref|NM_194272|ens|ENST00000300069|gb|AK127873|gb|AK124123', 'ref|NM_020371|ens|ENST00000306730|gb|AF283508|gb|BC010488'], 'CHROMOSOMAL_LOCATION': ['chr15:93160848-93160789', 'chr15:90378743-90378684', 'chr15:91838329-91838388', 'chr15:65032375-65032316', 'chr15:34158739-34158680'], 'CYTOBAND': ['hs|15q26.1', 'hs|15q26.1', 'hs|15q26.1', 'hs|15q22.31', 'hs|15q14'], 'DESCRIPTION': ['Homo sapiens family with sequence similarity 174, member B (FAM174B), mRNA [NM_207446]', 'Homo sapiens adaptor-related protein complex 3, sigma 2 subunit (AP3S2), transcript variant 1, mRNA [NM_005829]', 'Homo sapiens synaptic vesicle glycoprotein 2B (SV2B), transcript variant 1, mRNA [NM_014848]', 'Homo sapiens RNA binding protein with multiple splicing 2 (RBPMS2), mRNA [NM_194272]', 'Homo sapiens apoptosis, caspase activation inhibitor (AVEN), mRNA [NM_020371]'], 'GO_ID': ['GO:0016020(membrane)|GO:0016021(integral to membrane)', 'GO:0005794(Golgi apparatus)|GO:0006886(intracellular protein transport)|GO:0008565(protein transporter activity)|GO:0016020(membrane)|GO:0016192(vesicle-mediated transport)|GO:0030117(membrane coat)|GO:0030659(cytoplasmic vesicle membrane)|GO:0031410(cytoplasmic vesicle)', 'GO:0001669(acrosomal vesicle)|GO:0006836(neurotransmitter transport)|GO:0016020(membrane)|GO:0016021(integral to membrane)|GO:0022857(transmembrane transporter activity)|GO:0030054(cell junction)|GO:0030672(synaptic vesicle membrane)|GO:0031410(cytoplasmic vesicle)|GO:0045202(synapse)', 'GO:0000166(nucleotide binding)|GO:0003676(nucleic acid binding)', 'GO:0005515(protein binding)|GO:0005622(intracellular)|GO:0005624(membrane fraction)|GO:0006915(apoptosis)|GO:0006916(anti-apoptosis)|GO:0012505(endomembrane system)|GO:0016020(membrane)'], 'SEQUENCE': ['ATCTCATGGAAAAGCTGGATTCCTCTGCCTTACGCAGAAACACCCGGGCTCCATCTGCCA', 'TCAAGTATTGGCCTGACATAGAGTCCTTAAGACAAGCAAAGACAAGCAAGGCAAGCACGT', 'ATGTCGGCTGTGGAGGGTTAAAGGGATGAGGCTTTCCTTTGTTTAGCAAATCTGTTCACA', 'CCCTGTCAGATAAGTTTAATGTTTAGTTTGAGGCATGAAGAAGAAAAGGGTTTCCATTCT', 'GACCAGCCAGTTTACAAGCATGTCTCAAGCTAGTGTGTTCCATTATGCTCACAGCAGTAA']}\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": "10880b81",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "89dc6c60",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:51:22.154852Z",
     "iopub.status.busy": "2025-03-25T03:51:22.154735Z",
     "iopub.status.idle": "2025-03-25T03:51:22.344821Z",
     "shell.execute_reply": "2025-03-25T03:51:22.344377Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of mapped gene expression data:\n",
      "(18488, 56)\n",
      "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT',\n",
      "       'AAAS', 'AACS'],\n",
      "      dtype='object', name='Gene')\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the columns in the gene annotation dataframe\n",
    "# From the preview, 'ID' in the gene_annotation corresponds to the probe identifiers in gene_data\n",
    "# 'GENE_SYMBOL' contains the human gene symbols we want to map to\n",
    "prob_col = 'ID'\n",
    "gene_col = 'GENE_SYMBOL'\n",
    "\n",
    "# 2. Extract the mapping between probe IDs and gene symbols\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)\n",
    "\n",
    "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n",
    "# This function handles the many-to-many relationship as specified\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "\n",
    "# Preview the result to verify the transformation\n",
    "print(\"Preview of mapped gene expression data:\")\n",
    "print(gene_data.shape)\n",
    "print(gene_data.index[:10])  # Print first 10 gene symbols\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fbb6eb5c",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "dd1bd097",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T03:51:22.346326Z",
     "iopub.status.busy": "2025-03-25T03:51:22.346207Z",
     "iopub.status.idle": "2025-03-25T03:51:23.003979Z",
     "shell.execute_reply": "2025-03-25T03:51:23.003614Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Normalized gene data saved to ../../output/preprocess/Rheumatoid_Arthritis/gene_data/GSE176440.csv\n",
      "Clinical data columns: ['0', '1', '2', '3']\n",
      "Linked data shape: (61, 18248)\n",
      "Error processing data: ['Rheumatoid_Arthritis']\n",
      "Abnormality detected in the cohort: GSE176440. Preprocessing failed.\n",
      "Dataset not usable for analysis. No linked data saved.\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "\n",
    "# Save the normalized gene data\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "normalized_gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
    "\n",
    "# 2. Load the clinical data that was saved in Step 2\n",
    "clinical_data_df = pd.read_csv(out_clinical_data_file)\n",
    "\n",
    "# Check the structure of the clinical data\n",
    "print(\"Clinical data columns:\", clinical_data_df.columns.tolist())\n",
    "\n",
    "# Since we don't have a proper trait column in the clinical data,\n",
    "# we need to add it before linking\n",
    "if trait not in clinical_data_df.columns:\n",
    "    # Create a proper clinical data structure with the trait column\n",
    "    # From previous steps, we see all values are 1.0 for RA patients\n",
    "    clinical_data_df[trait] = 1.0\n",
    "\n",
    "# Link the clinical and genetic data on sample IDs\n",
    "linked_data = geo_link_clinical_genetic_data(clinical_data_df, normalized_gene_data)\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "\n",
    "# 3. Handle missing values in the linked data\n",
    "try:\n",
    "    linked_data = handle_missing_values(linked_data, trait)\n",
    "    print(f\"After handling missing values, linked data shape: {linked_data.shape}\")\n",
    "    \n",
    "    # 4. Determine whether the trait and demographic features are severely biased\n",
    "    trait_biased, linked_data_filtered = judge_and_remove_biased_features(linked_data, trait)\n",
    "    \n",
    "    # 5. Conduct final quality validation and save relevant information\n",
    "    is_usable = validate_and_save_cohort_info(\n",
    "        is_final=True, \n",
    "        cohort=cohort, \n",
    "        info_path=json_path, \n",
    "        is_gene_available=True, \n",
    "        is_trait_available=True,\n",
    "        is_biased=trait_biased, \n",
    "        df=linked_data_filtered,\n",
    "        note=\"Dataset contains gene expression data from CD4+ T cells of rheumatoid arthritis patients before and after methotrexate treatment.\"\n",
    "    )\n",
    "    \n",
    "    # 6. If the linked data is usable, save it as a CSV file\n",
    "    if is_usable:\n",
    "        os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "        linked_data_filtered.to_csv(out_data_file)\n",
    "        print(f\"Linked data saved to {out_data_file}\")\n",
    "    else:\n",
    "        print(\"Dataset not usable for analysis. No linked data saved.\")\n",
    "        \n",
    "except Exception as e:\n",
    "    print(f\"Error processing data: {e}\")\n",
    "    # If there's an error, mark the dataset as not usable\n",
    "    is_usable = validate_and_save_cohort_info(\n",
    "        is_final=True, \n",
    "        cohort=cohort, \n",
    "        info_path=json_path, \n",
    "        is_gene_available=True, \n",
    "        is_trait_available=False,  # Marking as unavailable due to processing error\n",
    "        is_biased=True, \n",
    "        df=pd.DataFrame(),\n",
    "        note=f\"Error during data processing: {e}. Dataset contains only RA patients with constant trait value.\"\n",
    "    )\n",
    "    print(\"Dataset not usable for analysis. No linked data saved.\")"
   ]
  }
 ],
 "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
}