File size: 31,291 Bytes
d1894e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ecdbd0bf",
   "metadata": {},
   "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 = \"Glucocorticoid_Sensitivity\"\n",
    "cohort = \"GSE48801\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Glucocorticoid_Sensitivity\"\n",
    "in_cohort_dir = \"../../input/GEO/Glucocorticoid_Sensitivity/GSE48801\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Glucocorticoid_Sensitivity/GSE48801.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Glucocorticoid_Sensitivity/gene_data/GSE48801.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE48801.csv\"\n",
    "json_path = \"../../output/preprocess/Glucocorticoid_Sensitivity/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "392ddc45",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "263e6c59",
   "metadata": {},
   "outputs": [],
   "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": "11712666",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "430b9104",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information, this dataset studies the transcriptome-wide\n",
    "# response to glucocorticoids and mentions RNA, suggesting gene expression data is available\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "\n",
    "# 2.1 Trait - Glucocorticoid Sensitivity\n",
    "# From the sample characteristics, row 1 contains \"in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex)\"\n",
    "# which matches our trait of interest\n",
    "trait_row = 1\n",
    "\n",
    "# Define conversion function for Glucocorticoid_Sensitivity\n",
    "def convert_trait(value):\n",
    "    # Extract numeric value from the string\n",
    "    if isinstance(value, str) and \"in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex):\" in value:\n",
    "        try:\n",
    "            # Extract the numeric part after the colon\n",
    "            numeric_value = float(value.split(\":\")[-1].strip())\n",
    "            return numeric_value\n",
    "        except (ValueError, IndexError):\n",
    "            return None\n",
    "    return None\n",
    "\n",
    "# 2.2 Age - Not available in this dataset\n",
    "# There is no information about age in the sample characteristics\n",
    "age_row = None\n",
    "\n",
    "def convert_age(value):\n",
    "    return None\n",
    "\n",
    "# 2.3 Gender - Not available in this dataset\n",
    "# There is no information about gender in the sample characteristics\n",
    "gender_row = None\n",
    "\n",
    "def convert_gender(value):\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Trait data is available (trait_row is not None)\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Conduct initial filtering on dataset usability\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",
    "    # Create a proper DataFrame from sample characteristics\n",
    "    sample_characteristics = {0: ['treatment: dexamethasone + phytohemagglutinin', 'treatment: vehicle (EtOH) + phytohemagglutinin', 'treatment: no treatment'], \n",
    "                              1: ['in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 90.2096916857165', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 92.0660852718675', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 85.8770390662799', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 87.4945143923344', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 85.1993812425936', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 84.9616236229156', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 83.9341340611542', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 88.7663927292959', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 88.4126127755346', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 90.1302355511097', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 86.3038207243861', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 97.9389927348314', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 85.6565800452145', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 72.080026977723', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 95.7902581814721', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 84.7169700775247', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 97.2440363125325', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 98.6965291984436', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 96.3897437049292', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 93.7864779279733', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 88.9409584548941', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 95.2180128029044', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 80.3262384967705', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 98.9664822965928', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 86.7141270837215', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 94.1342236284511', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 76.5646360533747', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 94.4880035822124', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 84.2040871593034', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 81.2524330708547']}\n",
    "    \n",
    "    # Create a properly structured DataFrame as expected by geo_select_clinical_features\n",
    "    clinical_data = pd.DataFrame()\n",
    "    for key, values in sample_characteristics.items():\n",
    "        clinical_data.loc[key] = pd.Series(values)\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 dataframe\n",
    "    preview = preview_df(selected_clinical_df)\n",
    "    print(\"Preview of selected clinical features:\")\n",
    "    print(preview)\n",
    "    \n",
    "    # Save to CSV\n",
    "    # Create directory if it doesn't exist\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\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": "820b0d9e",
   "metadata": {},
   "source": [
    "### Step 3: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a07459b3",
   "metadata": {},
   "outputs": [],
   "source": [
    "I understand that there's a syntax error in the previous code, and I need to implement a clean solution for analyzing the dataset and extracting clinical features. Here's my corrected implementation:\n",
    "\n",
    "```python\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import os\n",
    "import json\n",
    "from typing import Callable, Optional, Dict, Any\n",
    "import glob\n",
    "\n",
    "# First, let's define variables for data availability\n",
    "is_gene_available = False\n",
    "\n",
    "# Check what files are available in the input directory\n",
    "print(f\"Files in input directory: {os.listdir(in_cohort_dir)}\")\n",
    "\n",
    "# Look for files that might contain clinical/sample data\n",
    "clinical_files = [f for f in os.listdir(in_cohort_dir) if any(term in f.lower() for term in \n",
    "                  ['clinical', 'sample', 'characteristic', 'series', 'matrix', 'info'])]\n",
    "print(f\"Potential clinical data files: {clinical_files}\")\n",
    "\n",
    "clinical_data = None\n",
    "# Try to find and load clinical data from various possible files\n",
    "for file_pattern in [\"*series_matrix*\", \"*clinical*\", \"*sample*\", \"*.soft\", \"GSE*\"]:\n",
    "    matching_files = glob.glob(os.path.join(in_cohort_dir, file_pattern))\n",
    "    for file in matching_files:\n",
    "        try:\n",
    "            # Try different read methods based on file extension\n",
    "            if file.endswith('.csv'):\n",
    "                temp_data = pd.read_csv(file)\n",
    "            elif file.endswith('.txt') or file.endswith('.tsv'):\n",
    "                temp_data = pd.read_csv(file, sep='\\t')\n",
    "            else:\n",
    "                # Try to infer delimiter\n",
    "                temp_data = pd.read_csv(file, sep=None, engine='python')\n",
    "            \n",
    "            # Check if this looks like sample characteristics data\n",
    "            if 'sample' in temp_data.columns or any('characteristic' in col.lower() for col in temp_data.columns):\n",
    "                clinical_data = temp_data\n",
    "                print(f\"Found clinical data in {file} with shape: {clinical_data.shape}\")\n",
    "                break\n",
    "        except Exception as e:\n",
    "            print(f\"Could not read {file}: {str(e)}\")\n",
    "    \n",
    "    if clinical_data is not None:\n",
    "        break\n",
    "\n",
    "# If we still don't have clinical data, use a more aggressive approach to find any tabular data\n",
    "if clinical_data is None:\n",
    "    for file in os.listdir(in_cohort_dir):\n",
    "        try:\n",
    "            file_path = os.path.join(in_cohort_dir, file)\n",
    "            if os.path.isfile(file_path):\n",
    "                # Try to read the first few lines to determine format\n",
    "                with open(file_path, 'r') as f:\n",
    "                    first_lines = []\n",
    "                    for _ in range(10):\n",
    "                        try:\n",
    "                            line = next(f)\n",
    "                            if line.strip():\n",
    "                                first_lines.append(line)\n",
    "                        except StopIteration:\n",
    "                            break\n",
    "                \n",
    "                # If file seems to contain tabular data, try to read it\n",
    "                if any('\\t' in line for line in first_lines) or any(',' in line for line in first_lines):\n",
    "                    try:\n",
    "                        # Determine delimiter\n",
    "                        if any('\\t' in line for line in first_lines):\n",
    "                            temp_data = pd.read_csv(file_path, sep='\\t')\n",
    "                        else:\n",
    "                            temp_data = pd.read_csv(file_path, sep=',')\n",
    "                        \n",
    "                        if temp_data.shape[0] > 1 and temp_data.shape[1] > 1:\n",
    "                            clinical_data = temp_data\n",
    "                            print(f\"Found potential data in {file} with shape: {clinical_data.shape}\")\n",
    "                            print(clinical_data.head())\n",
    "                            break\n",
    "                    except Exception as e:\n",
    "                        print(f\"Failed to process {file}: {str(e)}\")\n",
    "        except Exception as e:\n",
    "            print(f\"Error accessing {file}: {str(e)}\")\n",
    "            continue\n",
    "\n",
    "# Check if gene expression data is available\n",
    "try:\n",
    "    gene_files = [f for f in os.listdir(in_cohort_dir) if f.endswith(('.txt', '.csv', '.tsv', '.gz'))]\n",
    "    for file in gene_files:\n",
    "        try:\n",
    "            file_path = os.path.join(in_cohort_dir, file)\n",
    "            # For compressed files, check the filename\n",
    "            if file.endswith('.gz'):\n",
    "                if any(term in file.lower() for term in ['gene', 'expr', 'rna']):\n",
    "                    is_gene_available = True\n",
    "                    print(f\"Potential gene expression data found in compressed file {file}\")\n",
    "                    break\n",
    "            else:\n",
    "                # Read just the first few lines to check format\n",
    "                with open(file_path, 'r') as f:\n",
    "                    header = []\n",
    "                    for _ in range(5):\n",
    "                        try:\n",
    "                            line = next(f)\n",
    "                            header.append(line)\n",
    "                        except StopIteration:\n",
    "                            break\n",
    "                \n",
    "                # If it contains gene IDs or symbols, it's likely gene expression data\n",
    "                header_text = ''.join(header).lower()\n",
    "                if any(term in header_text for term in ['ensg', 'nm_', 'gene', 'entrez', 'probe']):\n",
    "                    is_gene_available = True\n",
    "                    print(f\"Potential gene expression data found in {file}\")\n",
    "                    break\n",
    "        except Exception as e:\n",
    "            print(f\"Error checking {file}: {str(e)}\")\n",
    "            continue\n",
    "except Exception as e:\n",
    "    print(f\"Could not access the directory to check for gene expression files: {str(e)}\")\n",
    "\n",
    "# If we couldn't determine from file content, check for large files which might be gene expression data\n",
    "if not is_gene_available:\n",
    "    try:\n",
    "        large_files = [f for f in os.listdir(in_cohort_dir) \n",
    "                     if os.path.isfile(os.path.join(in_cohort_dir, f)) \n",
    "                     and os.path.getsize(os.path.join(in_cohort_dir, f)) > 1000000]\n",
    "        if large_files:\n",
    "            print(f\"Assuming gene expression data is available based on large files: {large_files}\")\n",
    "            is_gene_available = True\n",
    "    except Exception as e:\n",
    "        print(f\"Error checking file sizes: {str(e)}\")\n",
    "\n",
    "# Let's examine the clinical data to identify trait, age, and gender information\n",
    "trait_row = None\n",
    "age_row = None\n",
    "gender_row = None\n",
    "\n",
    "# Check if clinical_data is available\n",
    "if clinical_data is not None:\n",
    "    print(\"Sample of clinical data:\")\n",
    "    print(clinical_data.head())\n",
    "    \n",
    "    # Try to identify the structure of the data\n",
    "    if 'sample' in clinical_data.columns:\n",
    "        # This might be a traditional GEO series matrix format\n",
    "        for i in range(1, min(clinical_data.shape[0], 20)):  # Check first 20 rows\n",
    "            try:\n",
    "                # Get the unique values for this row\n",
    "                unique_values = clinical_data.iloc[i, 1:].dropna().unique()\n",
    "                row_name = str(clinical_data.iloc[i, 0]).lower() if not pd.isna(clinical_data.iloc[i, 0]) else \"\"\n",
    "                \n",
    "                print(f\"Row {i}: {row_name}\")\n",
    "                print(f\"Unique values: {[str(val) for val in unique_values[:5]]}\")\n",
    "                \n",
    "                # Check for trait data related to glucocorticoid sensitivity\n",
    "                if any(term in row_name for term in ['gluco', 'cortico', 'sensitiv', 'resist', 'treatment', 'response']) or \\\n",
    "                   any(term in str(val).lower() for val in unique_values for term in ['gluco', 'cortico', 'sensitiv', 'resist']):\n",
    "                    trait_row = i\n",
    "                    print(f\"Potential trait data found in row {i}: {row_name}\")\n",
    "                \n",
    "                # Check for age data\n",
    "                if 'age' in row_name or \\\n",
    "                   any('year' in str(val).lower() for val in unique_values) or \\\n",
    "                   any(str(val).strip().isdigit() and 0 < int(val) < 100 for val in unique_values if str(val).strip().isdigit()):\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f0bc459b",
   "metadata": {},
   "source": [
    "### Step 4: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a95b4272",
   "metadata": {},
   "outputs": [],
   "source": [
    "I'll now implement the correct code that follows the instructions and addresses the error from the previous attempt.\n",
    "\n",
    "```python\n",
    "import os\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import json\n",
    "from typing import Callable, Optional, Dict, Any\n",
    "\n",
    "# First, let's check what files are available in the cohort directory\n",
    "print(\"Available files in the cohort directory:\")\n",
    "if os.path.exists(in_cohort_dir):\n",
    "    files = os.listdir(in_cohort_dir)\n",
    "    for file in files:\n",
    "        print(f\"- {file}\")\n",
    "else:\n",
    "    print(f\"Directory {in_cohort_dir} does not exist.\")\n",
    "\n",
    "# Let's try to find the series matrix file which typically contains gene expression and clinical data\n",
    "series_matrix_file = None\n",
    "for file in os.listdir(in_cohort_dir) if os.path.exists(in_cohort_dir) else []:\n",
    "    if file.endswith('_series_matrix.txt') or file == 'series_matrix.txt':\n",
    "        series_matrix_file = os.path.join(in_cohort_dir, file)\n",
    "        break\n",
    "\n",
    "if series_matrix_file and os.path.exists(series_matrix_file):\n",
    "    print(f\"Found series matrix file: {series_matrix_file}\")\n",
    "    \n",
    "    # Read the series matrix file to extract sample characteristics\n",
    "    with open(series_matrix_file, 'r') as file:\n",
    "        lines = file.readlines()\n",
    "    \n",
    "    # Extract background information\n",
    "    background_info = \"\"\n",
    "    i = 0\n",
    "    while i < len(lines) and not lines[i].startswith('!series_matrix_table_begin'):\n",
    "        background_info += lines[i]\n",
    "        i += 1\n",
    "    \n",
    "    # Extract sample characteristics (lines starting with !Sample_characteristics_ch1)\n",
    "    clinical_data_lines = []\n",
    "    for i, line in enumerate(lines):\n",
    "        if line.startswith('!Sample_characteristics_ch1'):\n",
    "            clinical_data_lines.append((i, line.strip().split('\\t')[1:]))\n",
    "    \n",
    "    # Convert to DataFrame where each row is a characteristic type\n",
    "    if clinical_data_lines:\n",
    "        sample_ids = [f\"Sample_{i+1}\" for i in range(len(clinical_data_lines[0][1]))]\n",
    "        clinical_data = pd.DataFrame(index=range(len(clinical_data_lines)), columns=sample_ids)\n",
    "        \n",
    "        for row_idx, (_, values) in enumerate(clinical_data_lines):\n",
    "            for col_idx, value in enumerate(values):\n",
    "                if col_idx < len(sample_ids):\n",
    "                    clinical_data.iloc[row_idx, col_idx] = value\n",
    "    else:\n",
    "        clinical_data = pd.DataFrame()\n",
    "    \n",
    "    # Display background information\n",
    "    print(\"\\nBackground Information Preview:\")\n",
    "    print(background_info[:1000]) \n",
    "    \n",
    "    # Display the sample characteristics\n",
    "    print(\"\\nSample Characteristics Preview:\")\n",
    "    for i in range(min(10, len(clinical_data))):\n",
    "        unique_values = set(clinical_data.iloc[i].dropna())\n",
    "        if len(unique_values) < 10:  # Only print if there aren't too many unique values\n",
    "            print(f\"Row {i}: {unique_values}\")\n",
    "    \n",
    "    # 1. Gene Expression Data Availability\n",
    "    # Determine if gene expression data is available based on background information\n",
    "    is_gene_available = True\n",
    "    if any(term in background_info.lower() for term in ['methylation array', 'methylation only', 'mirna only']):\n",
    "        is_gene_available = False\n",
    "    \n",
    "    # 2. Variable Availability and Data Type Conversion\n",
    "    # 2.1 Data Availability - identify rows containing trait, age, and gender data\n",
    "    trait_row = None\n",
    "    age_row = None\n",
    "    gender_row = None\n",
    "    \n",
    "    # Examine each row for characteristic type\n",
    "    for i in range(len(clinical_data)):\n",
    "        if i < len(clinical_data):\n",
    "            row_values = clinical_data.iloc[i].dropna().tolist()\n",
    "            if row_values:\n",
    "                row_text = str(row_values[0]).lower()\n",
    "                \n",
    "                # Check for glucocorticoid sensitivity indicators\n",
    "                if any(term in row_text for term in [\"glucocorticoid\", \"dexamethasone\", \"treatment\", \"sensitivity\", \"steroid\"]):\n",
    "                    trait_row = i\n",
    "                \n",
    "                # Check for age indicators\n",
    "                elif any(term in row_text for term in [\"age\", \"years old\"]):\n",
    "                    age_row = i\n",
    "                \n",
    "                # Check for gender/sex indicators\n",
    "                elif any(term in row_text for term in [\"gender\", \"sex\"]):\n",
    "                    gender_row = i\n",
    "    \n",
    "    # Check if the rows have more than one unique value (not constant)\n",
    "    if trait_row is not None and len(set(str(x).lower() for x in clinical_data.iloc[trait_row].dropna())) <= 1:\n",
    "        trait_row = None  # Not useful if all values are the same\n",
    "    \n",
    "    if age_row is not None and len(set(str(x).lower() for x in clinical_data.iloc[age_row].dropna())) <= 1:\n",
    "        age_row = None  # Not useful if all values are the same\n",
    "    \n",
    "    if gender_row is not None and len(set(str(x).lower() for x in clinical_data.iloc[gender_row].dropna())) <= 1:\n",
    "        gender_row = None  # Not useful if all values are the same\n",
    "    \n",
    "    # 2.2 Data Type Conversion Functions\n",
    "    def convert_trait(value):\n",
    "        \"\"\"Convert trait values to binary (0 or 1) or None if unknown.\"\"\"\n",
    "        if pd.isna(value) or value is None:\n",
    "            return None\n",
    "        \n",
    "        value = str(value).lower()\n",
    "        \n",
    "        # Extract value after colon if present\n",
    "        if \":\" in value:\n",
    "            value = value.split(\":\", 1)[1].strip()\n",
    "        \n",
    "        # Define conversion rules for glucocorticoid sensitivity\n",
    "        sensitive_terms = [\"sensitive\", \"sensitivity\", \"responder\", \"responsive\", \"response\", \"untreated\", \"control\"]\n",
    "        resistant_terms = [\"resistant\", \"resistance\", \"non-responder\", \"unresponsive\", \"no response\", \"treated\", \"dexamethasone\"]\n",
    "        \n",
    "        if any(term in value for term in sensitive_terms):\n",
    "            return 1  # Sensitive\n",
    "        elif any(term in value for term in resistant_terms):\n",
    "            return 0  # Resistant\n",
    "        else:\n",
    "            return None\n",
    "    \n",
    "    def convert_age(value):\n",
    "        \"\"\"Convert age values to continuous numerical values or None if unknown.\"\"\"\n",
    "        if pd.isna(value) or value is None:\n",
    "            return None\n",
    "        \n",
    "        value = str(value)\n",
    "        \n",
    "        # Extract value after colon if present\n",
    "        if \":\" in value:\n",
    "            value = value.split(\":\", 1)[1].strip()\n",
    "        \n",
    "        # Try to extract numerical value\n",
    "        import re\n",
    "        numbers = re.findall(r'\\d+', value)\n",
    "        if numbers:\n",
    "            return float(numbers[0])\n",
    "        else:\n",
    "            return None\n",
    "    \n",
    "    def convert_gender(value):\n",
    "        \"\"\"Convert gender values to binary (0=female, 1=male) or None if unknown.\"\"\"\n",
    "        if pd.isna(value) or value is None:\n",
    "            return None\n",
    "        \n",
    "        value = str(value).lower()\n",
    "        \n",
    "        # Extract value after colon if present\n",
    "        if \":\" in value:\n",
    "            value = value.split(\":\", 1)[1].strip()\n",
    "        \n",
    "        if any(term in value for term in [\"female\", \"f\", \"woman\"]):\n",
    "            return 0  # Female\n",
    "        elif any(term in value for term in [\"male\", \"m\", \"man\"]):\n",
    "            return 1  # Male\n",
    "        else:\n",
    "            return None\n",
    "    \n",
    "    # 3. Save Metadata\n",
    "    # Determine trait availability\n",
    "    is_trait_available = trait_row is not None\n",
    "    \n",
    "    # Conduct initial filtering and save metadata\n",
    "    validation_result = 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",
    "    # Only execute if trait data is available\n",
    "    if trait_row is not None:\n",
    "        # Extract clinical features\n",
    "        clinical\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f94ecad",
   "metadata": {},
   "source": [
    "### Step 5: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9d17c839",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Get the file paths for the SOFT file and matrix file\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. First, let's examine the structure of the matrix file to understand its format\n",
    "import gzip\n",
    "\n",
    "# Peek at the first few lines of the file to understand its structure\n",
    "with gzip.open(matrix_file, 'rt') as file:\n",
    "    # Read first 100 lines to find the header structure\n",
    "    for i, line in enumerate(file):\n",
    "        if '!series_matrix_table_begin' in line:\n",
    "            print(f\"Found data marker at line {i}\")\n",
    "            # Read the next line which should be the header\n",
    "            header_line = next(file)\n",
    "            print(f\"Header line: {header_line.strip()}\")\n",
    "            # And the first data line\n",
    "            first_data_line = next(file)\n",
    "            print(f\"First data line: {first_data_line.strip()}\")\n",
    "            break\n",
    "        if i > 100:  # Limit search to first 100 lines\n",
    "            print(\"Matrix table marker not found in first 100 lines\")\n",
    "            break\n",
    "\n",
    "# 3. Now try to get the genetic data with better error handling\n",
    "try:\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    print(gene_data.index[:20])\n",
    "except KeyError as e:\n",
    "    print(f\"KeyError: {e}\")\n",
    "    \n",
    "    # Alternative approach: manually extract the data\n",
    "    print(\"\\nTrying alternative approach to read the gene data:\")\n",
    "    with gzip.open(matrix_file, 'rt') as file:\n",
    "        # Find the start of the data\n",
    "        for line in file:\n",
    "            if '!series_matrix_table_begin' in line:\n",
    "                break\n",
    "                \n",
    "        # Read the headers and data\n",
    "        import pandas as pd\n",
    "        df = pd.read_csv(file, sep='\\t', index_col=0)\n",
    "        print(f\"Column names: {df.columns[:5]}\")\n",
    "        print(f\"First 20 row IDs: {df.index[:20]}\")\n",
    "        gene_data = df\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "073b009a",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6f5835f8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Reviewing the gene identifiers in the gene expression data\n",
    "# The identifiers start with \"ILMN_\" which indicates these are Illumina probe IDs\n",
    "# These are not human gene symbols but rather probe identifiers from Illumina microarray platform\n",
    "# They need to be mapped to human gene symbols for biological interpretation\n",
    "\n",
    "requires_gene_mapping = True"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}