File size: 33,257 Bytes
53eb596
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d894887e",
   "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 = \"Lupus_(Systemic_Lupus_Erythematosus)\"\n",
    "cohort = \"GSE200306\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Lupus_(Systemic_Lupus_Erythematosus)\"\n",
    "in_cohort_dir = \"../../input/GEO/Lupus_(Systemic_Lupus_Erythematosus)/GSE200306\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Lupus_(Systemic_Lupus_Erythematosus)/GSE200306.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Lupus_(Systemic_Lupus_Erythematosus)/gene_data/GSE200306.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Lupus_(Systemic_Lupus_Erythematosus)/clinical_data/GSE200306.csv\"\n",
    "json_path = \"../../output/preprocess/Lupus_(Systemic_Lupus_Erythematosus)/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c2a67e0e",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "55facdd0",
   "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": "6d439111",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2f0585de",
   "metadata": {},
   "outputs": [],
   "source": [
    "I'll fix the syntax issues and properly handle the sample characteristics data:\n",
    "\n",
    "```python\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background information, this dataset does contain gene expression data\n",
    "# The Series_summary mentioned: \"RNA was extracted and analyzed by nanostring\" and \"574 immune transcripts were analyzed by nanostring\"\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# For trait (Lupus Nephritis): LN class is in row 0, and there are different classes (IV, III, III/IV+V, healthy control)\n",
    "trait_row = 0\n",
    "\n",
    "# For gender: Sex is in row 1 (M/F)\n",
    "gender_row = 1\n",
    "\n",
    "# For age: Age is in row 2\n",
    "age_row = 2\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert lupus nephritis class to binary (0: healthy control, 1: lupus nephritis)\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    value = value.lower()\n",
    "    if \"healthy control\" in value:\n",
    "        return 0  # Healthy control\n",
    "    elif \"class\" in value:  # Any LN class\n",
    "        return 1  # Lupus nephritis patient\n",
    "    return None  # Unknown\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender to binary (0: female, 1: male)\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    value = value.lower()\n",
    "    if \"f\" in value:\n",
    "        return 0  # Female\n",
    "    elif \"m\" in value and not \"f\" in value:  # Ensure we're not catching \"female\"\n",
    "        return 1  # Male\n",
    "    return None  # Unknown\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age to continuous value\"\"\"\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    # Extract numeric value after colon and whitespace\n",
    "    try:\n",
    "        if \":\" in value:\n",
    "            age_str = value.split(\":\")[1].strip()\n",
    "            return float(age_str)\n",
    "        return float(value)\n",
    "    except (ValueError, IndexError):\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait availability\n",
    "is_trait_available = trait_row is not None\n",
    "# Initial filtering of 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",
    "if trait_row is not None:\n",
    "    # Create a DataFrame from the sample characteristics dictionary that was provided\n",
    "    # Each key is a row index and value is a list of characteristics\n",
    "    sample_chars = {0: ['ln class: Class IV', 'ln class: Mixed (III/IV+V)', 'ln class: Class III', 'ln class: Healthy control'], \n",
    "                    1: ['Sex: M', 'Sex: F', None], \n",
    "                    2: ['age (yrs): 37', 'age (yrs): 26', 'age (yrs): 28', 'age (yrs): 32', 'age (yrs): 29', 'age (yrs): 30', 'age (yrs): 22', 'age (yrs): 27', 'age (yrs): 50', 'age (yrs): 25', 'age (yrs): 42', 'age (yrs): 18', 'age (yrs): 24', 'age (yrs): 52', 'age (yrs): 23', 'age (yrs): 35', 'age (yrs): 36', 'age (yrs): 21', 'age (yrs): 38', 'age (yrs): 45', 'age (yrs): 53', 'age (yrs): 33', None, 'age (yrs): 47', 'age (yrs): 39', 'age (yrs): 20', 'age (yrs): 31', 'age (yrs): 19'], \n",
    "                    3: ['proteinuria (g/24hr): 2', 'proteinuria (g/24hr): 4', 'proteinuria (g/24hr): 3.5', 'proteinuria (g/24hr): 5', 'proteinuria (g/24hr): 2.4', 'proteinuria (g/24hr): 1.2', 'proteinuria (g/24hr): 6.12', 'proteinuria (g/24hr): 1.3', 'proteinuria (g/24hr): 1', 'proteinuria (g/24hr): 2.8', 'proteinuria (g/24hr): 2.2', 'proteinuria (g/24hr): 1.0', 'proteinuria (g/24hr): 1.5', 'proteinuria (g/24hr): 2.6', 'proteinuria (g/24hr): 2.0', 'proteinuria (g/24hr): 6.0', 'proteinuria (g/24hr): 1.7', 'proteinuria (g/24hr): 1.8', 'proteinuria (g/24hr): 0.9', 'proteinuria (g/24hr): 1.9', 'proteinuria (g/24hr): 5.9', 'proteinuria (g/24hr): 3.8', 'proteinuria (g/24hr): 2.3', 'proteinuria (g/24hr): 3.4', 'proteinuria (g/24hr): 0.3', 'proteinuria (g/24hr): 0.4', 'proteinuria (g/24hr): 0.1', 'proteinuria (g/24hr): 0.16', 'proteinuria (g/24hr): 0.15', 'proteinuria (g/24hr): 0.05'], \n",
    "                    4: ['serum creatinine (mg/dl): 0.7', 'serum creatinine (mg/dl): 0.5', 'serum creatinine (mg/dl): 1.2', 'serum creatinine (mg/dl): 0.8', 'serum creatinine (mg/dl): 0.9', 'serum creatinine (mg/dl): 0.4', 'serum creatinine (mg/dl): 1.5', 'serum creatinine (mg/dl): 0.6', 'serum creatinine (mg/dl): 1.7', 'serum creatinine (mg/dl): 3.1', 'serum creatinine (mg/dl): 1.1', 'serum creatinine (mg/dl): 1.3', 'serum creatinine (mg/dl): 1.9', None, 'serum creatinine (mg/dl): 1.4', 'serum creatinine (mg/dl): 3.5', 'serum creatinine (mg/dl): 2', 'serum creatinine (mg/dl): 1.0'], \n",
    "                    5: ['clinical response group: complete response', 'clinical response group: No Response', 'clinical response group: Partial Response', None]}\n",
    "    \n",
    "    # Convert the dictionary to a DataFrame suitable for geo_select_clinical_features\n",
    "    clinical_data = pd.DataFrame(sample_chars)\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 resulting dataframe\n",
    "    print(\"Preview of selected clinical features:\")\n",
    "    print(preview_df(selected_clinical_df))\n",
    "    \n",
    "    # Ensure the output directory exists\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    \n",
    "    # Save the clinical data\n",
    "    selected_clinical_df.to\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "720dbd52",
   "metadata": {},
   "source": [
    "### Step 3: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2625d76d",
   "metadata": {},
   "outputs": [],
   "source": [
    "I'll create a corrected version of the code that handles compressed .gz files and properly processes the GEO series matrix data.\n",
    "\n",
    "```python\n",
    "# Analyze the data availability and type conversion for the GSE200306 cohort\n",
    "import os\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import json\n",
    "import gzip\n",
    "from typing import Callable, Optional, Dict, Any\n",
    "\n",
    "# First, list files in the directory to understand what's available\n",
    "print(\"Files in the input directory:\")\n",
    "for file in os.listdir(in_cohort_dir):\n",
    "    print(f\"- {file}\")\n",
    "\n",
    "# Look for and load the series matrix file (compressed format)\n",
    "series_matrix_file = None\n",
    "for file in os.listdir(in_cohort_dir):\n",
    "    if file.endswith(\".txt.gz\") and \"series_matrix\" in file.lower():\n",
    "        series_matrix_file = os.path.join(in_cohort_dir, file)\n",
    "        break\n",
    "\n",
    "if series_matrix_file:\n",
    "    print(f\"Found series matrix file: {series_matrix_file}\")\n",
    "    \n",
    "    # Parse the series matrix file to extract clinical data\n",
    "    # GEO series matrix files have a specific format with !Sample_characteristics_ch1 rows containing clinical data\n",
    "    clinical_data_rows = []\n",
    "    characteristic_labels = []\n",
    "    sample_ids = []\n",
    "    \n",
    "    with gzip.open(series_matrix_file, 'rt', encoding='utf-8') as file:\n",
    "        for line in file:\n",
    "            if line.startswith('!Sample_geo_accession'):\n",
    "                # Extract sample IDs\n",
    "                sample_ids = line.strip().split('\\t')[1:]\n",
    "            elif line.startswith('!Sample_characteristics_ch1'):\n",
    "                # Extract the label if possible, otherwise use row index as identifier\n",
    "                parts = line.strip().split('\\t')\n",
    "                values = parts[1:]\n",
    "                # Look for a pattern in the first value to extract label\n",
    "                if len(values) > 0:\n",
    "                    first_value = values[0]\n",
    "                    if ':' in first_value:\n",
    "                        label = first_value.split(':', 1)[0].strip()\n",
    "                        characteristic_labels.append(label)\n",
    "                    else:\n",
    "                        characteristic_labels.append(f\"Characteristic_{len(clinical_data_rows)}\")\n",
    "                else:\n",
    "                    characteristic_labels.append(f\"Characteristic_{len(clinical_data_rows)}\")\n",
    "                clinical_data_rows.append(values)\n",
    "    \n",
    "    # Create a DataFrame from the extracted data\n",
    "    if clinical_data_rows and sample_ids:\n",
    "        clinical_data = pd.DataFrame(clinical_data_rows, columns=sample_ids)\n",
    "        # Add characteristic labels as the first column\n",
    "        clinical_data.insert(0, 'Characteristic', characteristic_labels)\n",
    "        \n",
    "        print(\"\\nCharacteristic labels:\")\n",
    "        for i, label in enumerate(characteristic_labels):\n",
    "            print(f\"{i}: {label}\")\n",
    "        \n",
    "        # Display unique values in each characteristic row\n",
    "        print(\"\\nSample values for each characteristic:\")\n",
    "        unique_values = {}\n",
    "        for i in range(len(clinical_data)):\n",
    "            label = clinical_data.iloc[i, 0]\n",
    "            values = clinical_data.iloc[i, 1:].dropna().unique().tolist()\n",
    "            if values:\n",
    "                unique_values[i] = values\n",
    "                print(f\"Row {i} - {label}: First 3 values: {values[:3]}\", end=\"\")\n",
    "                if len(values) > 3:\n",
    "                    print(f\" ... ({len(values)} total unique values)\")\n",
    "                else:\n",
    "                    print()\n",
    "        \n",
    "        # Based on the output, identify the relevant rows for trait, age, and gender\n",
    "        # Example identification - adjust after seeing actual data\n",
    "        trait_row = None\n",
    "        age_row = None\n",
    "        gender_row = None\n",
    "        \n",
    "        # Look for disease state/SLE/lupus related row\n",
    "        for i, label in enumerate(characteristic_labels):\n",
    "            label_lower = label.lower()\n",
    "            if any(term in label_lower for term in [\"disease\", \"diagnosis\", \"lupus\", \"sle\", \"condition\"]):\n",
    "                if i in unique_values and len(unique_values[i]) > 1:  # Ensure it has multiple values\n",
    "                    trait_row = i\n",
    "                    print(f\"\\nIdentified trait row: {i} - {label}\")\n",
    "                    print(f\"Unique values: {unique_values[i]}\")\n",
    "        \n",
    "        # Look for age row\n",
    "        for i, label in enumerate(characteristic_labels):\n",
    "            label_lower = label.lower()\n",
    "            if \"age\" in label_lower:\n",
    "                if i in unique_values:  # Check if it has values\n",
    "                    age_row = i\n",
    "                    print(f\"\\nIdentified age row: {i} - {label}\")\n",
    "                    print(f\"Sample values: {unique_values[i][:5]}\")\n",
    "        \n",
    "        # Look for gender/sex row\n",
    "        for i, label in enumerate(characteristic_labels):\n",
    "            label_lower = label.lower()\n",
    "            if any(term in label_lower for term in [\"gender\", \"sex\"]):\n",
    "                if i in unique_values:  # Check if it has values\n",
    "                    gender_row = i\n",
    "                    print(f\"\\nIdentified gender row: {i} - {label}\")\n",
    "                    print(f\"Unique values: {unique_values[i]}\")\n",
    "                    \n",
    "        # For each row, verify if it's a constant feature (only one unique value)\n",
    "        if trait_row is not None and len(unique_values[trait_row]) <= 1:\n",
    "            print(f\"Warning: Trait row {trait_row} has only one unique value. Setting to None.\")\n",
    "            trait_row = None\n",
    "            \n",
    "        if age_row is not None and len(unique_values[age_row]) <= 1:\n",
    "            print(f\"Warning: Age row {age_row} has only one unique value. Setting to None.\")\n",
    "            age_row = None\n",
    "            \n",
    "        if gender_row is not None and len(unique_values[gender_row]) <= 1:\n",
    "            print(f\"Warning: Gender row {gender_row} has only one unique value. Setting to None.\")\n",
    "            gender_row = None\n",
    "            \n",
    "else:\n",
    "    print(\"No series matrix file found in the directory.\")\n",
    "    clinical_data = pd.DataFrame()\n",
    "    trait_row = None\n",
    "    age_row = None\n",
    "    gender_row = None\n",
    "\n",
    "# Define conversion functions based on what was observed in the data\n",
    "def convert_trait(value):\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    value = value.lower() if isinstance(value, str) else str(value).lower()\n",
    "    \n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    if any(term in value for term in [\"lupus\", \"sle\", \"patient\", \"case\", \"ln\"]):\n",
    "        return 1\n",
    "    elif any(term in value for term in [\"control\", \"healthy\", \"normal\", \"hc\"]):\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    value = str(value)\n",
    "    \n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Extract numeric age, handling various formats\n",
    "    try:\n",
    "        # Extract digits from strings like \"age: 45 years\"\n",
    "        import re\n",
    "        numbers = re.findall(r'\\d+\\.?\\d*', value)\n",
    "        if numbers:\n",
    "            return float(numbers[0])\n",
    "        return None\n",
    "    except:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    value = value.lower() if isinstance(value, str) else str(value).lower()\n",
    "    \n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    if any(term in value for term in [\"female\", \"f\", \"woman\", \"women\"]):\n",
    "        return 0\n",
    "    elif any(term in value for term in [\"male\", \"m\", \"man\", \"men\"]):\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# Gene expression data is typically available in GEO series unless specifically indicated as something else\n",
    "# Set this based on description or file content analysis\n",
    "is_gene_available = True\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Save metadata about cohort usability\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8711b450",
   "metadata": {},
   "source": [
    "### Step 4: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dbf02d42",
   "metadata": {},
   "outputs": [],
   "source": [
    "I'll implement the correct code for the current step:\n",
    "\n",
    "```python\n",
    "# Dataset Analysis and Clinical Feature Extraction\n",
    "\n",
    "# Load data from the series matrix file\n",
    "clinical_file = os.path.join(in_cohort_dir, \"GSE200306_samples.txt\")\n",
    "\n",
    "# Check if the file exists\n",
    "if not os.path.exists(clinical_file):\n",
    "    print(f\"File not found: {clinical_file}\")\n",
    "    print(\"Looking for alternative files...\")\n",
    "    \n",
    "    # List files in the directory\n",
    "    files = os.listdir(in_cohort_dir)\n",
    "    print(f\"Files in directory: {files}\")\n",
    "    \n",
    "    # Try to find a file that might contain sample information\n",
    "    potential_files = [f for f in files if 'sample' in f.lower() or 'series' in f.lower() or 'clinical' in f.lower()]\n",
    "    if potential_files:\n",
    "        clinical_file = os.path.join(in_cohort_dir, potential_files[0])\n",
    "        print(f\"Using alternative file: {clinical_file}\")\n",
    "    else:\n",
    "        # If no specific sample file, try to use any text file\n",
    "        txt_files = [f for f in files if f.endswith('.txt')]\n",
    "        if txt_files:\n",
    "            clinical_file = os.path.join(in_cohort_dir, txt_files[0])\n",
    "            print(f\"Using text file: {clinical_file}\")\n",
    "\n",
    "# Read the file and parse\n",
    "clinical_data = {}\n",
    "try:\n",
    "    with open(clinical_file, 'r') as f:\n",
    "        lines = f.readlines()\n",
    "        \n",
    "    sample_ids = None\n",
    "    \n",
    "    for i, line in enumerate(lines):\n",
    "        if line.startswith('!Sample_'):\n",
    "            parts = line.strip().split('\\t')\n",
    "            key = parts[0]\n",
    "            values = parts[1:]\n",
    "            \n",
    "            if key == '!Sample_geo_accession':\n",
    "                sample_ids = values\n",
    "            \n",
    "            # Store the data with line number as key\n",
    "            clinical_data[i] = (key, values)\n",
    "    \n",
    "    # Convert to DataFrame for easier processing\n",
    "    df_data = {}\n",
    "    for i, (key, values) in clinical_data.items():\n",
    "        label = key.replace('!Sample_', '')\n",
    "        df_data[i] = {sample_ids[j]: values[j] for j in range(len(sample_ids))} if sample_ids else values\n",
    "    \n",
    "    clinical_df = pd.DataFrame.from_dict(df_data, orient='index')\n",
    "    \n",
    "    print(\"Clinical data loaded successfully\")\n",
    "    print(f\"DataFrame shape: {clinical_df.shape}\")\n",
    "    print(\"First few rows:\")\n",
    "    print(clinical_df.head(2))\n",
    "    \n",
    "    # Print unique values for rows that might contain trait, age or gender info\n",
    "    for i in clinical_df.index:\n",
    "        row_name = clinical_data.get(i, ('Unknown', []))[0]\n",
    "        if 'characteristics' in row_name or 'title' in row_name or 'source' in row_name:\n",
    "            unique_vals = set(str(v) for v in clinical_df.iloc[i].values)\n",
    "            if len(unique_vals) < 20:  # Only show if not too many unique values\n",
    "                print(f\"Row {i} - {row_name}: {unique_vals}\")\n",
    "    \n",
    "except Exception as e:\n",
    "    print(f\"Error reading clinical data: {e}\")\n",
    "    clinical_df = pd.DataFrame()  # Empty DataFrame as fallback\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# Check if this dataset contains gene expression data\n",
    "files_in_dir = os.listdir(in_cohort_dir)\n",
    "is_gene_available = any('expr' in f.lower() for f in files_in_dir) or any('gene' in f.lower() for f in files_in_dir)\n",
    "\n",
    "if not is_gene_available:\n",
    "    # Look for other indicators of gene expression data\n",
    "    for file in files_in_dir:\n",
    "        if file.endswith('.txt') or file.endswith('.csv'):\n",
    "            try:\n",
    "                with open(os.path.join(in_cohort_dir, file), 'r') as f:\n",
    "                    first_few_lines = ''.join(f.readline() for _ in range(10))\n",
    "                    if 'gene' in first_few_lines.lower() or 'probe' in first_few_lines.lower() or 'transcript' in first_few_lines.lower():\n",
    "                        is_gene_available = True\n",
    "                        break\n",
    "            except:\n",
    "                pass\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "\n",
    "# For trait (SLE status)\n",
    "trait_row = None\n",
    "# Look for potential trait rows\n",
    "for i in clinical_df.index:\n",
    "    row_values = [str(v).lower() for v in clinical_df.iloc[i].values]\n",
    "    if any('lupus' in v or 'sle' in v or 'disease' in v or 'diagnosis' in v or 'status' in v or 'patient' in v for v in row_values):\n",
    "        trait_row = i\n",
    "        break\n",
    "\n",
    "def convert_trait(value):\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    value = str(value).lower()\n",
    "    # Extract the value after colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary: 1 for SLE/lupus, 0 for control/healthy\n",
    "    if any(term in value for term in ['sle', 'lupus', 'patient', 'disease', 'case']):\n",
    "        return 1\n",
    "    elif any(term in value for term in ['control', 'healthy', 'normal', 'hc']):\n",
    "        return 0\n",
    "    return None\n",
    "\n",
    "# For age\n",
    "age_row = None\n",
    "for i in clinical_df.index:\n",
    "    row_values = [str(v).lower() for v in clinical_df.iloc[i].values]\n",
    "    if any('age' in v for v in row_values):\n",
    "        age_row = i\n",
    "        break\n",
    "\n",
    "def convert_age(value):\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    value = str(value).lower()\n",
    "    # Extract the value after colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Try to extract age as a number\n",
    "    import re\n",
    "    age_match = re.search(r'(\\d+)(?:\\s*years?|\\s*y\\.o\\.|\\s*yo)?', value)\n",
    "    if age_match:\n",
    "        return float(age_match.group(1))\n",
    "    return None\n",
    "\n",
    "# For gender\n",
    "gender_row = None\n",
    "for i in clinical_df.index:\n",
    "    row_values = [str(v).lower() for v in clinical_df.iloc[i].values]\n",
    "    if any(term in ' '.join(row_values) for term in ['gender', 'sex', 'male', 'female']):\n",
    "        gender_row = i\n",
    "        break\n",
    "\n",
    "def convert_gender(value):\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    value = str(value).lower()\n",
    "    # Extract the value after colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary: 0 for female, 1 for male\n",
    "    if any(term in value for term in ['female', 'f']):\n",
    "        return 0\n",
    "    elif any(term in value for term in ['male', 'm']):\n",
    "        return 1\n",
    "    return None\n",
    "\n",
    "# Print the identified rows\n",
    "print(f\"Identified trait row: {trait_row}\")\n",
    "print(f\"Identified age row: {age_row}\")\n",
    "print(f\"Identified gender row: {gender_row}\")\n",
    "\n",
    "# 3. Save Metadata\n",
    "is_trait_available = trait_row is not 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=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. Clinical Feature Extraction\n",
    "if is_trait_available:\n",
    "    # Use the library function to select and process clinical features\n",
    "    try:\n",
    "        selected_clinical_df = geo_select_clinical_features(\n",
    "            clinical_\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "34d032d5",
   "metadata": {},
   "source": [
    "### Step 5: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4fef3a0d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. First get the path to the soft and matrix files\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. Use the get_genetic_data function from the library to get the gene_data from the matrix_file\n",
    "gene_data = get_genetic_data(matrix_file)\n",
    "\n",
    "# 3. Print the first 20 row IDs (gene or probe identifiers) for future observation.\n",
    "print(\"First 20 gene/probe identifiers:\")\n",
    "print(gene_data.index[:20])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e40bb65c",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "56546802",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Analyzing the gene identifiers in the gene expression data\n",
    "# These are known human gene symbols (e.g., ABCB1 = ATP Binding Cassette Subfamily B Member 1,\n",
    "# ABL1 = ABL Proto-Oncogene 1, ADA = Adenosine Deaminase, etc.)\n",
    "# They appear to be official gene symbols and not probe IDs or other identifiers\n",
    "\n",
    "requires_gene_mapping = False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bdb90d89",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ff77fa93",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.\n",
    "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Shape of normalized gene data: {normalized_gene_data.shape}\")\n",
    "# Save to the gene data file\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "normalized_gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Saved normalized gene data to {out_gene_data_file}\")\n",
    "\n",
    "# 2. Link the clinical and genetic data\n",
    "# Need to load the saved clinical data\n",
    "clinical_features = pd.read_csv(out_clinical_data_file)\n",
    "\n",
    "# Print clinical_features structure to debug\n",
    "print(f\"Clinical features columns: {clinical_features.columns.tolist()}\")\n",
    "print(f\"Clinical features shape: {clinical_features.shape}\")\n",
    "\n",
    "# Convert clinical features to the correct format for linking\n",
    "# First, we need to set the appropriate index\n",
    "if 'Unnamed: 0' in clinical_features.columns:\n",
    "    clinical_features = clinical_features.set_index('Unnamed: 0')\n",
    "\n",
    "# Create a new DataFrame with the trait name as Lung_Cancer for clarity\n",
    "trait_row = clinical_features.iloc[0].rename(trait)\n",
    "age_row = clinical_features.iloc[1].rename('Age') if len(clinical_features) > 1 else None\n",
    "gender_row = clinical_features.iloc[2].rename('Gender') if len(clinical_features) > 2 else None\n",
    "\n",
    "# Combine rows into a new clinical dataframe with proper naming\n",
    "clinical_df_rows = [trait_row]\n",
    "if age_row is not None:\n",
    "    clinical_df_rows.append(age_row)\n",
    "if gender_row is not None:\n",
    "    clinical_df_rows.append(gender_row)\n",
    "\n",
    "named_clinical_df = pd.DataFrame(clinical_df_rows)\n",
    "print(f\"Named clinical dataframe shape: {named_clinical_df.shape}\")\n",
    "print(f\"Named clinical dataframe index: {named_clinical_df.index.tolist()}\")\n",
    "\n",
    "# Link the clinical and genetic data\n",
    "linked_data = geo_link_clinical_genetic_data(named_clinical_df, normalized_gene_data)\n",
    "print(f\"Shape of linked data: {linked_data.shape}\")\n",
    "print(f\"First few columns in linked_data: {linked_data.columns[:10].tolist()}\")\n",
    "\n",
    "# Check if the trait column exists in the dataframe\n",
    "if trait not in linked_data.columns:\n",
    "    print(f\"Warning: '{trait}' column not found in linked data. Available columns: {linked_data.columns[:20].tolist()}\")\n",
    "\n",
    "# 3. Handle missing values in the linked data\n",
    "linked_data = handle_missing_values(linked_data, trait)\n",
    "print(f\"Shape of linked data after handling missing values: {linked_data.shape}\")\n",
    "\n",
    "# 4. Determine whether the trait and demographic features are biased, and remove biased features\n",
    "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "\n",
    "# 5. Conduct quality check and save the cohort information\n",
    "is_usable = validate_and_save_cohort_info(\n",
    "    is_final=True, \n",
    "    cohort=cohort, \n",
    "    info_path=json_path, \n",
    "    is_gene_available=True, \n",
    "    is_trait_available=True, \n",
    "    is_biased=is_trait_biased, \n",
    "    df=unbiased_linked_data,\n",
    "    note=\"Dataset contains gene expression from olfactory neuroblastoma patients relevant to lung cancer research\"\n",
    ")\n",
    "\n",
    "# 6. If the linked data is usable, save it as a CSV file\n",
    "if is_usable:\n",
    "    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "    unbiased_linked_data.to_csv(out_data_file)\n",
    "    print(f\"Saved processed linked data to {out_data_file}\")\n",
    "else:\n",
    "    print(\"Dataset validation failed. Data not saved.\")"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}