File size: 34,730 Bytes
9fe78b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "84e3c49d",
   "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 = \"Psoriatic_Arthritis\"\n",
    "cohort = \"GSE141934\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Psoriatic_Arthritis\"\n",
    "in_cohort_dir = \"../../input/GEO/Psoriatic_Arthritis/GSE141934\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Psoriatic_Arthritis/GSE141934.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Psoriatic_Arthritis/gene_data/GSE141934.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Psoriatic_Arthritis/clinical_data/GSE141934.csv\"\n",
    "json_path = \"../../output/preprocess/Psoriatic_Arthritis/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7935854a",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d1b57050",
   "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": "a45c2fa8",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cde632f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Based on the series summary and design, this dataset contains transcriptional data \n",
    "# which implies gene expression data is available\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "\n",
    "# For trait - looking at diagnosis information in rows 5 and 6\n",
    "# Row 6 (working_diagnosis) contains Psoriatic Arthritis data\n",
    "trait_row = 6\n",
    "\n",
    "# For age - found in row 2 \n",
    "age_row = 2\n",
    "\n",
    "# For gender - found in row 1\n",
    "gender_row = 1\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "\n",
    "# Function to convert trait data to binary (1 for Psoriatic Arthritis, 0 for others)\n",
    "def convert_trait(value):\n",
    "    if not value or ':' not in value:\n",
    "        return None\n",
    "    diagnosis = value.split(':', 1)[1].strip()\n",
    "    if diagnosis == \"Psoriatic Arthritis\":\n",
    "        return 1\n",
    "    return 0\n",
    "\n",
    "# Function to convert age data to continuous values\n",
    "def convert_age(value):\n",
    "    if not value or ':' not in value:\n",
    "        return None\n",
    "    try:\n",
    "        age = int(value.split(':', 1)[1].strip())\n",
    "        return age\n",
    "    except (ValueError, TypeError):\n",
    "        return None\n",
    "\n",
    "# Function to convert gender data to binary (0 for female, 1 for male)\n",
    "def convert_gender(value):\n",
    "    if not value or ':' not in value:\n",
    "        return None\n",
    "    gender = value.split(':', 1)[1].strip()\n",
    "    if gender.upper() == 'F':\n",
    "        return 0\n",
    "    elif gender.upper() == 'M':\n",
    "        return 1\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Check if trait data is available (trait_row is not None)\n",
    "is_trait_available = trait_row is not None\n",
    "# Initial filtering on dataset usability\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. Clinical Feature Extraction - Only if trait_row is not None\n",
    "if trait_row is not None:\n",
    "    # The sample characteristics dictionary represents characteristics categorized by row index\n",
    "    # First, we need to create a proper clinical data DataFrame\n",
    "    \n",
    "    # Get the sample characteristics dictionary from the previous step\n",
    "    sample_char_dict = {0: ['patient: 1072', 'patient: 1085', 'patient: 1076', 'patient: 1087', 'patient: 1080', 'patient: 1088', 'patient: 1083', 'patient: 1094', 'patient: 1050', 'patient: 1067', 'patient: 1051', 'patient: 1054', 'patient: 1070', 'patient: 1058', 'patient: 2010', 'patient: 2012', 'patient: 2029', 'patient: 2075', 'patient: 2062', 'patient: 2078', 'patient: 2086', 'patient: 2087', 'patient: 2067', 'patient: 2072', 'patient: 2090', 'patient: 1019', 'patient: 1020', 'patient: 1003', 'patient: 1008', 'patient: 2030'], \n",
    "                          1: ['gender: F', 'gender: M'], \n",
    "                          2: ['age: 50', 'age: 43', 'age: 66', 'age: 55', 'age: 52', 'age: 54', 'age: 63', 'age: 61', 'age: 58', 'age: 79', 'age: 69', 'age: 57', 'age: 46', 'age: 44', 'age: 59', 'age: 81', 'age: 60', 'age: 92', 'age: 45', 'age: 47', 'age: 27', 'age: 38', 'age: 51', 'age: 70', 'age: 56', 'age: 53', 'age: 74', 'age: 49', 'age: 31', 'age: 65'], \n",
    "                          3: ['tissue: peripheral blood'], \n",
    "                          4: ['cell type: CD4+ T cells'], \n",
    "                          5: ['first_diagnosis: Rheumatoid Arthritis', 'first_diagnosis: Undifferentiated Inflammatory Arthritis', 'first_diagnosis: Reactive Arthritis', 'first_diagnosis: Crystal Arthritis', 'first_diagnosis: Psoriatic Arthritis', 'first_diagnosis: Non-Inflammatory', 'first_diagnosis: Other Inflammatory Arthritis', 'first_diagnosis: Enteropathic Arthritis', 'first_diagnosis: Undifferentiated Spondylo-Arthropathy', 'first_diagnosis: Unknown'], \n",
    "                          6: ['working_diagnosis: Rheumatoid Arthritis', 'working_diagnosis: Psoriatic Arthritis', 'working_diagnosis: Reactive Arthritis', 'working_diagnosis: Crystal Arthritis', 'working_diagnosis: Osteoarthritis', 'working_diagnosis: Non-Inflammatory', 'working_diagnosis: Undifferentiated Inflammatory Arthritis', 'working_diagnosis: Other Inflammatory Arthritis', 'working_diagnosis: Enteropathic Arthritis', 'working_diagnosis: Undifferentiated Spondylo-Arthropathy', 'working_diagnosis: Unknown']}\n",
    "    \n",
    "    # Create a DataFrame where each row is a patient and each column is a feature\n",
    "    # We'll extract values from individual cells in the dictionary and create a more suitable structure\n",
    "    \n",
    "    # For the purposes of geo_select_clinical_features, we need a DataFrame where:\n",
    "    # - Rows correspond to features (rows in the sample characteristics dictionary)\n",
    "    # - Each column represents a sample\n",
    "    clinical_data = pd.DataFrame(sample_char_dict)\n",
    "    \n",
    "    # Extract clinical features using the geo_select_clinical_features function\n",
    "    selected_clinical_features = geo_select_clinical_features(\n",
    "        clinical_df=clinical_data,\n",
    "        trait=trait,\n",
    "        trait_row=trait_row,\n",
    "        convert_trait=convert_trait,\n",
    "        age_row=age_row,\n",
    "        convert_age=convert_age,\n",
    "        gender_row=gender_row,\n",
    "        convert_gender=convert_gender\n",
    "    )\n",
    "    \n",
    "    # Preview the extracted clinical features\n",
    "    preview = preview_df(selected_clinical_features)\n",
    "    print(\"Clinical Features Preview:\")\n",
    "    print(preview)\n",
    "    \n",
    "    # Save the extracted clinical features as a CSV file\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    selected_clinical_features.to_csv(out_clinical_data_file)\n",
    "    print(f\"Clinical data saved to: {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cbf0a77f",
   "metadata": {},
   "source": [
    "### Step 3: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "14f8efce",
   "metadata": {},
   "outputs": [],
   "source": [
    "I've analyzed the errors - it appears the input files don't exist in the expected directory structure. Let me implement a more robust solution that adapts to the available data.\n",
    "\n",
    "```python\n",
    "import pandas as pd\n",
    "import os\n",
    "import json\n",
    "from typing import Callable, Optional, Dict, Any\n",
    "import glob\n",
    "import re\n",
    "from pathlib import Path\n",
    "\n",
    "# Initialize variables\n",
    "sample_characteristics = {}\n",
    "background = {}\n",
    "clinical_data = pd.DataFrame()\n",
    "\n",
    "# Check directory contents to find available files\n",
    "print(f\"Checking contents of {in_cohort_dir}\")\n",
    "if os.path.exists(in_cohort_dir):\n",
    "    files = os.listdir(in_cohort_dir)\n",
    "    print(f\"Files in directory: {files}\")\n",
    "else:\n",
    "    print(f\"Directory {in_cohort_dir} does not exist\")\n",
    "    # Try to check if parent directory exists\n",
    "    parent_dir = os.path.dirname(in_cohort_dir)\n",
    "    if os.path.exists(parent_dir):\n",
    "        print(f\"Parent directory {parent_dir} exists with contents: {os.listdir(parent_dir)}\")\n",
    "\n",
    "# Try multiple possible paths for sample characteristics\n",
    "possible_paths = [\n",
    "    os.path.join(in_cohort_dir, \"sample_characteristics.json\"),\n",
    "    os.path.join(in_trait_dir, \"sample_characteristics.json\"),\n",
    "    os.path.join(in_cohort_dir, \"characteristics.json\"),\n",
    "    os.path.join(in_cohort_dir, \"samples.json\")\n",
    "]\n",
    "\n",
    "for path in possible_paths:\n",
    "    if os.path.exists(path):\n",
    "        print(f\"Found sample characteristics at {path}\")\n",
    "        with open(path, 'r') as f:\n",
    "            sample_characteristics = json.load(f)\n",
    "        break\n",
    "else:\n",
    "    print(\"Could not find sample characteristics file\")\n",
    "\n",
    "# Try multiple possible paths for background info\n",
    "possible_bg_paths = [\n",
    "    os.path.join(in_cohort_dir, \"background.json\"),\n",
    "    os.path.join(in_trait_dir, \"background.json\"),\n",
    "    os.path.join(in_cohort_dir, \"metadata.json\"),\n",
    "    os.path.join(in_cohort_dir, \"info.json\")\n",
    "]\n",
    "\n",
    "for path in possible_bg_paths:\n",
    "    if os.path.exists(path):\n",
    "        print(f\"Found background info at {path}\")\n",
    "        with open(path, 'r') as f:\n",
    "            background = json.load(f)\n",
    "        break\n",
    "else:\n",
    "    print(\"Could not find background information file\")\n",
    "\n",
    "# Look for any CSV file that might contain clinical data\n",
    "csv_files = glob.glob(os.path.join(in_cohort_dir, \"*.csv\"))\n",
    "if csv_files:\n",
    "    # Try to identify the most likely clinical data file\n",
    "    for file in csv_files:\n",
    "        if \"clinical\" in file.lower() or \"pheno\" in file.lower() or \"characteristic\" in file.lower():\n",
    "            print(f\"Found clinical data at {file}\")\n",
    "            clinical_data = pd.read_csv(file)\n",
    "            break\n",
    "    else:\n",
    "        # If no specific clinical file found, use the first CSV\n",
    "        print(f\"Using first CSV file as clinical data: {csv_files[0]}\")\n",
    "        clinical_data = pd.read_csv(csv_files[0])\n",
    "else:\n",
    "    # Try parent directory\n",
    "    csv_files = glob.glob(os.path.join(in_trait_dir, \"*.csv\"))\n",
    "    if csv_files:\n",
    "        for file in csv_files:\n",
    "            if os.path.basename(file).startswith(cohort) or cohort in file:\n",
    "                print(f\"Found possible clinical data at {file}\")\n",
    "                clinical_data = pd.read_csv(file)\n",
    "                break\n",
    "\n",
    "# Determine gene data availability based on available information\n",
    "is_gene_available = True  # Default assumption\n",
    "\n",
    "# Check platform info in background data if available\n",
    "if background and \"platform\" in background:\n",
    "    platform = str(background[\"platform\"]).lower()\n",
    "    if \"mirna\" in platform or \"methylation\" in platform:\n",
    "        is_gene_available = False\n",
    "    print(f\"Platform info: {platform}\")\n",
    "else:\n",
    "    # Check file names for clues about data type\n",
    "    expression_files = [f for f in files if os.path.exists(in_cohort_dir) and \n",
    "                        (\"expression\" in f.lower() or \"gene\" in f.lower())]\n",
    "    if not expression_files:\n",
    "        # If no expression files and we have CSV files that might be miRNA or methylation\n",
    "        for f in csv_files:\n",
    "            if \"mirna\" in f.lower() or \"methylation\" in f.lower():\n",
    "                is_gene_available = False\n",
    "                break\n",
    "\n",
    "# Initialize trait, age, and gender rows\n",
    "trait_row = None\n",
    "age_row = None\n",
    "gender_row = None\n",
    "\n",
    "# Examine the sample characteristics to identify relevant rows\n",
    "if sample_characteristics:\n",
    "    print(\"Sample Characteristics Keys:\")\n",
    "    for key, values in sample_characteristics.items():\n",
    "        if not values:\n",
    "            continue\n",
    "        \n",
    "        # Get a sample of unique values for display\n",
    "        unique_values = list(set(str(v) for v in values if v is not None))[:5]\n",
    "        print(f\"Key {key}: {unique_values}\")\n",
    "        \n",
    "        # Check for psoriatic arthritis related information\n",
    "        if any(re.search(r'psoria|arthritis|psa', str(v).lower()) for v in values):\n",
    "            trait_row = int(key)\n",
    "        \n",
    "        # Check for age information\n",
    "        if any(re.search(r'age|years old', str(v).lower()) for v in values):\n",
    "            age_row = int(key)\n",
    "        \n",
    "        # Check for gender/sex information\n",
    "        if any(re.search(r'gender|sex', str(v).lower()) for v in values):\n",
    "            gender_row = int(key)\n",
    "else:\n",
    "    print(\"No sample characteristics data available\")\n",
    "\n",
    "# Define conversion functions\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait values to binary (0 for control, 1 for psoriatic arthritis)\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    value_lower = str(value).lower()\n",
    "    if \":\" in value_lower:\n",
    "        value_lower = value_lower.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    if re.search(r'psoria.*arthritis|psa', value_lower):\n",
    "        return 1\n",
    "    elif re.search(r'control|healthy|hc', value_lower):\n",
    "        return 0\n",
    "    return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age values to continuous numeric values\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    value_str = str(value).lower()\n",
    "    if \":\" in value_str:\n",
    "        value_str = value_str.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Extract numeric age\n",
    "    age_match = re.search(r'(\\d+\\.?\\d*)', value_str)\n",
    "    if age_match:\n",
    "        try:\n",
    "            return float(age_match.group(1))\n",
    "        except:\n",
    "            return None\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:\n",
    "        return None\n",
    "    \n",
    "    value_str = str(value).lower()\n",
    "    if \":\" in value_str:\n",
    "        value_str = value_str.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    if re.search(r'female|f$|f\\s', value_str):\n",
    "        return 0\n",
    "    elif re.search(r'male|m$|m\\s', value_str):\n",
    "        return 1\n",
    "    return None\n",
    "\n",
    "# Determine if trait data is available\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Print findings\n",
    "print(f\"Is gene data available: {is_gene_available}\")\n",
    "print(f\"Is trait data available: {is_trait_available}\")\n",
    "print(f\"Trait row: {trait_row}\")\n",
    "print(f\"Age row: {age_row}\")\n",
    "print(f\"Gender row: {gender_row}\")\n",
    "\n",
    "# Save metadata about the cohort\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 and not clinical_\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d0ee9911",
   "metadata": {},
   "source": [
    "### Step 4: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8591d05e",
   "metadata": {},
   "outputs": [],
   "source": [
    "I'll implement the code that properly accesses the available data for this cohort.\n",
    "\n",
    "```python\n",
    "import pandas as pd\n",
    "import json\n",
    "import os\n",
    "from typing import Callable, Optional, Dict, Any\n",
    "import glob\n",
    "\n",
    "# First, let's explore the input directory to see what files are available\n",
    "print(f\"Contents of input directory {in_cohort_dir}:\")\n",
    "directory_contents = os.listdir(in_cohort_dir)\n",
    "for item in directory_contents:\n",
    "    print(f\"  - {item}\")\n",
    "\n",
    "# Look for potential clinical or sample data files\n",
    "clinical_file_candidates = glob.glob(os.path.join(in_cohort_dir, \"*clinical*.csv\"))\n",
    "clinical_file_candidates.extend(glob.glob(os.path.join(in_cohort_dir, \"*clinical*.pkl\")))\n",
    "clinical_file_candidates.extend(glob.glob(os.path.join(in_cohort_dir, \"*sample*.csv\")))\n",
    "clinical_file_candidates.extend(glob.glob(os.path.join(in_cohort_dir, \"*sample*.pkl\")))\n",
    "\n",
    "print(\"\\nPotential clinical data files:\")\n",
    "for file in clinical_file_candidates:\n",
    "    print(f\"  - {file}\")\n",
    "\n",
    "# Try to load from clinical_data.csv (which might have been generated in a previous step)\n",
    "try:\n",
    "    clinical_data_paths = [\n",
    "        os.path.join(in_cohort_dir, \"clinical_data.csv\"),\n",
    "        os.path.join(in_cohort_dir, \"sample_characteristics.csv\"),\n",
    "        os.path.join(in_cohort_dir, \"clinical_data.pkl\"),\n",
    "        os.path.join(in_cohort_dir, \"GSE141934_clinical_data.csv\")\n",
    "    ]\n",
    "    \n",
    "    clinical_data = None\n",
    "    data_path_used = None\n",
    "    \n",
    "    for path in clinical_data_paths:\n",
    "        if os.path.exists(path):\n",
    "            if path.endswith('.csv'):\n",
    "                clinical_data = pd.read_csv(path, index_col=0)\n",
    "            else:\n",
    "                clinical_data = pd.read_pickle(path)\n",
    "            data_path_used = path\n",
    "            break\n",
    "    \n",
    "    if clinical_data is not None:\n",
    "        print(f\"\\nClinical data loaded from {data_path_used}\")\n",
    "        \n",
    "        # Display the clinical data to understand its structure\n",
    "        print(\"\\nClinical data shape:\", clinical_data.shape)\n",
    "        print(\"\\nClinical data preview:\")\n",
    "        print(clinical_data.head())\n",
    "        \n",
    "        # Get unique values for each row to identify relevant rows\n",
    "        unique_values_dict = {}\n",
    "        for idx, row in clinical_data.iterrows():\n",
    "            unique_values = set(row)\n",
    "            unique_values_dict[idx] = unique_values\n",
    "            if len(unique_values) <= 20:  # Only show if reasonable number of unique values\n",
    "                print(f\"Row {idx}: {unique_values}\")\n",
    "        \n",
    "        # 1. Gene Expression Data Availability - Assume it's available based on cohort\n",
    "        is_gene_available = True\n",
    "        \n",
    "        # 2. Variable Availability and Data Type Conversion\n",
    "        # Identify relevant rows for trait, age, and gender\n",
    "        trait_row = None\n",
    "        age_row = None\n",
    "        gender_row = None\n",
    "        \n",
    "        for idx, unique_vals in unique_values_dict.items():\n",
    "            values_str = ' '.join(str(val).lower() for val in unique_vals if val is not None)\n",
    "            \n",
    "            # Look for trait/diagnosis row\n",
    "            if ('psoriatic' in values_str and 'arthritis' in values_str) or ('psa' in values_str and ('healthy' in values_str or 'control' in values_str)):\n",
    "                trait_row = idx\n",
    "                print(f\"Found trait row at index {idx}\")\n",
    "            \n",
    "            # Look for age row\n",
    "            if 'age' in values_str:\n",
    "                age_row = idx\n",
    "                print(f\"Found age row at index {idx}\")\n",
    "            \n",
    "            # Look for gender row\n",
    "            if 'female' in values_str or 'male' in values_str or 'gender' in values_str or 'sex' in values_str:\n",
    "                gender_row = idx\n",
    "                print(f\"Found gender row at index {idx}\")\n",
    "        \n",
    "        # 2.2 Data Type Conversion Functions\n",
    "        def convert_trait(value: str) -> int:\n",
    "            \"\"\"Convert trait values to binary (0 for control, 1 for disease)\"\"\"\n",
    "            if value is None or pd.isna(value) or value == '':\n",
    "                return None\n",
    "            \n",
    "            value_str = str(value).lower()\n",
    "            \n",
    "            # Extract value after colon if present\n",
    "            if ':' in value_str:\n",
    "                value_str = value_str.split(':', 1)[1].strip()\n",
    "            \n",
    "            if 'healthy' in value_str or 'control' in value_str or 'hc' in value_str:\n",
    "                return 0\n",
    "            elif 'psoriatic' in value_str or 'psa' in value_str or 'patient' in value_str:\n",
    "                return 1\n",
    "            return None\n",
    "        \n",
    "        def convert_age(value: str) -> float:\n",
    "            \"\"\"Convert age values to float\"\"\"\n",
    "            if value is None or pd.isna(value) or value == '':\n",
    "                return None\n",
    "            \n",
    "            value_str = str(value).lower()\n",
    "            \n",
    "            # Extract value after colon if present\n",
    "            if ':' in value_str:\n",
    "                value_str = value_str.split(':', 1)[1].strip()\n",
    "            \n",
    "            # Extract numeric part\n",
    "            import re\n",
    "            age_match = re.search(r'(\\d+)', value_str)\n",
    "            if age_match:\n",
    "                return float(age_match.group(1))\n",
    "            return None\n",
    "        \n",
    "        def convert_gender(value: str) -> int:\n",
    "            \"\"\"Convert gender values to binary (0 for female, 1 for male)\"\"\"\n",
    "            if value is None or pd.isna(value) or value == '':\n",
    "                return None\n",
    "            \n",
    "            value_str = str(value).lower()\n",
    "            \n",
    "            # Extract value after colon if present\n",
    "            if ':' in value_str:\n",
    "                value_str = value_str.split(':', 1)[1].strip()\n",
    "            \n",
    "            if 'female' in value_str or 'f' in value_str:\n",
    "                return 0\n",
    "            elif 'male' in value_str or 'm' in value_str:\n",
    "                return 1\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 is_trait_available:\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 extracted clinical features\n",
    "            print(\"\\nPreview of selected clinical features:\")\n",
    "            preview = preview_df(selected_clinical_df)\n",
    "            print(preview)\n",
    "            \n",
    "            # Save clinical data to CSV\n",
    "            os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "            selected_clinical_df.to_csv(out_clinical_data_file)\n",
    "            print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "        else:\n",
    "            print(\"Trait data is not available. Skipping clinical feature extraction.\")\n",
    "    \n",
    "    else:\n",
    "        print(\"No clinical data files found in expected locations.\")\n",
    "        # If we can't find the clinical data, we still need to save metadata\n",
    "        is_gene_available = True  # Assuming gene expression data is available\n",
    "        is_trait_available = False  # No trait information available\n",
    "        \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\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b3fd2c64",
   "metadata": {},
   "source": [
    "### Step 5: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "30dd931c",
   "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": "4ce024b6",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1eeae24c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Based on the identifiers shown, these are Illumina BeadArray probe IDs (ILMN_*), \n",
    "# not human gene symbols. These identifiers need to be mapped to official gene symbols.\n",
    "# The \"ILMN_\" prefix indicates these are Illumina's proprietary identifiers for\n",
    "# their microarray probes.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "73e1f55b",
   "metadata": {},
   "source": [
    "### Step 7: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "86fa2418",
   "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. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
    "print(\"Gene annotation preview:\")\n",
    "print(preview_df(gene_annotation))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f3375032",
   "metadata": {},
   "source": [
    "### Step 8: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1cdbce16",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Identify which columns in gene_annotation contain probe IDs and gene symbols\n",
    "# From the preview, we can see 'ID' contains the probe identifiers (ILMN_*)\n",
    "# and 'Symbol' contains the gene symbols\n",
    "prob_col = 'ID'\n",
    "gene_col = 'Symbol'\n",
    "\n",
    "# 2. Get gene mapping dataframe using the get_gene_mapping function\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)\n",
    "print(f\"Gene mapping shape: {gene_mapping.shape}\")\n",
    "print(\"First few rows of gene mapping:\")\n",
    "print(gene_mapping.head())\n",
    "\n",
    "# 3. Apply gene mapping to convert probe-level data to gene expression data\n",
    "# Using the apply_gene_mapping function that handles many-to-many relations\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "print(f\"Gene data shape after mapping: {gene_data.shape}\")\n",
    "print(\"First few gene symbols after mapping:\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# 4. Normalize gene symbols to ensure consistency\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Gene data shape after normalization: {gene_data.shape}\")\n",
    "print(\"First few normalized gene symbols:\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# 5. Save the processed gene expression data\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Gene expression data saved to: {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "06116bca",
   "metadata": {},
   "source": [
    "### Step 9: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "de647908",
   "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",
    "normalized_gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Gene data saved to {out_gene_data_file}\")\n",
    "\n",
    "# Re-extract clinical features since we need it for linking\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",
    "# 2. Link the clinical and genetic data with the 'geo_link_clinical_genetic_data' function from the library.\n",
    "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n",
    "print(f\"Linked data shape before handling missing values: {linked_data.shape}\")\n",
    "\n",
    "# 3. Handle missing values in the linked data\n",
    "linked_data = handle_missing_values(linked_data, trait)\n",
    "print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
    "\n",
    "# 4. Determine whether the trait and some demographic features are severely 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 endothelial cells derived from circulating progenitors of RA patients\"\n",
    ")\n",
    "\n",
    "# 6. If the linked data is usable, save it as a CSV file to 'out_data_file'.\n",
    "if is_usable:\n",
    "    print(f\"Data is usable. Saving to {out_data_file}\")\n",
    "    unbiased_linked_data.to_csv(out_data_file)\n",
    "else:\n",
    "    print(\"Data is not usable. Not saving linked data file.\")"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}