File size: 27,128 Bytes
32677ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
642
643
644
645
646
647
648
649
650
651
652
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a673eb5c",
   "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 = \"Eczema\"\n",
    "cohort = \"GSE61225\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Eczema\"\n",
    "in_cohort_dir = \"../../input/GEO/Eczema/GSE61225\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Eczema/GSE61225.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Eczema/gene_data/GSE61225.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Eczema/clinical_data/GSE61225.csv\"\n",
    "json_path = \"../../output/preprocess/Eczema/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ba7645bd",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bd7f464e",
   "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": "5207c5a4",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d9a2283d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# From the background information, we can see this is a gene expression study\n",
    "# \"Gene expression in whole blood RNA was evaluated using Illumina HumanHT-12v3 Expression-BeadChip\"\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# For trait - in this study about exposure to swimming pool water, we'll use swimming pool exposure\n",
    "trait_row = 2  # 'swimming pool water exposure time' shows exposure status\n",
    "\n",
    "# For age information\n",
    "age_row = 6  # 'age' is available\n",
    "\n",
    "# For gender information\n",
    "gender_row = 5  # 'gender' is available\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "def convert_trait(value):\n",
    "    \"\"\"\n",
    "    Convert swimming pool exposure to binary trait\n",
    "    0 = no exposure (0 minutes)\n",
    "    1 = exposure (40 minutes)\n",
    "    \"\"\"\n",
    "    if not value or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if needed\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Convert to exposure status (binary)\n",
    "    if '0 minutes' in value:\n",
    "        return 0  # No exposure\n",
    "    elif '40 minutes' in value:\n",
    "        return 1  # Exposure\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"\n",
    "    Convert age to continuous value\n",
    "    \"\"\"\n",
    "    if not value or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if needed\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    try:\n",
    "        return float(value)\n",
    "    except:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"\n",
    "    Convert gender to binary\n",
    "    0 = female\n",
    "    1 = male\n",
    "    \"\"\"\n",
    "    if not value or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract value after colon if needed\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    value = value.lower()\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",
    "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. Clinical Feature Extraction\n",
    "if trait_row is not None:\n",
    "    # Construct clinical data from the sample characteristics dictionary\n",
    "    # First, create a dictionary to store the data\n",
    "    data = {}\n",
    "    \n",
    "    # Extract sample IDs (assuming they're at index 0)\n",
    "    sample_ids = [s.split(': ')[1] for s in sample_characteristics[0]]\n",
    "    \n",
    "    # Prepare data for each feature\n",
    "    trait_values = [convert_trait(s) for s in sample_characteristics[trait_row]]\n",
    "    age_values = [convert_age(s) for s in sample_characteristics[age_row]]\n",
    "    gender_values = [convert_gender(s) for s in sample_characteristics[gender_row]]\n",
    "    \n",
    "    # Create DataFrame with the clinical data\n",
    "    clinical_data = pd.DataFrame({\n",
    "        'ID_REF': sample_ids,\n",
    "        'VALUE': trait_values,\n",
    "        'Age': age_values,\n",
    "        'Gender': gender_values\n",
    "    })\n",
    "    \n",
    "    # Extract clinical features\n",
    "    selected_clinical_df = geo_select_clinical_features(\n",
    "        clinical_data,\n",
    "        trait=trait,\n",
    "        trait_row=1,  # Column position in the DataFrame (VALUE column)\n",
    "        convert_trait=lambda x: x,  # Values are already converted\n",
    "        age_row=2,  # Column position in the DataFrame (Age column)\n",
    "        convert_age=lambda x: x,  # Values are already converted\n",
    "        gender_row=3,  # Column position in the DataFrame (Gender column)\n",
    "        convert_gender=lambda x: x  # Values are already converted\n",
    "    )\n",
    "    \n",
    "    # Preview the clinical data\n",
    "    preview = preview_df(selected_clinical_df)\n",
    "    print(\"Preview of selected clinical data:\")\n",
    "    print(preview)\n",
    "    \n",
    "    # Save 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, index=False)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6ac00181",
   "metadata": {},
   "source": [
    "### Step 3: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a4e15502",
   "metadata": {},
   "outputs": [],
   "source": [
    "I'll revise the code to address the syntax errors and properly implement the required functionality.\n",
    "\n",
    "```python\n",
    "# Examining the sample characteristics from output_dict\n",
    "import pandas as pd\n",
    "import os\n",
    "import json\n",
    "from typing import Callable, Optional, Dict, Any\n",
    "import glob\n",
    "\n",
    "# Let's try to find the clinical data and determine what we have\n",
    "files = os.listdir(in_cohort_dir)\n",
    "print(f\"Files found in directory: {files}\")\n",
    "\n",
    "# Step 1: Find the clinical data file in the cohort directory\n",
    "# Try different possible file patterns for clinical data\n",
    "clinical_file = None\n",
    "possible_patterns = [\n",
    "    '*characteristics*', '*clinical*', '*sample*', '*.soft', '*.txt', '*.tsv'\n",
    "]\n",
    "\n",
    "for pattern in possible_patterns:\n",
    "    matching_files = glob.glob(os.path.join(in_cohort_dir, pattern))\n",
    "    if matching_files:\n",
    "        # Try to read each file and see if it has the expected format for clinical data\n",
    "        for file in matching_files:\n",
    "            try:\n",
    "                df = pd.read_csv(file, sep='\\t', nrows=5)\n",
    "                # If the file has multiple columns and rows, it's likely clinical data\n",
    "                if df.shape[1] > 1 and df.shape[0] > 0:\n",
    "                    clinical_file = file\n",
    "                    break\n",
    "            except Exception as e:\n",
    "                print(f\"Couldn't read {file} as tabular data: {e}\")\n",
    "                # Try with comma separator\n",
    "                try:\n",
    "                    df = pd.read_csv(file, nrows=5)\n",
    "                    if df.shape[1] > 1 and df.shape[0] > 0:\n",
    "                        clinical_file = file\n",
    "                        break\n",
    "                except:\n",
    "                    pass\n",
    "        if clinical_file:\n",
    "            break\n",
    "\n",
    "if clinical_file:\n",
    "    print(f\"Found clinical data file: {clinical_file}\")\n",
    "    try:\n",
    "        clinical_data = pd.read_csv(clinical_file, sep='\\t')\n",
    "    except:\n",
    "        clinical_data = pd.read_csv(clinical_file)\n",
    "    \n",
    "    # Preview the data to understand its structure\n",
    "    print(f\"Clinical data shape: {clinical_data.shape}\")\n",
    "    print(clinical_data.head())\n",
    "    \n",
    "    sample_chars = clinical_data.to_dict(orient='list')\n",
    "    unique_values = {i: list(set(val)) for i, val in enumerate(sample_chars.values())}\n",
    "    \n",
    "    # Print unique values to help with identification\n",
    "    for i, values in unique_values.items():\n",
    "        print(f\"Column {i}: {values[:5]}{'...' if len(values) > 5 else ''}\")\n",
    "else:\n",
    "    # If we still can't find a clinical file, try to look for a series matrix file\n",
    "    matrix_files = glob.glob(os.path.join(in_cohort_dir, '*series_matrix*'))\n",
    "    if matrix_files:\n",
    "        print(f\"Found series matrix file: {matrix_files[0]}\")\n",
    "        try:\n",
    "            # Series matrix files have characteristics in the header section\n",
    "            with open(matrix_files[0], 'r') as f:\n",
    "                lines = []\n",
    "                for line in f:\n",
    "                    if line.startswith('!Sample_characteristics'):\n",
    "                        lines.append(line.strip())\n",
    "                    if line.startswith('!series_matrix_table_begin'):\n",
    "                        break\n",
    "            \n",
    "            if lines:\n",
    "                # Create a DataFrame from the sample characteristics\n",
    "                samples = []\n",
    "                for line in lines:\n",
    "                    parts = line.split('\\t')\n",
    "                    if len(parts) > 1:\n",
    "                        samples.append(parts[1:])\n",
    "                \n",
    "                if samples:\n",
    "                    # Transpose the data to match expected format\n",
    "                    clinical_data = pd.DataFrame(samples).T\n",
    "                    sample_chars = clinical_data.to_dict(orient='list')\n",
    "                    unique_values = {i: list(set(val)) for i, val in enumerate(sample_chars.values())}\n",
    "                    print(\"Extracted clinical data from series matrix file\")\n",
    "        except Exception as e:\n",
    "            print(f\"Error reading series matrix file: {e}\")\n",
    "\n",
    "# If we still don't have clinical data, mark the dataset as not usable\n",
    "if 'clinical_data' not in locals() or clinical_data.empty:\n",
    "    is_gene_available = False\n",
    "    trait_row = None\n",
    "    is_usable = 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=(trait_row is not None)\n",
    "    )\n",
    "    print(f\"No usable clinical data found. Dataset marked as not usable.\")\n",
    "    exit()\n",
    "\n",
    "# Assume that if we have a file with .CEL or .txt extension, we likely have gene expression data\n",
    "gene_files = [f for f in files if f.endswith('.CEL') or f.endswith('.txt') or \n",
    "              f.endswith('.csv') or 'expression' in f.lower()]\n",
    "is_gene_available = len(gene_files) > 0\n",
    "print(f\"Gene expression data available: {is_gene_available}\")\n",
    "\n",
    "# Now let's examine the clinical data to find trait, age, and gender\n",
    "trait_row = None\n",
    "age_row = None\n",
    "gender_row = None\n",
    "\n",
    "# Define conversion functions\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait value to binary (0/1)\"\"\"\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    # Convert to string if it's not already\n",
    "    value = str(value)\n",
    "    # Split by colon if it exists\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    # Convert to lowercase for case-insensitive comparison\n",
    "    value_lower = value.lower()\n",
    "    \n",
    "    # Map values to binary (0 = control, 1 = case)\n",
    "    if any(term in value_lower for term in [\"healthy\", \"control\", \"normal\", \"non-atopic\"]):\n",
    "        return 0\n",
    "    elif any(term in value_lower for term in [\"eczema\", \"ad\", \"atopic dermatitis\", \"atopic\"]):\n",
    "        return 1\n",
    "    return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age value to continuous numeric value\"\"\"\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    # Convert to string if it's not already\n",
    "    value = str(value)\n",
    "    # Split by colon if it exists\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Try to extract numeric value\n",
    "    import re\n",
    "    numbers = re.findall(r'\\d+(?:\\.\\d+)?', value)\n",
    "    if numbers:\n",
    "        return float(numbers[0])\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender value to binary (0 = female, 1 = male)\"\"\"\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    # Convert to string if it's not already\n",
    "    value = str(value)\n",
    "    # Split by colon if it exists\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Convert to lowercase for case-insensitive comparison\n",
    "    value_lower = value.lower()\n",
    "    \n",
    "    if any(term in value_lower for term in [\"female\", \"f\", \"woman\", \"girl\"]):\n",
    "        return 0\n",
    "    elif any(term in value_lower for term in [\"male\", \"m\", \"man\", \"boy\"]):\n",
    "        return 1\n",
    "    return None\n",
    "\n",
    "# Examine the unique values to find trait, age, and gender data\n",
    "for i, values in unique_values.items():\n",
    "    # Convert values to string if they aren't already\n",
    "    values_str = [str(v) for v in values if v is not None and not pd.isna(v)]\n",
    "    if not values_str:\n",
    "        continue\n",
    "        \n",
    "    values_joined = ' '.join(values_str).lower()\n",
    "    col_name = clinical_data.columns[i] if i < len(clinical_data.columns) else f\"Column {i}\"\n",
    "    print(f\"Examining column {i} ({col_name}): {values_str[:3]}\")\n",
    "    \n",
    "    # Look for trait-related keywords\n",
    "    if any(keyword in values_joined for keyword in [\"eczema\", \"ad\", \"atopic dermatitis\", \"atopic\", \"healthy\", \"control\"]):\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3f3c5e25",
   "metadata": {},
   "source": [
    "### Step 4: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "35ca033d",
   "metadata": {},
   "outputs": [],
   "source": [
    "I'll debug the code and make sure it properly processes the GEO series matrix file to extract clinical data.\n",
    "\n",
    "```python\n",
    "# Let's examine the dataset information by parsing the GEO series matrix file\n",
    "import pandas as pd\n",
    "import os\n",
    "import json\n",
    "import gzip\n",
    "import re\n",
    "from typing import Optional, Callable, Dict, Any\n",
    "\n",
    "# First, let's check the available files in the cohort directory\n",
    "cohort_files = os.listdir(in_cohort_dir)\n",
    "print(f\"Files in the cohort directory: {cohort_files}\")\n",
    "\n",
    "# Parse the GEO series matrix file\n",
    "matrix_file_path = os.path.join(in_cohort_dir, \"GSE61225_series_matrix.txt.gz\")\n",
    "is_gene_available = False\n",
    "clinical_data = None\n",
    "background_info = \"\"\n",
    "\n",
    "if os.path.exists(matrix_file_path):\n",
    "    print(\"Found GEO series matrix file, parsing...\")\n",
    "    \n",
    "    # Read the gzipped file\n",
    "    with gzip.open(matrix_file_path, 'rt') as f:\n",
    "        lines = f.readlines()\n",
    "    \n",
    "    # Extract background information and sample characteristics\n",
    "    sample_char_dict = {}\n",
    "    reading_sample_char = False\n",
    "    sample_id_line = None\n",
    "    \n",
    "    for i, line in enumerate(lines):\n",
    "        line = line.strip()\n",
    "        \n",
    "        # Collect background information\n",
    "        if line.startswith(\"!Series_\"):\n",
    "            background_info += line + \"\\n\"\n",
    "        \n",
    "        # Identify sample characteristics section\n",
    "        if line.startswith(\"!Sample_characteristics_ch1\"):\n",
    "            reading_sample_char = True\n",
    "            char_name = line.split('\\t')[1].strip('\"')\n",
    "            sample_char_dict[i] = [char_name] + [v.strip('\"') for v in line.split('\\t')[2:]]\n",
    "        elif reading_sample_char and line.startswith(\"!Sample_\"):\n",
    "            if not line.startswith(\"!Sample_characteristics_ch1\"):\n",
    "                reading_sample_char = False\n",
    "            else:\n",
    "                char_name = line.split('\\t')[1].strip('\"')\n",
    "                sample_char_dict[i] = [char_name] + [v.strip('\"') for v in line.split('\\t')[2:]]\n",
    "        \n",
    "        # Identify sample ID line\n",
    "        if line.startswith(\"!Sample_geo_accession\"):\n",
    "            sample_id_line = [col.strip('\"') for col in line.split('\\t')[1:]]\n",
    "        \n",
    "        # Check if the file likely contains gene expression data\n",
    "        if line.startswith(\"!Platform_technology\") and \"expression\" in line.lower():\n",
    "            is_gene_available = True\n",
    "        \n",
    "        # Identify the start of the gene expression data section\n",
    "        if line.startswith(\"!series_matrix_table_begin\"):\n",
    "            is_gene_available = True\n",
    "            break\n",
    "    \n",
    "    # Create a DataFrame from sample characteristics\n",
    "    if sample_char_dict and sample_id_line:\n",
    "        clinical_data_rows = []\n",
    "        for row_idx, char_data in sample_char_dict.items():\n",
    "            if len(char_data) >= len(sample_id_line):\n",
    "                clinical_data_rows.append(char_data[:len(sample_id_line)])\n",
    "        \n",
    "        if clinical_data_rows:\n",
    "            clinical_data = pd.DataFrame(clinical_data_rows)\n",
    "            if sample_id_line:\n",
    "                clinical_data.columns = ['Description'] + sample_id_line[1:]\n",
    "    \n",
    "    print(\"Finished parsing GEO series matrix file\")\n",
    "\n",
    "# Display the extracted information\n",
    "if clinical_data is not None:\n",
    "    print(\"\\nSample characteristics preview:\")\n",
    "    print(clinical_data.head())\n",
    "    \n",
    "    # Print unique values for each row to understand the data better\n",
    "    for i in range(len(clinical_data)):\n",
    "        unique_values = clinical_data.iloc[i, 1:].unique()\n",
    "        print(f\"Row {i}: {clinical_data.iloc[i, 0]}\")\n",
    "        print(f\"Unique values: {unique_values[:5]}{'...' if len(unique_values) > 5 else ''}\")\n",
    "        print()\n",
    "else:\n",
    "    print(\"No sample characteristics found in the GEO series matrix file\")\n",
    "\n",
    "print(\"\\nBackground information snippet:\")\n",
    "print(background_info[:500] + \"...\" if len(background_info) > 500 else background_info)\n",
    "\n",
    "print(f\"\\nGene expression data available: {is_gene_available}\")\n",
    "\n",
    "# Define conversion functions based on the data analysis\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert eczema trait information to binary (0: healthy control, 1: eczema)\"\"\"\n",
    "    if pd.isna(value) or value is None:\n",
    "        return None\n",
    "    \n",
    "    value = str(value).lower()\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    if 'non-lesional' in value or 'non lesional' in value or 'nonlesional' in value:\n",
    "        return 1  # Non-lesional skin from eczema patients\n",
    "    elif 'lesional' in value:\n",
    "        return 1  # Lesional skin from eczema patients\n",
    "    elif 'healthy' in value or 'control' in value or 'normal' in value:\n",
    "        return 0  # Healthy control\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age information to continuous numeric value\"\"\"\n",
    "    if pd.isna(value) or value is None:\n",
    "        return None\n",
    "    \n",
    "    value = str(value)\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Try to extract numeric age\n",
    "    age_match = re.search(r'(\\d+)', value)\n",
    "    if age_match:\n",
    "        return float(age_match.group(1))\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender information to binary (0: female, 1: male)\"\"\"\n",
    "    if pd.isna(value) or value is None:\n",
    "        return None\n",
    "    \n",
    "    value = str(value).lower()\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    if 'female' in value or 'f' == value.strip():\n",
    "        return 0\n",
    "    elif 'male' in value or 'm' == value.strip():\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# Based on the data analysis, set the row indices for trait, age, and gender\n",
    "trait_row = None\n",
    "age_row = None\n",
    "gender_row = None\n",
    "\n",
    "# If clinical data is available, determine which rows contain trait, age, and gender\n",
    "if clinical_data is not None:\n",
    "    # Identify trait row\n",
    "    for i in range(len(clinical_data)):\n",
    "        row_label = str(clinical_data.iloc[i, 0]).lower()\n",
    "        unique_values = clinical_data.iloc[i, 1:].unique()\n",
    "        \n",
    "        # Check for trait information\n",
    "        if ('disease' in row_label or 'status' in row_label or 'diagnosis' in row_label or \n",
    "            'condition' in row_label or 'skin' in row_label or 'health' in row_label or \n",
    "            'lesion' in row_label or 'source' in row_label or 'sample' in row_label):\n",
    "            # Test if we can convert some values\n",
    "            test_conversions = [convert_trait(val) for val in unique_values if not pd.isna(val)]\n",
    "            if any(v is not None for v in test_conversions) and len(set(test_conversions) - {None}) > 1:\n",
    "                trait_row = i\n",
    "                print(f\"Found trait information in row {i}: {row_label}\")\n",
    "                print(f\"Unique values: {unique_values}\")\n",
    "                print(f\"Converted values: {test_conversions}\")\n",
    "        \n",
    "        # Check for age information\n",
    "        if 'age' in row_label:\n",
    "            # Test if we can convert some values\n",
    "            test_conversions = [convert_age(val) for val in unique_values if not pd.isna(val)]\n",
    "            if any(v is not None for v in test_conversions) and len(set(test_conversions) - {None}) > 1:\n",
    "                age_row = i\n",
    "                print(f\"Found age information in row {i}: {row_label}\")\n",
    "        \n",
    "        # Check for gender information\n",
    "        if 'gender' in row_label or '\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f8d74aeb",
   "metadata": {},
   "source": [
    "### Step 5: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4d010d3c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Get the SOFT and matrix file paths again \n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "print(f\"Matrix file found: {matrix_file}\")\n",
    "\n",
    "# 2. Use the get_genetic_data function from the library to get the gene_data\n",
    "try:\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    print(f\"Gene data shape: {gene_data.shape}\")\n",
    "    \n",
    "    # 3. Print the first 20 row IDs (gene or probe identifiers)\n",
    "    print(\"First 20 gene/probe identifiers:\")\n",
    "    print(gene_data.index[:20])\n",
    "except Exception as e:\n",
    "    print(f\"Error extracting gene data: {e}\")"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}