File size: 33,914 Bytes
92d2f89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5728adab",
   "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 = \"Arrhythmia\"\n",
    "cohort = \"GSE53622\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Arrhythmia\"\n",
    "in_cohort_dir = \"../../input/GEO/Arrhythmia/GSE53622\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Arrhythmia/GSE53622.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Arrhythmia/gene_data/GSE53622.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Arrhythmia/clinical_data/GSE53622.csv\"\n",
    "json_path = \"../../output/preprocess/Arrhythmia/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e0eab6e",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f5eec03c",
   "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": "2dc4220d",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d6ad9df0",
   "metadata": {},
   "outputs": [],
   "source": [
    "I'll provide the correct solution for step 2:\n",
    "\n",
    "```python\n",
    "# 1. Gene Expression Data Analysis\n",
    "# Based on the background information, this dataset contains lncRNA expression profiles, not typical gene expression.\n",
    "is_gene_available = False\n",
    "\n",
    "# 2. Data Availability and Type Conversion\n",
    "# 2.1 Data Availability\n",
    "\n",
    "# Trait data - Arrhythmia\n",
    "trait_row = 10  # 'arrhythmia: no', 'arrhythmia: yes'\n",
    "\n",
    "# Age data \n",
    "age_row = 1  # 'age: 66.4602739726027', etc.\n",
    "\n",
    "# Gender data\n",
    "gender_row = 2  # 'Sex: female', 'Sex: male'\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert arrhythmia status to binary values.\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip().lower()\n",
    "    \n",
    "    if value == \"yes\":\n",
    "        return 1\n",
    "    elif value == \"no\":\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age to a continuous numeric value.\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    try:\n",
    "        return float(value)\n",
    "    except (ValueError, TypeError):\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender to binary (0: female, 1: male).\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip().lower()\n",
    "    \n",
    "    if value == \"female\":\n",
    "        return 0\n",
    "    elif value == \"male\":\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save metadata for initial filtering\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",
    "    # Create a DataFrame from the sample characteristics dictionary\n",
    "    sample_characteristics_dict = {\n",
    "        0: ['patient id: ec302', 'patient id: ec303', 'patient id: ec305', 'patient id: ec306', 'patient id: ec325', 'patient id: ec326', 'patient id: ec330', 'patient id: ec331', 'patient id: ec308', 'patient id: ec309', 'patient id: ec311', 'patient id: ec312', 'patient id: ec315', 'patient id: ec316', 'patient id: ec317', 'patient id: ec318', 'patient id: ec319', 'patient id: ec321', 'patient id: ec322', 'patient id: ec324', 'patient id: ec333', 'patient id: ec334', 'patient id: ec337', 'patient id: ec338', 'patient id: ec340', 'patient id: ec341', 'patient id: ec342', 'patient id: ec347', 'patient id: ec353', 'patient id: ec355'],\n",
    "        1: ['age: 66.4602739726027', 'age: 64.013698630137', 'age: 50.9123287671233', 'age: 46.3287671232877', 'age: 53.9972602739726', 'age: 67.8438356164384', 'age: 64.8794520547945', 'age: 45.2219178082192', 'age: 54.4794520547945', 'age: 56.2328767123288', 'age: 57.0986301369863', 'age: 44.6630136986301', 'age: 43.7698630136986', 'age: 67.2739726027397', 'age: 68.2904109589041', 'age: 60.5068493150685', 'age: 48.4027397260274', 'age: 54.2931506849315', 'age: 51.9890410958904', 'age: 58.3205479452055', 'age: 66.2712328767123', 'age: 72.241095890411', 'age: 64.7506849315069', 'age: 54.5753424657534', 'age: 62.4383561643836', 'age: 66.1479452054794', 'age: 53.7424657534247', 'age: 56.9643835616438', 'age: 71.9150684931507', 'age: 53.5643835616438'],\n",
    "        2: ['Sex: female', 'Sex: male'],\n",
    "        3: ['tobacco use: no', 'tobacco use: yes'],\n",
    "        4: ['alcohol use: no', 'alcohol use: yes'],\n",
    "        5: ['tumor loation: middle', 'tumor loation: lower', 'tumor loation: upper'],\n",
    "        6: ['tumor grade: moderately', 'tumor grade: poorly', 'tumor grade: well'],\n",
    "        7: ['t stage: T3', 't stage: T1', 't stage: T2', 't stage: T4'],\n",
    "        8: ['n stage: N2', 'n stage: N0', 'n stage: N1', 'n stage: N3'],\n",
    "        9: ['tnm stage: III', 'tnm stage: II', 'tnm stage: I'],\n",
    "        10: ['arrhythmia: no', 'arrhythmia: yes'],\n",
    "        11: ['pneumonia: no', 'pneumonia: yes'],\n",
    "        12: ['anastomotic leak: no', 'anastomotic leak: yes'],\n",
    "        13: ['adjuvant therapy: yes', 'adjuvant therapy: no', 'adjuvant therapy: unknown'],\n",
    "        14: ['death at fu: yes', 'death at fu: no'],\n",
    "        15: ['survival time(months): 11.6333333333333', 'survival time(months): 58.2', 'survival time(months): 39.1666666666667', 'survival time(months): 57.7333333333333', 'survival time(months): 11.0666666666667', 'survival time(months): 55.2666666666667', 'survival time(months): 29.7', 'survival time(months): 10.9666666666667', 'survival time(months): 57.6', 'survival time(months): 57.5333333333333', 'survival time(months): 57.3666666666667', 'survival time(months): 57.2666666666667', 'survival time(months): 57.2333333333333', 'survival time(months): 13', 'survival time(months): 5.7', 'survival time(months): 56.6333333333333', 'survival time(months): 56.1333333333333', 'survival time(months): 55.6666666666667', 'survival time(months): 6.26666666666667', 'survival time(months): 25.4666666666667', 'survival time(months): 10.2', 'survival time(months): 13.1666666666667', 'survival time(months): 54.7333333333333', 'survival time(months): 18.0666666666667', 'survival time(months): 36.3', 'survival time(months): 54.1', 'survival time(months): 16.0333333333333', 'survival time(months): 52.9333333333333', 'survival time(months): 52.7', 'survival time(months): 8.46666666666667'],\n",
    "        16: ['disease state: esophageal squamous cell carcinoma'],\n",
    "        17: ['tissue: cancer tissue from patient 302', 'tissue: normal tissue from patient 302', 'tissue: cancer tissue from patient 303', 'tissue: normal tissue from patient 303', 'tissue: cancer tissue\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c05abbb2",
   "metadata": {},
   "source": [
    "### Step 3: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2ecca341",
   "metadata": {},
   "outputs": [],
   "source": [
    "I've analyzed the error and will provide a fixed and complete solution:\n",
    "\n",
    "```python\n",
    "import pandas as pd\n",
    "import os\n",
    "import json\n",
    "import numpy as np\n",
    "import re\n",
    "import glob\n",
    "from typing import Dict, Any, Optional, Callable\n",
    "\n",
    "# --- Step 1: Explore available files in the directory\n",
    "available_files = glob.glob(os.path.join(in_cohort_dir, \"*\"))\n",
    "print(f\"Available files in {in_cohort_dir}:\")\n",
    "for file in available_files:\n",
    "    print(f\"  - {os.path.basename(file)}\")\n",
    "\n",
    "# Look for potential series matrix files with different patterns\n",
    "series_files = [f for f in available_files if \"series_matrix\" in f.lower() or \"series\" in f.lower()]\n",
    "if not series_files:\n",
    "    # Try to find any text files\n",
    "    series_files = [f for f in available_files if f.endswith('.txt') or f.endswith('.csv')]\n",
    "\n",
    "if not series_files:\n",
    "    print(\"No suitable data files found. Cannot proceed with analysis.\")\n",
    "    # If we have any files, let's try to examine the content of the first one\n",
    "    if available_files:\n",
    "        sample_file = available_files[0]\n",
    "        print(f\"Examining content of {os.path.basename(sample_file)}:\")\n",
    "        try:\n",
    "            with open(sample_file, 'r') as f:\n",
    "                content_preview = [next(f) for _ in range(min(10, os.path.getsize(sample_file)))]\n",
    "                for line in content_preview:\n",
    "                    print(line.strip())\n",
    "        except Exception as e:\n",
    "            print(f\"Could not read file: {e}\")\n",
    "    \n",
    "    # Set variables to indicate data is not available\n",
    "    is_gene_available = False\n",
    "    is_trait_available = False\n",
    "else:\n",
    "    # Use the first found file\n",
    "    matrix_file_path = series_files[0]\n",
    "    print(f\"Using file: {os.path.basename(matrix_file_path)}\")\n",
    "    \n",
    "    # Attempt to extract information from the file\n",
    "    try:\n",
    "        # Read file content\n",
    "        with open(matrix_file_path, 'r') as file:\n",
    "            # Read the first several lines to analyze header info\n",
    "            header_lines = []\n",
    "            line_count = 0\n",
    "            max_lines = 200  # Read more lines to ensure we capture sample characteristics\n",
    "            \n",
    "            for line in file:\n",
    "                header_lines.append(line)\n",
    "                line_count += 1\n",
    "                if line_count >= max_lines:\n",
    "                    break\n",
    "        \n",
    "        # Check if this is likely gene expression data\n",
    "        platform_line = [line for line in header_lines if \"!Series_platform_id\" in line]\n",
    "        is_gene_available = True\n",
    "        \n",
    "        if platform_line:\n",
    "            platform_id = platform_line[0].split(\"=\")[1].strip().strip('\"')\n",
    "            print(f\"Platform ID: {platform_id}\")\n",
    "            # Check if platform suggests miRNA or methylation data\n",
    "            if \"mirna\" in platform_id.lower() or \"methylation\" in platform_id.lower():\n",
    "                print(\"Dataset appears to be miRNA or methylation data, not gene expression.\")\n",
    "                is_gene_available = False\n",
    "        \n",
    "        # Extract sample characteristics\n",
    "        sample_characteristics = {}\n",
    "        for i, line in enumerate(header_lines):\n",
    "            if line.startswith(\"!Sample_characteristics_ch1\"):\n",
    "                parts = line.strip().split('\\t')\n",
    "                if len(parts) > 1:\n",
    "                    if i not in sample_characteristics:\n",
    "                        sample_characteristics[i] = []\n",
    "                    for part in parts[1:]:\n",
    "                        sample_characteristics[i].append(part)\n",
    "        \n",
    "        # Check if sample characteristics were found\n",
    "        if not sample_characteristics:\n",
    "            print(\"No sample characteristics found in the file.\")\n",
    "            for i, line in enumerate(header_lines[:20]):\n",
    "                print(f\"Line {i}: {line.strip()}\")\n",
    "            is_trait_available = False\n",
    "        else:\n",
    "            # Print unique values for each row to help identify variables\n",
    "            print(\"\\nSample characteristics analysis:\")\n",
    "            for key, values in sample_characteristics.items():\n",
    "                unique_values = list(set(values))\n",
    "                print(f\"Row {key}: {unique_values[:5]}\")\n",
    "                if len(unique_values) > 5:\n",
    "                    print(f\"  ...and {len(unique_values)-5} more unique values\")\n",
    "            \n",
    "            # Load clinical data\n",
    "            clinical_data = pd.DataFrame()\n",
    "            for key, values in sample_characteristics.items():\n",
    "                clinical_data[key] = values\n",
    "            \n",
    "            # Based on inspection of sample characteristics, identify rows for trait, age, and gender\n",
    "            trait_row = None\n",
    "            age_row = None\n",
    "            gender_row = None\n",
    "            \n",
    "            # Look for row containing Arrhythmia information\n",
    "            for key, values in sample_characteristics.items():\n",
    "                unique_str = ' '.join(set([str(v).lower() for v in values]))\n",
    "                \n",
    "                # Check for trait information (Arrhythmia)\n",
    "                if any(term in unique_str for term in ['arrhythmia', 'disease', 'condition', 'patient', 'control', 'case']):\n",
    "                    trait_row = key\n",
    "                    print(f\"Found potential trait information in row {key}: {list(set(values))[:5]}\")\n",
    "                \n",
    "                # Check for age information\n",
    "                if any(term in unique_str for term in ['age', 'years']):\n",
    "                    age_row = key\n",
    "                    print(f\"Found potential age information in row {key}: {list(set(values))[:5]}\")\n",
    "                \n",
    "                # Check for gender information\n",
    "                if any(term in unique_str for term in ['gender', 'sex', 'male', 'female']):\n",
    "                    gender_row = key\n",
    "                    print(f\"Found potential gender information in row {key}: {list(set(values))[:5]}\")\n",
    "            \n",
    "            # Define conversion functions based on the identified data\n",
    "            def convert_trait(value):\n",
    "                \"\"\"Convert trait values to binary (0/1)\"\"\"\n",
    "                if value is None or pd.isna(value):\n",
    "                    return None\n",
    "                value = str(value).lower()\n",
    "                if ':' in value:\n",
    "                    value = value.split(':', 1)[1].strip()\n",
    "                \n",
    "                # Adapt based on the actual values in the dataset\n",
    "                if any(term in value for term in ['control', 'normal', 'healthy', 'no', 'negative']):\n",
    "                    return 0\n",
    "                elif any(term in value for term in ['arrhythmia', 'disease', 'patient', 'yes', 'positive']):\n",
    "                    return 1\n",
    "                else:\n",
    "                    return None\n",
    "            \n",
    "            def convert_age(value):\n",
    "                \"\"\"Convert age values to continuous numeric form\"\"\"\n",
    "                if value is None or pd.isna(value):\n",
    "                    return None\n",
    "                value = str(value)\n",
    "                if ':' in value:\n",
    "                    value = value.split(':', 1)[1].strip()\n",
    "                \n",
    "                # Extract numeric age using regex\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 values to binary (0 for female, 1 for male)\"\"\"\n",
    "                if value is None or pd.isna(value):\n",
    "                    return None\n",
    "                value = str(value).lower()\n",
    "                if ':' in value:\n",
    "                    value = value.split(':', 1)[1].strip()\n",
    "                \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",
    "                else:\n",
    "                    return None\n",
    "            \n",
    "            is_trait_available = trait_row is not None\n",
    "            \n",
    "            # Save metadata for initial filtering\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",
    "            # Extract clinical features if trait data is available\n",
    "            if is_trait_available:\n",
    "                selected_clinical_df = geo_select_clinical_features(\n",
    "                    clinical_df=clinical_data,\n",
    "                    trait=trait,\n",
    "                    trait_\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0acb2393",
   "metadata": {},
   "source": [
    "### Step 4: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dc77b2d0",
   "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}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0273c6ce",
   "metadata": {},
   "source": [
    "### Step 5: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e9893739",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Review the gene identifiers shown in the output\n",
    "# These appear to be numeric identifiers (1, 2, 24, 25...) rather than standard human gene symbols\n",
    "# Standard human gene symbols would typically be alphabetic like BRCA1, TP53, etc.\n",
    "# Therefore, these identifiers need to be mapped to gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cbcc3900",
   "metadata": {},
   "source": [
    "### Step 6: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "306ef120",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "\n",
    "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
    "print(\"\\nGene annotation preview:\")\n",
    "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
    "print(preview_df(gene_annotation, n=5))\n",
    "\n",
    "# Check for gene information in the SPOT_ID.1 column which appears to contain gene names\n",
    "print(\"\\nAnalyzing SPOT_ID.1 column for gene symbols:\")\n",
    "if 'SPOT_ID.1' in gene_annotation.columns:\n",
    "    # Extract a few sample values\n",
    "    sample_values = gene_annotation['SPOT_ID.1'].head(3).tolist()\n",
    "    for i, value in enumerate(sample_values):\n",
    "        print(f\"Sample {i+1} excerpt: {value[:200]}...\")  # Print first 200 chars\n",
    "        # Test the extract_human_gene_symbols function on these values\n",
    "        symbols = extract_human_gene_symbols(value)\n",
    "        print(f\"  Extracted gene symbols: {symbols}\")\n",
    "\n",
    "# Try to find the probe IDs in the gene annotation\n",
    "gene_data_id_prefix = gene_data.index[0].split('_')[0]  # Get prefix of first gene ID\n",
    "print(f\"\\nGene data ID prefix: {gene_data_id_prefix}\")\n",
    "\n",
    "# Look for columns that might match the gene data IDs\n",
    "for col in gene_annotation.columns:\n",
    "    if gene_annotation[col].astype(str).str.contains(gene_data_id_prefix).any():\n",
    "        print(f\"Column '{col}' contains values matching gene data ID pattern\")\n",
    "\n",
    "# Check if there's any column that might contain transcript or gene IDs\n",
    "print(\"\\nChecking for columns containing transcript or gene related terms:\")\n",
    "for col in gene_annotation.columns:\n",
    "    if any(term in col.upper() for term in ['GENE', 'TRANSCRIPT', 'SYMBOL', 'NAME', 'DESCRIPTION']):\n",
    "        print(f\"Column '{col}' may contain gene-related information\")\n",
    "        # Show sample values\n",
    "        print(f\"Sample values: {gene_annotation[col].head(3).tolist()}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "72559510",
   "metadata": {},
   "source": [
    "### Step 7: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9d097843",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Analyze the structure of the gene data identifiers\n",
    "print(\"Gene data index structure:\")\n",
    "print(gene_data.index[:5].tolist())\n",
    "\n",
    "# First, we need to determine if the SPOT_ID column in gene_annotation might contain gene symbols\n",
    "# Check if there's a relationship between gene_data index and gene_annotation ID\n",
    "gene_id_set = set(gene_data.index.astype(str))\n",
    "annotation_id_set = set(gene_annotation['ID'].astype(str))\n",
    "\n",
    "# Check the overlap between gene_data IDs and gene_annotation IDs\n",
    "overlap = gene_id_set.intersection(annotation_id_set)\n",
    "print(f\"\\nOverlap between gene data IDs and gene annotation IDs: {len(overlap)} IDs\")\n",
    "print(f\"Example overlapping IDs: {list(overlap)[:5] if overlap else 'None'}\")\n",
    "\n",
    "# Since we don't have clear gene symbols in our annotation, we'll check if the SPOT_ID column might contain information\n",
    "# that can be parsed to extract gene symbols\n",
    "print(\"\\nAnalyzing SPOT_ID column for potential gene information:\")\n",
    "spot_id_examples = gene_annotation['SPOT_ID'].dropna().head(10).tolist()\n",
    "print(f\"SPOT_ID examples: {spot_id_examples}\")\n",
    "\n",
    "# Try to extract gene symbols from SPOT_ID values\n",
    "gene_symbols_extracted = [extract_human_gene_symbols(str(id_val)) for id_val in spot_id_examples]\n",
    "print(f\"Extracted gene symbols from SPOT_ID: {gene_symbols_extracted}\")\n",
    "\n",
    "# If we can't find clear gene symbols from the annotation, we need another approach\n",
    "# This is a special case where we might need to use the SPOT_ID as a temporary gene identifier\n",
    "# and advise that proper gene mapping would require additional annotation data\n",
    "\n",
    "# Since we have limited information in the annotation, we'll create a simple mapping using SPOT_ID\n",
    "# assuming it might contain some biological information even if not standard gene symbols\n",
    "prob_col = 'ID'\n",
    "gene_col = 'SPOT_ID'  # Using SPOT_ID as our best available option\n",
    "\n",
    "# Create a mapping dataframe - the best we can do with available annotation\n",
    "mapping_df = gene_annotation[[prob_col, gene_col]].dropna()\n",
    "mapping_df = mapping_df.rename(columns={gene_col: 'Gene'})\n",
    "mapping_df = mapping_df.astype({'ID': 'str'})\n",
    "\n",
    "print(\"\\nMapping dataframe created:\")\n",
    "print(f\"Shape: {mapping_df.shape}\")\n",
    "print(mapping_df.head())\n",
    "\n",
    "# Check if mapping covers gene_data IDs\n",
    "coverage = len(set(mapping_df['ID']).intersection(gene_id_set)) / len(gene_id_set) * 100\n",
    "print(f\"Mapping covers {coverage:.2f}% of gene_data IDs\")\n",
    "\n",
    "# Apply the gene mapping to convert probe-level measurements to gene expression\n",
    "try:\n",
    "    gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
    "    print(\"\\nGene expression data created:\")\n",
    "    print(f\"Shape: {gene_data.shape}\")\n",
    "    print(f\"First few gene symbols: {gene_data.index[:5].tolist()}\")\n",
    "except Exception as e:\n",
    "    print(f\"Error during gene mapping: {e}\")\n",
    "    \n",
    "    # Alternative approach if the mapping fails - create a simple one-to-one mapping\n",
    "    # This is not ideal but allows the pipeline to continue\n",
    "    print(\"\\nFalling back to simplified mapping approach...\")\n",
    "    \n",
    "    # Create a mapping where each probe ID maps to itself (preserving the data)\n",
    "    # This is a workaround when proper gene symbols aren't available\n",
    "    fallback_mapping = pd.DataFrame({'ID': gene_data.index, 'Gene': gene_data.index})\n",
    "    gene_data = apply_gene_mapping(gene_data, fallback_mapping)\n",
    "    print(f\"Fallback gene expression data shape: {gene_data.shape}\")\n",
    "    print(f\"First few identifiers: {gene_data.index[:5].tolist()}\")\n",
    "    \n",
    "    # Add a note about the limitations of this mapping\n",
    "    print(\"NOTE: Unable to map to standard gene symbols. Using probe IDs as gene identifiers.\")\n",
    "\n",
    "# Print a summary of the gene data\n",
    "print(\"\\nSummary of mapped gene expression data:\")\n",
    "print(f\"Number of genes: {gene_data.shape[0]}\")\n",
    "print(f\"Number of samples: {gene_data.shape[1]}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ebf53e1f",
   "metadata": {},
   "source": [
    "### Step 8: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "593dcfe0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "# Use normalize_gene_symbols_in_index to standardize gene symbols\n",
    "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Gene data shape before normalization: {gene_data.shape}\")\n",
    "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
    "\n",
    "# Save the normalized gene data to 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\"Normalized gene expression data saved to {out_gene_data_file}\")\n",
    "\n",
    "# Load the actual clinical data from the matrix file that was previously obtained in Step 1\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n",
    "\n",
    "# Get preview of clinical data to understand its structure\n",
    "print(\"Original clinical data preview:\")\n",
    "print(clinical_data.head())\n",
    "\n",
    "# 2. If we have trait data available, proceed with linking\n",
    "if trait_row is not None:\n",
    "    # Extract clinical features using the original clinical data\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",
    "    print(f\"Selected clinical data shape: {selected_clinical_df.shape}\")\n",
    "    print(\"Clinical data preview:\")\n",
    "    print(selected_clinical_df.head())\n",
    "\n",
    "    # Link the clinical and genetic data\n",
    "    linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n",
    "    print(f\"Linked data shape before processing: {linked_data.shape}\")\n",
    "    print(\"Linked data preview (first 5 rows, 5 columns):\")\n",
    "    print(linked_data.iloc[:5, :5] if not linked_data.empty else \"Empty dataframe\")\n",
    "\n",
    "    # 3. Handle missing values\n",
    "    try:\n",
    "        linked_data = handle_missing_values(linked_data, trait)\n",
    "        print(f\"Data shape after handling missing values: {linked_data.shape}\")\n",
    "    except Exception as e:\n",
    "        print(f\"Error handling missing values: {e}\")\n",
    "        linked_data = pd.DataFrame()  # Create empty dataframe if error occurs\n",
    "\n",
    "    # 4. Check for bias in features\n",
    "    if not linked_data.empty and linked_data.shape[0] > 0:\n",
    "        is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "        print(f\"Data shape after removing biased features: {linked_data.shape}\")\n",
    "    else:\n",
    "        is_biased = True\n",
    "        print(\"Cannot check for bias as dataframe is empty or has no rows after missing value handling\")\n",
    "\n",
    "    # 5. Validate and save cohort information\n",
    "    note = \"\"\n",
    "    if linked_data.empty or linked_data.shape[0] == 0:\n",
    "        note = \"Dataset contains gene expression data related to liver fibrosis progression, but linking clinical and genetic data failed, possibly due to mismatched sample IDs.\"\n",
    "    else:\n",
    "        note = \"Dataset contains gene expression data for liver fibrosis progression, which is relevant to liver cirrhosis research.\"\n",
    "    \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_biased,\n",
    "        df=linked_data,\n",
    "        note=note\n",
    "    )\n",
    "\n",
    "    # 6. Save the linked data if usable\n",
    "    if is_usable:\n",
    "        os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "        linked_data.to_csv(out_data_file)\n",
    "        print(f\"Linked data saved to {out_data_file}\")\n",
    "    else:\n",
    "        print(\"Dataset is not usable for analysis. No linked data file saved.\")\n",
    "else:\n",
    "    # If no trait data available, validate with trait_available=False\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=False,\n",
    "        is_biased=True,  # Set to True since we can't use data without trait\n",
    "        df=pd.DataFrame(),  # Empty DataFrame\n",
    "        note=\"Dataset contains gene expression data but lacks proper clinical trait information for liver cirrhosis analysis.\"\n",
    "    )\n",
    "    \n",
    "    print(\"Dataset is not usable for liver cirrhosis analysis due to lack of clinical trait data. No linked data file saved.\")"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}