File size: 23,884 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
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "54681efd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:01:53.543600Z",
     "iopub.status.busy": "2025-03-25T07:01:53.543488Z",
     "iopub.status.idle": "2025-03-25T07:01:53.706285Z",
     "shell.execute_reply": "2025-03-25T07:01:53.705828Z"
    }
   },
   "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 = \"Breast_Cancer\"\n",
    "cohort = \"GSE225328\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Breast_Cancer\"\n",
    "in_cohort_dir = \"../../input/GEO/Breast_Cancer/GSE225328\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Breast_Cancer/GSE225328.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Breast_Cancer/gene_data/GSE225328.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Breast_Cancer/clinical_data/GSE225328.csv\"\n",
    "json_path = \"../../output/preprocess/Breast_Cancer/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a38711d6",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "62e23e20",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:01:53.707710Z",
     "iopub.status.busy": "2025-03-25T07:01:53.707557Z",
     "iopub.status.idle": "2025-03-25T07:01:53.735100Z",
     "shell.execute_reply": "2025-03-25T07:01:53.734694Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Transcriptome profiling in early-stage luminal breast cancer\"\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: ['disease: early-stage luminal breast cancer'], 1: ['Sex: female']}\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": "ad985c48",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "de5ab3c3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:01:53.736344Z",
     "iopub.status.busy": "2025-03-25T07:01:53.736230Z",
     "iopub.status.idle": "2025-03-25T07:01:53.750929Z",
     "shell.execute_reply": "2025-03-25T07:01:53.750474Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preview of clinical features:\n",
      "{'GSM7043537': [1.0, 0.0], 'GSM7043538': [1.0, 0.0], 'GSM7043539': [1.0, 0.0], 'GSM7043540': [1.0, 0.0], 'GSM7043541': [1.0, 0.0], 'GSM7043542': [1.0, 0.0], 'GSM7043543': [1.0, 0.0], 'GSM7043544': [1.0, 0.0], 'GSM7043545': [1.0, 0.0], 'GSM7043546': [1.0, 0.0], 'GSM7043547': [1.0, 0.0], 'GSM7043548': [1.0, 0.0], 'GSM7043549': [1.0, 0.0], 'GSM7043550': [1.0, 0.0], 'GSM7043551': [1.0, 0.0], 'GSM7043552': [1.0, 0.0], 'GSM7043553': [1.0, 0.0], 'GSM7043554': [1.0, 0.0], 'GSM7043555': [1.0, 0.0], 'GSM7043556': [1.0, 0.0], 'GSM7043557': [1.0, 0.0], 'GSM7043558': [1.0, 0.0], 'GSM7043559': [1.0, 0.0], 'GSM7043560': [1.0, 0.0], 'GSM7043561': [1.0, 0.0], 'GSM7043562': [1.0, 0.0], 'GSM7043563': [1.0, 0.0], 'GSM7043564': [1.0, 0.0], 'GSM7043565': [1.0, 0.0], 'GSM7043566': [1.0, 0.0], 'GSM7043567': [1.0, 0.0], 'GSM7043568': [1.0, 0.0], 'GSM7043569': [1.0, 0.0], 'GSM7043570': [1.0, 0.0], 'GSM7043571': [1.0, 0.0], 'GSM7043572': [1.0, 0.0], 'GSM7043573': [1.0, 0.0], 'GSM7043574': [1.0, 0.0], 'GSM7043575': [1.0, 0.0], 'GSM7043576': [1.0, 0.0], 'GSM7043577': [1.0, 0.0], 'GSM7043578': [1.0, 0.0], 'GSM7043579': [1.0, 0.0], 'GSM7043580': [1.0, 0.0], 'GSM7043581': [1.0, 0.0], 'GSM7043582': [1.0, 0.0], 'GSM7043583': [1.0, 0.0], 'GSM7043584': [1.0, 0.0], 'GSM7043585': [1.0, 0.0], 'GSM7043586': [1.0, 0.0], 'GSM7043587': [1.0, 0.0], 'GSM7043588': [1.0, 0.0], 'GSM7043589': [1.0, 0.0], 'GSM7043590': [1.0, 0.0], 'GSM7043591': [1.0, 0.0], 'GSM7043592': [1.0, 0.0], 'GSM7043593': [1.0, 0.0], 'GSM7043594': [1.0, 0.0], 'GSM7043595': [1.0, 0.0], 'GSM7043596': [1.0, 0.0], 'GSM7043597': [1.0, 0.0], 'GSM7043598': [1.0, 0.0], 'GSM7043599': [1.0, 0.0], 'GSM7043600': [1.0, 0.0], 'GSM7043601': [1.0, 0.0], 'GSM7043602': [1.0, 0.0], 'GSM7043603': [1.0, 0.0], 'GSM7043604': [1.0, 0.0], 'GSM7043605': [1.0, 0.0], 'GSM7043606': [1.0, 0.0], 'GSM7043607': [1.0, 0.0], 'GSM7043608': [1.0, 0.0], 'GSM7043609': [1.0, 0.0], 'GSM7043610': [1.0, 0.0], 'GSM7043611': [1.0, 0.0], 'GSM7043612': [1.0, 0.0], 'GSM7043613': [1.0, 0.0], 'GSM7043614': [1.0, 0.0], 'GSM7043615': [1.0, 0.0], 'GSM7043616': [1.0, 0.0], 'GSM7043617': [1.0, 0.0], 'GSM7043618': [1.0, 0.0], 'GSM7043619': [1.0, 0.0], 'GSM7043620': [1.0, 0.0], 'GSM7043621': [1.0, 0.0], 'GSM7043622': [1.0, 0.0], 'GSM7043623': [1.0, 0.0], 'GSM7043624': [1.0, 0.0], 'GSM7043625': [1.0, 0.0], 'GSM7043626': [1.0, 0.0], 'GSM7043627': [1.0, 0.0], 'GSM7043628': [1.0, 0.0], 'GSM7043629': [1.0, 0.0], 'GSM7043630': [1.0, 0.0], 'GSM7043631': [1.0, 0.0], 'GSM7043632': [1.0, 0.0], 'GSM7043633': [1.0, 0.0], 'GSM7043634': [1.0, 0.0], 'GSM7043635': [1.0, 0.0], 'GSM7043636': [1.0, 0.0], 'GSM7043637': [1.0, 0.0], 'GSM7043638': [1.0, 0.0], 'GSM7043639': [1.0, 0.0], 'GSM7043640': [1.0, 0.0], 'GSM7043641': [1.0, 0.0], 'GSM7043642': [1.0, 0.0], 'GSM7043643': [1.0, 0.0], 'GSM7043644': [1.0, 0.0], 'GSM7043645': [1.0, 0.0], 'GSM7043646': [1.0, 0.0], 'GSM7043647': [1.0, 0.0], 'GSM7043648': [1.0, 0.0], 'GSM7043649': [1.0, 0.0], 'GSM7043650': [1.0, 0.0], 'GSM7043651': [1.0, 0.0], 'GSM7043652': [1.0, 0.0], 'GSM7043653': [1.0, 0.0], 'GSM7043654': [1.0, 0.0], 'GSM7043655': [1.0, 0.0], 'GSM7043656': [1.0, 0.0], 'GSM7043657': [1.0, 0.0], 'GSM7043658': [1.0, 0.0], 'GSM7043659': [1.0, 0.0], 'GSM7043660': [1.0, 0.0], 'GSM7043661': [1.0, 0.0]}\n",
      "Clinical features saved to ../../output/preprocess/Breast_Cancer/clinical_data/GSE225328.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# According to the background information, this is a transcriptome profiling study\n",
    "# which typically means gene expression data is available\n",
    "is_gene_available = True\n",
    "\n",
    "# 2.1 Data Availability\n",
    "# Looking at the Sample Characteristics Dictionary:\n",
    "# Key 0 has \"disease: early-stage luminal breast cancer\" which is related to the trait (Breast Cancer)\n",
    "# Key 1 has \"Sex: female\" which is gender information\n",
    "# There is no age information available\n",
    "\n",
    "trait_row = 0  # Disease information is in row 0\n",
    "age_row = None  # Age information is not available\n",
    "gender_row = 1  # Gender information is in row 1\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait values to binary format.\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Since all samples are \"early-stage luminal breast cancer\", \n",
    "    # all will be converted to 1 (indicating presence of breast cancer)\n",
    "    if \"breast cancer\" in value.lower():\n",
    "        return 1\n",
    "    else:\n",
    "        return None  # For any unexpected values\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age values to continuous format.\"\"\"\n",
    "    # Age data is not available, but we include this function for completeness\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    try:\n",
    "        return float(value)\n",
    "    except (ValueError, TypeError):\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender values to binary format (0 for female, 1 for male).\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip().lower()\n",
    "    \n",
    "    if \"female\" in value:\n",
    "        return 0\n",
    "    elif \"male\" in value:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait data availability\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Initial filtering and saving metadata\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",
    "if trait_row is not None:\n",
    "    # Extract clinical features\n",
    "    clinical_features_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",
    "    print(\"Preview of clinical features:\")\n",
    "    print(preview_df(clinical_features_df))\n",
    "    \n",
    "    # Save the clinical features as a CSV file\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    clinical_features_df.to_csv(out_clinical_data_file)\n",
    "    print(f\"Clinical features saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2e6e732c",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "0b14f656",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:01:53.752701Z",
     "iopub.status.busy": "2025-03-25T07:01:53.752366Z",
     "iopub.status.idle": "2025-03-25T07:01:53.790641Z",
     "shell.execute_reply": "2025-03-25T07:01:53.790170Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SOFT file: ../../input/GEO/Breast_Cancer/GSE225328/GSE225328_family.soft.gz\n",
      "Matrix file: ../../input/GEO/Breast_Cancer/GSE225328/GSE225328-GPL18402_series_matrix.txt.gz\n",
      "Found the matrix table marker at line 60\n",
      "Gene data shape: (2006, 125)\n",
      "First 20 gene/probe identifiers:\n",
      "['hsa-let-7a-3p', 'hsa-let-7a-5p', 'hsa-let-7b-3p', 'hsa-let-7b-5p', 'hsa-let-7c', 'hsa-let-7d-3p', 'hsa-let-7d-5p', 'hsa-let-7e-3p', 'hsa-let-7e-5p', 'hsa-let-7f-1-3p', 'hsa-let-7f-2-3p', 'hsa-let-7f-5p', 'hsa-let-7g-3p', 'hsa-let-7g-5p', 'hsa-let-7i-3p', 'hsa-let-7i-5p', 'hsa-miR-1', 'hsa-miR-100-3p', 'hsa-miR-100-5p', 'hsa-miR-101-3p']\n"
     ]
    }
   ],
   "source": [
    "# 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",
    "print(f\"SOFT file: {soft_file}\")\n",
    "print(f\"Matrix file: {matrix_file}\")\n",
    "\n",
    "# Set gene availability flag\n",
    "is_gene_available = True  # Initially assume gene data is available\n",
    "\n",
    "# First check if the matrix file contains the expected marker\n",
    "found_marker = False\n",
    "marker_row = None\n",
    "try:\n",
    "    with gzip.open(matrix_file, 'rt') as file:\n",
    "        for i, line in enumerate(file):\n",
    "            if \"!series_matrix_table_begin\" in line:\n",
    "                found_marker = True\n",
    "                marker_row = i\n",
    "                print(f\"Found the matrix table marker at line {i}\")\n",
    "                break\n",
    "    \n",
    "    if not found_marker:\n",
    "        print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
    "        is_gene_available = False\n",
    "        \n",
    "    # If marker was found, try to extract gene data\n",
    "    if is_gene_available:\n",
    "        try:\n",
    "            # Try using the library function\n",
    "            gene_data = get_genetic_data(matrix_file)\n",
    "            \n",
    "            if gene_data.shape[0] == 0:\n",
    "                print(\"Warning: Extracted gene data has 0 rows.\")\n",
    "                is_gene_available = False\n",
    "            else:\n",
    "                print(f\"Gene data shape: {gene_data.shape}\")\n",
    "                # Print the first 20 gene/probe identifiers\n",
    "                print(\"First 20 gene/probe identifiers:\")\n",
    "                print(gene_data.index[:20].tolist())\n",
    "        except Exception as e:\n",
    "            print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
    "            is_gene_available = False\n",
    "    \n",
    "    # If gene data extraction failed, examine file content to diagnose\n",
    "    if not is_gene_available:\n",
    "        print(\"Examining file content to diagnose the issue:\")\n",
    "        try:\n",
    "            with gzip.open(matrix_file, 'rt') as file:\n",
    "                # Print lines around the marker if found\n",
    "                if marker_row is not None:\n",
    "                    for i, line in enumerate(file):\n",
    "                        if i >= marker_row - 2 and i <= marker_row + 10:\n",
    "                            print(f\"Line {i}: {line.strip()[:100]}...\")\n",
    "                        if i > marker_row + 10:\n",
    "                            break\n",
    "                else:\n",
    "                    # If marker not found, print first 10 lines\n",
    "                    for i, line in enumerate(file):\n",
    "                        if i < 10:\n",
    "                            print(f\"Line {i}: {line.strip()[:100]}...\")\n",
    "                        else:\n",
    "                            break\n",
    "        except Exception as e2:\n",
    "            print(f\"Error examining file: {e2}\")\n",
    "        \n",
    "except Exception as e:\n",
    "    print(f\"Error processing file: {e}\")\n",
    "    is_gene_available = False\n",
    "\n",
    "# Update validation information if gene data extraction failed\n",
    "if not is_gene_available:\n",
    "    print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
    "    # Update the validation record since gene data isn't available\n",
    "    is_trait_available = False  # We already determined trait data isn't available in step 2\n",
    "    validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
    "                                 is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bb4bf217",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "0e4703c0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:01:53.792136Z",
     "iopub.status.busy": "2025-03-25T07:01:53.792027Z",
     "iopub.status.idle": "2025-03-25T07:01:53.794184Z",
     "shell.execute_reply": "2025-03-25T07:01:53.793754Z"
    }
   },
   "outputs": [],
   "source": [
    "# Based on the output from the previous step, I can see that the gene identifiers\n",
    "# are miRNA identifiers (e.g., \"hsa-let-7a-3p\", \"hsa-miR-1\", etc.)\n",
    "# These are proper standard miRNA names for human miRNAs (hsa prefix = Homo sapiens)\n",
    "# They are not gene symbols (like BRCA1, TP53) and would need to be mapped if we want\n",
    "# to convert to standard gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "48d28a60",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "fcc938b0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:01:53.795600Z",
     "iopub.status.busy": "2025-03-25T07:01:53.795494Z",
     "iopub.status.idle": "2025-03-25T07:01:54.048608Z",
     "shell.execute_reply": "2025-03-25T07:01:54.048080Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene annotation preview:\n",
      "Columns in gene annotation: ['ID', 'miRNA_ID', 'ACCESSION_STRING', 'CONTROL_TYPE', 'SPOT_ID', 'SPOT_ID.1']\n",
      "{'ID': ['hsa-let-7a-3p', 'hsa-let-7a-5p', 'hsa-let-7b-3p'], 'miRNA_ID': ['hsa-let-7a-3p', 'hsa-let-7a-5p', 'hsa-let-7b-3p'], 'ACCESSION_STRING': ['mir|hsa-let-7a-3p|mir|MIMAT0004481|mir|hsa-let-7a*_v17.0|mir|MIMAT0004481', 'mir|hsa-let-7a-5p|mir|MIMAT0000062|mir|hsa-let-7a_v17.0|mir|MIMAT0000062', 'mir|hsa-let-7b-3p|mir|MIMAT0004482|mir|hsa-let-7b*_v17.0|mir|MIMAT0004482'], 'CONTROL_TYPE': [False, False, False], 'SPOT_ID': [nan, nan, nan], 'SPOT_ID.1': [nan, nan, nan]}\n",
      "\n",
      "Examining ID and ORF columns format (first 3 rows):\n"
     ]
    }
   ],
   "source": [
    "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "\n",
    "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
    "print(\"\\nGene annotation preview:\")\n",
    "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
    "print(preview_df(gene_annotation, n=3))\n",
    "\n",
    "# Looking at the output, it appears the gene symbols are in the 'ORF' column\n",
    "# and the probe IDs are in the 'ID' column\n",
    "print(\"\\nExamining ID and ORF columns format (first 3 rows):\")\n",
    "if 'ID' in gene_annotation.columns and 'ORF' in gene_annotation.columns:\n",
    "    for i in range(min(3, len(gene_annotation))):\n",
    "        print(f\"Row {i}: ID={gene_annotation['ID'].iloc[i]}, ORF={gene_annotation['ORF'].iloc[i]}\")\n",
    "\n",
    "    # Check the quality and completeness of the mapping\n",
    "    non_null_symbols = gene_annotation['ORF'].notna().sum()\n",
    "    total_rows = len(gene_annotation)\n",
    "    print(f\"\\nORF column completeness: {non_null_symbols}/{total_rows} rows ({non_null_symbols/total_rows:.2%})\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "57976e5b",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "048f7954",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:01:54.050088Z",
     "iopub.status.busy": "2025-03-25T07:01:54.049962Z",
     "iopub.status.idle": "2025-03-25T07:01:54.084210Z",
     "shell.execute_reply": "2025-03-25T07:01:54.083767Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gene expression data sample (first 5 rows, 3 columns):\n",
      "               GSM7043537  GSM7043538  GSM7043539\n",
      "ID                                               \n",
      "hsa-let-7a-3p   -2.842319    0.656993   -3.119569\n",
      "hsa-let-7a-5p   12.236782   11.668952   12.020029\n",
      "hsa-let-7b-3p    3.586698   -3.123689    0.167606\n",
      "hsa-let-7b-5p   12.979993   12.667322   12.236782\n",
      "hsa-let-7c      11.518827   10.673440   10.153807\n",
      "\n",
      "This dataset contains miRNA expression data, not standard gene expression data.\n",
      "miRNAs are small non-coding RNAs that regulate gene expression but are not genes themselves.\n",
      "For the purpose of gene-trait association studies, we require standard gene expression data.\n",
      "\n",
      "Dataset marked as not containing suitable gene expression data for our analysis.\n"
     ]
    }
   ],
   "source": [
    "# Based on the exploration of columns, we can confirm this is miRNA data, not gene expression data\n",
    "# The identifiers are miRNA IDs (e.g., hsa-let-7a-3p) which don't map to standard gene symbols\n",
    "\n",
    "# Let's examine a sample of the gene expression data and annotation to confirm\n",
    "gene_expression_data = get_genetic_data(matrix_file)\n",
    "print(\"\\nGene expression data sample (first 5 rows, 3 columns):\")\n",
    "sample_cols = gene_expression_data.columns[:3].tolist()\n",
    "print(gene_expression_data.iloc[:5, :3])\n",
    "\n",
    "# Update our gene availability flag since this isn't standard gene expression data\n",
    "is_gene_available = False\n",
    "print(\"\\nThis dataset contains miRNA expression data, not standard gene expression data.\")\n",
    "print(\"miRNAs are small non-coding RNAs that regulate gene expression but are not genes themselves.\")\n",
    "print(\"For the purpose of gene-trait association studies, we require standard gene expression data.\")\n",
    "\n",
    "# Save the updated metadata to reflect that this dataset isn't suitable\n",
    "is_trait_available = True  # We confirmed trait data is available in earlier steps\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",
    "    note=\"Dataset contains miRNA expression data instead of gene expression data.\"\n",
    ")\n",
    "\n",
    "print(\"\\nDataset marked as not containing suitable gene expression data for our 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
}