File size: 26,468 Bytes
736e4a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "62cd86d9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:56:50.668591Z",
     "iopub.status.busy": "2025-03-25T06:56:50.668184Z",
     "iopub.status.idle": "2025-03-25T06:56:50.831556Z",
     "shell.execute_reply": "2025-03-25T06:56:50.831223Z"
    }
   },
   "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 = \"Bladder_Cancer\"\n",
    "cohort = \"GSE185264\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Bladder_Cancer\"\n",
    "in_cohort_dir = \"../../input/GEO/Bladder_Cancer/GSE185264\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Bladder_Cancer/GSE185264.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Bladder_Cancer/gene_data/GSE185264.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Bladder_Cancer/clinical_data/GSE185264.csv\"\n",
    "json_path = \"../../output/preprocess/Bladder_Cancer/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "117d9a6b",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "02a8ea67",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:56:50.832933Z",
     "iopub.status.busy": "2025-03-25T06:56:50.832801Z",
     "iopub.status.idle": "2025-03-25T06:56:50.859069Z",
     "shell.execute_reply": "2025-03-25T06:56:50.858783Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Identification of a Novel Inflamed Tumor Microenvironment Signature as a Predictive Biomarker of Bacillus Calmette-Guérin Immunotherapy in Non–Muscle-Invasive Bladder Cancer\"\n",
      "!Series_summary\t\"Improved risk stratification and predictive biomarkers of treatment response are needed for non–muscle-invasive bladder cancer (NMIBC). Here we assessed the clinical utility of targeted RNA and DNA molecular profiling in NMIBC. We performed RNA-based profiling by NanoString nCounter on non–muscle-invasive bladder cancer (NMIBC) clinical specimens and found that a novel expression signature of an inflamed tumor microenvironment (TME), but not molecular subtyping, was associated with improved recurrence-free survival after bacillus Calmette-Guérin (BCG) immunotherapy. We further demonstrated that immune checkpoint gene expression was not associated with higher recurrence rates after BCG.\"\n",
      "!Series_overall_design\t\"Gene expression in NMIBC samples was profiled by NanoString nCounter, an RNA quantification platform, from two independent cohorts (n = 28, n = 50).\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['studyid.sampleid: NA', 'studyid.sampleid: P-0005606-T01-IM5', 'studyid.sampleid: P-0006902-T01-IM5', 'studyid.sampleid: P-0009371-T01-IM5', 'studyid.sampleid: P-0004941-T01-IM5', 'studyid.sampleid: P-0005087-T01-IM5', 'studyid.sampleid: P-0003261-T01-IM5', 'studyid.sampleid: P-0003878-T01-IM5', 'studyid.sampleid: P-0004757-T01-IM5', 'studyid.sampleid: P-0003438-T01-IM5', 'studyid.sampleid: P-0003823-T01-IM5', 'studyid.sampleid: P-0003352-T01-IM5', 'studyid.sampleid: P-0003690-T01-IM5', 'studyid.sampleid: P-0003433-T01-IM5', 'studyid.sampleid: P-0008240-T01-IM5', 'studyid.sampleid: P-0004424-T01-IM5', 'studyid.sampleid: P-0003408-T01-IM5', 'studyid.sampleid: P-0003238-T01-IM5', 'studyid.sampleid: P-0008867-T01-IM5', 'studyid.sampleid: P-0003257-T01-IM5', 'studyid.sampleid: P-0006645-T01-IM5', 'studyid.sampleid: P-0003817-T01-IM5', 'studyid.sampleid: P-0006142-T01-IM5', 'studyid.sampleid: P-0006291-T01-IM5', 'studyid.sampleid: P-0007966-T01-IM5', 'studyid.sampleid: P-0006194-T01-IM5', 'studyid.sampleid: P-0003403-T01-IM5', 'studyid.sampleid: P-0007285-T01-IM5', 'studyid.sampleid: P-0004224-T01-IM5', 'studyid.sampleid: P-0008834-T01-IM5'], 1: ['study: UNC', 'study: MSK'], 2: ['tissue: Bladder Cancer'], 3: ['hede: Early Basal-like (H3)', 'hede: Luminal CIS-like (H2)', 'hede: Luminal (H1)'], 4: ['mda: Basal', 'mda: TP53', 'mda: NA', 'mda: Luminal'], 5: ['lund: GenomicUnstable', 'lund: SCC-Like', 'lund: NA', 'lund: Infiltrated', 'lund: UrobasalA', 'lund: UrobasalB'], 6: ['immune: high', 'immune: low', 'immune: medium'], 7: ['Sex: F', 'Sex: M'], 8: ['Stage: Ta', 'Stage: T1', 'Stage: Ta/T1'], 9: ['grade: Low', 'grade: High', 'grade: .'], 10: ['cis: No', 'cis: Yes'], 11: ['tumor_no: NA', 'tumor_no: 1', 'tumor_no: 2'], 12: ['recurrence: NA', 'recurrence: No.Recurrence', 'recurrence: Recurrence'], 13: ['bcg.y.n: NA', 'bcg.y.n: Treated.BCG'], 14: ['bcg: NA', 'bcg: BCG', 'bcg: Observation', 'bcg: Cystectomy', 'bcg: MMC']}\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": "b75167d7",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "d2a5a4e0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:56:50.860076Z",
     "iopub.status.busy": "2025-03-25T06:56:50.859968Z",
     "iopub.status.idle": "2025-03-25T06:56:50.870375Z",
     "shell.execute_reply": "2025-03-25T06:56:50.870098Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical features preview:\n",
      "{0: [nan, 0.0], 1: [1.0, 1.0], 2: [nan, nan], 3: [nan, nan], 4: [nan, nan], 5: [nan, nan], 6: [nan, nan], 7: [nan, nan], 8: [nan, nan], 9: [nan, nan], 10: [nan, nan], 11: [nan, nan], 12: [nan, nan], 13: [nan, nan], 14: [nan, nan], 15: [nan, nan], 16: [nan, nan], 17: [nan, nan], 18: [nan, nan], 19: [nan, nan], 20: [nan, nan], 21: [nan, nan], 22: [nan, nan], 23: [nan, nan], 24: [nan, nan], 25: [nan, nan], 26: [nan, nan], 27: [nan, nan], 28: [nan, nan], 29: [nan, nan]}\n",
      "Clinical data saved to: ../../output/preprocess/Bladder_Cancer/clinical_data/GSE185264.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Determine gene expression data availability\n",
    "is_gene_available = True  # Based on the Series_summary and overall_design, this contains RNA-based profiling\n",
    "\n",
    "# 2.1 Determine data availability for trait, age, and gender\n",
    "# For trait (Bladder Cancer), we'll use bcg response as the trait since this is the focus of the study\n",
    "trait_row = 13  # bcg.y.n field\n",
    "# Age is not available in the data\n",
    "age_row = None\n",
    "# Gender is available\n",
    "gender_row = 7  # Sex field\n",
    "\n",
    "# 2.2 Define conversion functions for each variable\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert BCG treatment status to binary format.\"\"\"\n",
    "    if value is None or pd.isna(value) or 'NA' in value:\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    if 'Treated.BCG' in value:\n",
    "        return 1  # BCG treated\n",
    "    else:\n",
    "        return 0  # Not treated with BCG\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age to numeric value.\"\"\"\n",
    "    # Age is not available\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender to binary format: female=0, male=1.\"\"\"\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    if value == 'F':\n",
    "        return 0  # Female\n",
    "    elif value == 'M':\n",
    "        return 1  # Male\n",
    "    else:\n",
    "        return None  # Unknown or other\n",
    "\n",
    "# 3. Save metadata\n",
    "is_trait_available = trait_row is not None\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. Extract clinical features if trait data is available\n",
    "if trait_row is not None:\n",
    "    # Create the clinical data DataFrame correctly\n",
    "    sample_chars = {\n",
    "        0: ['studyid.sampleid: NA', 'studyid.sampleid: P-0005606-T01-IM5', 'studyid.sampleid: P-0006902-T01-IM5', 'studyid.sampleid: P-0009371-T01-IM5', 'studyid.sampleid: P-0004941-T01-IM5', 'studyid.sampleid: P-0005087-T01-IM5', 'studyid.sampleid: P-0003261-T01-IM5', 'studyid.sampleid: P-0003878-T01-IM5', 'studyid.sampleid: P-0004757-T01-IM5', 'studyid.sampleid: P-0003438-T01-IM5', 'studyid.sampleid: P-0003823-T01-IM5', 'studyid.sampleid: P-0003352-T01-IM5', 'studyid.sampleid: P-0003690-T01-IM5', 'studyid.sampleid: P-0003433-T01-IM5', 'studyid.sampleid: P-0008240-T01-IM5', 'studyid.sampleid: P-0004424-T01-IM5', 'studyid.sampleid: P-0003408-T01-IM5', 'studyid.sampleid: P-0003238-T01-IM5', 'studyid.sampleid: P-0008867-T01-IM5', 'studyid.sampleid: P-0003257-T01-IM5', 'studyid.sampleid: P-0006645-T01-IM5', 'studyid.sampleid: P-0003817-T01-IM5', 'studyid.sampleid: P-0006142-T01-IM5', 'studyid.sampleid: P-0006291-T01-IM5', 'studyid.sampleid: P-0007966-T01-IM5', 'studyid.sampleid: P-0006194-T01-IM5', 'studyid.sampleid: P-0003403-T01-IM5', 'studyid.sampleid: P-0007285-T01-IM5', 'studyid.sampleid: P-0004224-T01-IM5', 'studyid.sampleid: P-0008834-T01-IM5'],\n",
    "        1: ['study: UNC', 'study: MSK'], \n",
    "        2: ['tissue: Bladder Cancer'], \n",
    "        3: ['hede: Early Basal-like (H3)', 'hede: Luminal CIS-like (H2)', 'hede: Luminal (H1)'], \n",
    "        4: ['mda: Basal', 'mda: TP53', 'mda: NA', 'mda: Luminal'], \n",
    "        5: ['lund: GenomicUnstable', 'lund: SCC-Like', 'lund: NA', 'lund: Infiltrated', 'lund: UrobasalA', 'lund: UrobasalB'], \n",
    "        6: ['immune: high', 'immune: low', 'immune: medium'], \n",
    "        7: ['Sex: F', 'Sex: M'], \n",
    "        8: ['Stage: Ta', 'Stage: T1', 'Stage: Ta/T1'], \n",
    "        9: ['grade: Low', 'grade: High', 'grade: .'], \n",
    "        10: ['cis: No', 'cis: Yes'], \n",
    "        11: ['tumor_no: NA', 'tumor_no: 1', 'tumor_no: 2'], \n",
    "        12: ['recurrence: NA', 'recurrence: No.Recurrence', 'recurrence: Recurrence'], \n",
    "        13: ['bcg.y.n: NA', 'bcg.y.n: Treated.BCG'], \n",
    "        14: ['bcg: NA', 'bcg: BCG', 'bcg: Observation', 'bcg: Cystectomy', 'bcg: MMC']\n",
    "    }\n",
    "    \n",
    "    # Create a proper DataFrame from the sample characteristics\n",
    "    clinical_data = pd.DataFrame.from_dict(sample_chars, orient='index')\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 extracted clinical features\n",
    "    preview = preview_df(selected_clinical_df)\n",
    "    print(\"Clinical features preview:\")\n",
    "    print(preview)\n",
    "    \n",
    "    # Save clinical data to CSV\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    selected_clinical_df.to_csv(out_clinical_data_file)\n",
    "    print(f\"Clinical data saved to: {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c0b3edaf",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "25e105be",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:56:50.871347Z",
     "iopub.status.busy": "2025-03-25T06:56:50.871247Z",
     "iopub.status.idle": "2025-03-25T06:56:50.884346Z",
     "shell.execute_reply": "2025-03-25T06:56:50.884069Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['53BP1', 'ABCD3', 'ACTB', 'ADIRF', 'ADPRHL2', 'AFTPH', 'AHNAK2', 'AKT',\n",
      "       'ALDH1L1', 'ALOX5', 'ALOX5AP', 'ANLN', 'APEX1', 'APH1B', 'APOBEC3A',\n",
      "       'APOBEC3B', 'APOBEC3C', 'APOBEC3D', 'APOBEC3F', 'APOBEC3G'],\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": "79d77abc",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "abf8c1bd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:56:50.885295Z",
     "iopub.status.busy": "2025-03-25T06:56:50.885195Z",
     "iopub.status.idle": "2025-03-25T06:56:50.886915Z",
     "shell.execute_reply": "2025-03-25T06:56:50.886652Z"
    }
   },
   "outputs": [],
   "source": [
    "# Based on the provided gene identifiers, I can analyze whether they are standard human gene symbols or other identifiers\n",
    "\n",
    "# Looking at the sample gene identifiers:\n",
    "# - 53BP1, ACTB, AKT: These are standard human gene symbols\n",
    "# - APOBEC3A, APOBEC3B, etc.: These are proper human gene symbols for the APOBEC3 family\n",
    "# - ALDH1L1, ALOX5, etc.: These are standard human gene nomenclature\n",
    "\n",
    "# All of these appear to be standard HGNC (HUGO Gene Nomenclature Committee) gene symbols\n",
    "# They follow the conventional naming patterns for human genes\n",
    "# No mapping appears to be needed as these are already human gene symbols\n",
    "\n",
    "requires_gene_mapping = False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f251872",
   "metadata": {},
   "source": [
    "### Step 5: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "7b991f1e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T06:56:50.887861Z",
     "iopub.status.busy": "2025-03-25T06:56:50.887765Z",
     "iopub.status.idle": "2025-03-25T06:56:51.065788Z",
     "shell.execute_reply": "2025-03-25T06:56:51.065473Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Original gene count: 446\n",
      "Sample of gene symbols before normalization:\n",
      "Index(['53BP1', 'ABCD3', 'ACTB', 'ADIRF', 'ADPRHL2', 'AFTPH', 'AHNAK2', 'AKT',\n",
      "       'ALDH1L1', 'ALOX5', 'ALOX5AP', 'ANLN', 'APEX1', 'APH1B', 'APOBEC3A',\n",
      "       'APOBEC3B', 'APOBEC3C', 'APOBEC3D', 'APOBEC3F', 'APOBEC3G'],\n",
      "      dtype='object', name='ID')\n",
      "Normalized gene count: 432\n",
      "Gene data saved to ../../output/preprocess/Bladder_Cancer/gene_data/GSE185264.csv\n",
      "Found 15 GSM IDs in clinical data\n",
      "First 5 GSM IDs: ['!Sample_characteristics_ch1', '!Sample_characteristics_ch1', '!Sample_characteristics_ch1', '!Sample_characteristics_ch1', '!Sample_characteristics_ch1']\n",
      "Number of common samples between clinical and gene data: 78\n",
      "Clinical data saved to ../../output/preprocess/Bladder_Cancer/clinical_data/GSE185264.csv\n",
      "Linked data shape after proper ID matching: (78, 434)\n",
      "Percentage of missing values in trait: 53.85%\n",
      "Linked data shape after handling missing values: (36, 434)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Quartiles for 'Bladder_Cancer':\n",
      "  25%: 1.0\n",
      "  50% (Median): 1.0\n",
      "  75%: 1.0\n",
      "Min: 1.0\n",
      "Max: 1.0\n",
      "The distribution of the feature 'Bladder_Cancer' in this dataset is severely biased.\n",
      "\n",
      "For the feature 'Gender', the least common label is '0.0' with 8 occurrences. This represents 22.22% of the dataset.\n",
      "The distribution of the feature 'Gender' in this dataset is fine.\n",
      "\n",
      "The dataset was determined to be not usable for analysis. Bias in trait: True\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "print(f\"Original gene count: {len(gene_data)}\")\n",
    "print(f\"Sample of gene symbols before normalization:\")\n",
    "print(gene_data.index[:20])  # Display first 20 gene symbols\n",
    "\n",
    "# Normalize the gene data (skip mapping since we already have gene symbols)\n",
    "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Normalized gene count: {len(normalized_gene_data)}\")\n",
    "\n",
    "# Since this dataset has a small number of genes, we'll use the original data if normalization removes too many\n",
    "if len(normalized_gene_data) < len(gene_data) * 0.9:  # If we lost more than 10% of genes\n",
    "    print(\"Warning: Gene symbol normalization removed too many genes. Using original gene data without normalization.\")\n",
    "    normalized_gene_data = gene_data  # Use the original data without normalization\n",
    "\n",
    "# Create directory for the gene data file if it doesn't exist\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "\n",
    "# Save the gene data to a CSV file\n",
    "normalized_gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Gene data saved to {out_gene_data_file}\")\n",
    "\n",
    "# 2. Fix the clinical data extraction to properly use sample accessions\n",
    "# Reread the clinical data from the matrix file\n",
    "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
    "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
    "_, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
    "\n",
    "# Check if we have the Sample_geo_accession column to identify GSM IDs\n",
    "if '!Sample_geo_accession' in clinical_data.columns:\n",
    "    # Extract the GSM IDs from the clinical data\n",
    "    gsm_ids = clinical_data['!Sample_geo_accession'].tolist()\n",
    "    print(f\"Found {len(gsm_ids)} GSM IDs in clinical data\")\n",
    "    print(f\"First 5 GSM IDs: {gsm_ids[:5]}\")\n",
    "    \n",
    "    # Extract clinical features with proper GSM IDs\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",
    "    # Transpose the clinical dataframe to have samples as rows and features as columns\n",
    "    selected_clinical_df = selected_clinical_df.T\n",
    "    \n",
    "    # Check if the sample IDs match between clinical and gene data\n",
    "    common_samples = set(selected_clinical_df.index).intersection(set(normalized_gene_data.columns))\n",
    "    print(f\"Number of common samples between clinical and gene data: {len(common_samples)}\")\n",
    "    \n",
    "    # Save the properly formatted 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)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "    \n",
    "    # Create a proper linked dataset using the common samples\n",
    "    if len(common_samples) > 0:\n",
    "        # Filter both datasets to only include common samples\n",
    "        clinical_filtered = selected_clinical_df.loc[list(common_samples)]\n",
    "        gene_filtered = normalized_gene_data[list(common_samples)]\n",
    "        \n",
    "        # Combine the datasets\n",
    "        linked_data = pd.concat([clinical_filtered, gene_filtered.T], axis=1)\n",
    "        print(f\"Linked data shape after proper ID matching: {linked_data.shape}\")\n",
    "        \n",
    "        # 3. Handle missing values in the linked data with more relaxed criteria\n",
    "        # First, check missing value percentages\n",
    "        trait_missing = linked_data[trait].isna().mean() * 100\n",
    "        print(f\"Percentage of missing values in trait: {trait_missing:.2f}%\")\n",
    "        \n",
    "        # Apply the missing value handling\n",
    "        linked_data_cleaned = handle_missing_values(linked_data, trait)\n",
    "        print(f\"Linked data shape after handling missing values: {linked_data_cleaned.shape}\")\n",
    "        \n",
    "        # If we still have adequate data after cleaning\n",
    "        if linked_data_cleaned.shape[0] >= 5 and linked_data_cleaned.shape[1] >= 10:  # Lower threshold\n",
    "            # 4. Determine whether the trait and demographic features are severely biased\n",
    "            is_trait_biased, linked_data_cleaned = judge_and_remove_biased_features(linked_data_cleaned, trait)\n",
    "            \n",
    "            # 5. Conduct quality check and save the cohort information\n",
    "            note = \"Dataset contains gene expression data from bladder cancer samples with BCG treatment 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=is_trait_biased, \n",
    "                df=linked_data_cleaned, \n",
    "                note=note\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_cleaned.to_csv(out_data_file)\n",
    "                print(f\"Linked data saved to {out_data_file}\")\n",
    "            else:\n",
    "                print(f\"The dataset was determined to be not usable for analysis. Bias in trait: {is_trait_biased}\")\n",
    "        else:\n",
    "            print(\"Warning: After handling missing values, insufficient data remains for analysis\")\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=True,\n",
    "                df=linked_data_cleaned, \n",
    "                note=\"After cleaning, insufficient data remains for analysis.\"\n",
    "            )\n",
    "            print(\"The dataset was determined to be not usable for analysis.\")\n",
    "    else:\n",
    "        print(\"Warning: No common samples found between clinical and gene data\")\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=True,\n",
    "            df=pd.DataFrame(), \n",
    "            note=\"No common samples found between clinical and gene data.\"\n",
    "        )\n",
    "        print(\"The dataset was determined to be not usable for analysis.\")\n",
    "else:\n",
    "    print(\"Warning: No GSM IDs found in clinical data\")\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=True,\n",
    "        df=pd.DataFrame(), \n",
    "        note=\"No GSM IDs found in clinical data.\"\n",
    "    )\n",
    "    print(\"The dataset was determined to be not usable for analysis.\")"
   ]
  }
 ],
 "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
}