File size: 26,535 Bytes
d1894e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1aa6a6ba",
   "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 = \"Fibromyalgia\"\n",
    "cohort = \"GSE67311\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Fibromyalgia\"\n",
    "in_cohort_dir = \"../../input/GEO/Fibromyalgia/GSE67311\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Fibromyalgia/GSE67311.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Fibromyalgia/gene_data/GSE67311.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Fibromyalgia/clinical_data/GSE67311.csv\"\n",
    "json_path = \"../../output/preprocess/Fibromyalgia/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b551ca0c",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "763973a4",
   "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": "7f86a7d2",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "af673d54",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# From the background information, we can see that Affymetrix Human Gene arrays were used\n",
    "# and gene expression analysis was performed, so 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 (Fibromyalgia)\n",
    "# From sample characteristics, we see 'diagnosis' in key 0 \n",
    "# with values 'healthy control' and 'fibromyalgia'\n",
    "trait_row = 0\n",
    "\n",
    "# For age - There is no age information in the sample characteristics\n",
    "age_row = None\n",
    "\n",
    "# For gender - There is no gender information in the sample characteristics\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "\n",
    "# Function to convert trait values\n",
    "def convert_trait(value):\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip().lower()\n",
    "    \n",
    "    # Convert to binary (0 for control, 1 for fibromyalgia)\n",
    "    if value == 'fibromyalgia':\n",
    "        return 1\n",
    "    elif value == 'healthy control':\n",
    "        return 0\n",
    "    return None\n",
    "\n",
    "# Age conversion function (not used as age is not available)\n",
    "def convert_age(value):\n",
    "    return None\n",
    "\n",
    "# Gender conversion function (not used as gender is not available)\n",
    "def convert_gender(value):\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Determine trait data availability\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Save initial filtering results\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",
    "    # Extract clinical features\n",
    "    # Create the clinical data DataFrame from the Sample Characteristics Dictionary provided earlier\n",
    "    sample_characteristics_dict = {\n",
    "        0: ['diagnosis: healthy control', 'diagnosis: fibromyalgia'], \n",
    "        1: ['tissue: peripheral blood'], \n",
    "        2: ['fiqr score: 8.5', 'fiqr score: -2.0', 'fiqr score: 9.8', 'fiqr score: 0.5', 'fiqr score: -1.0', 'fiqr score: -0.5', 'fiqr score: 2.2', 'fiqr score: 15.3', 'fiqr score: 4.0', 'fiqr score: 29.3', 'fiqr score: 27.2', 'fiqr score: 5.0', 'fiqr score: 1.0', 'fiqr score: 2.5', 'fiqr score: 3.0', 'fiqr score: -1.5', 'fiqr score: 1.3', 'fiqr score: 21.7', 'fiqr score: -1.2', 'fiqr score: 4.3', 'fiqr score: 6.5', 'fiqr score: 2.0', 'fiqr score: 11.7', 'fiqr score: 15.0', 'fiqr score: 6.0', 'fiqr score: 14.2', 'fiqr score: -0.2', 'fiqr score: 12.8', 'fiqr score: 15.7', 'fiqr score: 0.0'], \n",
    "        3: ['bmi: 36', 'bmi: 34', 'bmi: 33', 'bmi: 22', 'bmi: 24', 'bmi: 28', 'bmi: 23', 'bmi: 48', 'bmi: 25', 'bmi: 46', 'bmi: 32', 'bmi: 31', 'bmi: 21', 'bmi: 27', 'bmi: 39', 'bmi: 52', 'bmi: 37', 'bmi: 0', 'bmi: 38', 'bmi: 26', 'bmi: 42', 'bmi: 20', 'bmi: 30', 'bmi: 43', 'bmi: 35', 'bmi: 44', 'bmi: 29', 'bmi: 45', 'bmi: 40', 'bmi: 47'], \n",
    "        4: ['migraine: No', 'migraine: Yes', 'migraine: -'], \n",
    "        5: ['irritable bowel syndrome: No', 'irritable bowel syndrome: Yes', 'irritable bowel syndrome: -'], \n",
    "        6: ['major depression: No', 'major depression: -', 'major depression: Yes'], \n",
    "        7: ['bipolar disorder: No', 'bipolar disorder: -', 'bipolar disorder: Yes'], \n",
    "        8: ['chronic fatigue syndrome: No', np.nan, 'chronic fatigue syndrome: -', 'chronic fatigue syndrome: Yes']\n",
    "    }\n",
    "    \n",
    "    clinical_data = pd.DataFrame({k: pd.Series(v) for k, v in sample_characteristics_dict.items()})\n",
    "    \n",
    "    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 processed clinical data\n",
    "    print(\"Preview of clinical features:\")\n",
    "    print(preview_df(clinical_features))\n",
    "    \n",
    "    # Save the clinical data to CSV\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    clinical_features.to_csv(out_clinical_data_file, index=False)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "92901783",
   "metadata": {},
   "source": [
    "### Step 3: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "19c1b740",
   "metadata": {},
   "outputs": [],
   "source": [
    "```python\n",
    "# Let's examine whether the dataset contains the necessary information\n",
    "print(\"Examination of GSE67311 dataset for Fibromyalgia study\")\n",
    "\n",
    "# First, let's check if the files exist\n",
    "clinical_data_file = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n",
    "meta_data_file = os.path.join(in_cohort_dir, \"meta_data.json\")\n",
    "\n",
    "# Initialize flags for data availability\n",
    "is_gene_available = False\n",
    "is_trait_available = False\n",
    "\n",
    "# Initialize variables\n",
    "clinical_data = None\n",
    "meta_data = {}\n",
    "trait_row = None\n",
    "age_row = None\n",
    "gender_row = None\n",
    "\n",
    "# Try to load clinical data\n",
    "if os.path.exists(clinical_data_file):\n",
    "    clinical_data = pd.read_csv(clinical_data_file)\n",
    "    print(\"Clinical data shape:\", clinical_data.shape)\n",
    "    print(\"Clinical data columns:\", clinical_data.columns.tolist())\n",
    "    print(\"Sample of clinical data:\\n\", clinical_data.head())\n",
    "else:\n",
    "    print(f\"Clinical data file not found at: {clinical_data_file}\")\n",
    "    print(\"Checking for alternative files in the directory...\")\n",
    "    \n",
    "    # Check if there are any CSV files in the directory\n",
    "    csv_files = [f for f in os.listdir(in_cohort_dir) if f.endswith('.csv')]\n",
    "    if csv_files:\n",
    "        print(f\"Found CSV files: {csv_files}\")\n",
    "        # Try the first CSV file\n",
    "        alternative_file = os.path.join(in_cohort_dir, csv_files[0])\n",
    "        try:\n",
    "            clinical_data = pd.read_csv(alternative_file)\n",
    "            print(f\"Loaded alternative clinical data from: {alternative_file}\")\n",
    "            print(\"Clinical data shape:\", clinical_data.shape)\n",
    "            print(\"Sample of clinical data:\\n\", clinical_data.head())\n",
    "        except Exception as e:\n",
    "            print(f\"Error loading alternative file: {e}\")\n",
    "    else:\n",
    "        print(\"No CSV files found in the directory.\")\n",
    "\n",
    "# Try to load meta data\n",
    "if os.path.exists(meta_data_file):\n",
    "    with open(meta_data_file, 'r') as f:\n",
    "        meta_data = json.load(f)\n",
    "    print(\"Meta data keys:\", list(meta_data.keys()))\n",
    "    \n",
    "    if 'title' in meta_data:\n",
    "        print(\"Dataset title:\", meta_data.get('title'))\n",
    "    \n",
    "    if 'background' in meta_data:\n",
    "        print(\"Background information:\", meta_data.get('background'))\n",
    "    \n",
    "    # Check for gene expression data availability based on meta_data\n",
    "    if any(keyword in str(meta_data).lower() for keyword in \n",
    "           ['gene expression', 'mrna', 'transcriptome', 'gene profile']):\n",
    "        is_gene_available = True\n",
    "    \n",
    "    if 'sample_characteristics' in meta_data:\n",
    "        sample_chars = meta_data.get('sample_characteristics', {})\n",
    "        print(\"Sample characteristics keys:\", list(sample_chars.keys()))\n",
    "        \n",
    "        # Print the unique values for each key in sample characteristics\n",
    "        for key, values in sample_chars.items():\n",
    "            unique_values = set(values)\n",
    "            print(f\"Key {key} unique values:\", unique_values)\n",
    "            \n",
    "            # Check for trait, age, and gender data\n",
    "            if any('fibromyalgia' in str(v).lower() or 'fm' in str(v).lower() or trait.lower() in str(v).lower() \n",
    "                  for v in unique_values):\n",
    "                trait_row = int(key)\n",
    "                is_trait_available = True\n",
    "            \n",
    "            if any('age' in str(v).lower() for v in unique_values):\n",
    "                age_row = int(key)\n",
    "            \n",
    "            if any('gender' in str(v).lower() or 'sex' in str(v).lower() or \n",
    "                  'female' in str(v).lower() or 'male' in str(v).lower() for v in unique_values):\n",
    "                gender_row = int(key)\n",
    "else:\n",
    "    print(f\"Meta data file not found at: {meta_data_file}\")\n",
    "    print(\"Checking for alternative JSON files in the directory...\")\n",
    "    \n",
    "    # Check if there are any JSON files in the directory\n",
    "    json_files = [f for f in os.listdir(in_cohort_dir) if f.endswith('.json')]\n",
    "    if json_files:\n",
    "        print(f\"Found JSON files: {json_files}\")\n",
    "        # Try the first JSON file\n",
    "        alternative_file = os.path.join(in_cohort_dir, json_files[0])\n",
    "        try:\n",
    "            with open(alternative_file, 'r') as f:\n",
    "                meta_data = json.load(f)\n",
    "            print(f\"Loaded alternative meta data from: {alternative_file}\")\n",
    "        except Exception as e:\n",
    "            print(f\"Error loading alternative JSON file: {e}\")\n",
    "    else:\n",
    "        print(\"No JSON files found in the directory.\")\n",
    "\n",
    "# Check for data in any other files in the directory\n",
    "if not is_gene_available:\n",
    "    # Look for files that might contain gene expression data\n",
    "    gene_data_indicators = ['gene', 'expression', 'probe', 'mrna', 'matrix', 'series']\n",
    "    all_files = os.listdir(in_cohort_dir)\n",
    "    potential_gene_files = [f for f in all_files if any(indicator in f.lower() for indicator in gene_data_indicators)]\n",
    "    \n",
    "    if potential_gene_files:\n",
    "        print(f\"Found potential gene expression files: {potential_gene_files}\")\n",
    "        is_gene_available = True\n",
    "    else:\n",
    "        print(\"No files indicating gene expression data found.\")\n",
    "\n",
    "# Output 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",
    "print(f\"Is gene expression data available: {is_gene_available}\")\n",
    "print(f\"Is trait data available: {is_trait_available}\")\n",
    "\n",
    "# Define conversion functions regardless of data availability\n",
    "def convert_trait(value):\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    value = str(value).lower()\n",
    "    # Extract value after colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary (0 for control, 1 for fibromyalgia)\n",
    "    if 'fibromyalgia' in value or 'fm' in value or 'patient' in value:\n",
    "        return 1\n",
    "    elif 'control' in value or 'healthy' in value:\n",
    "        return 0\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    value = str(value).lower()\n",
    "    # Extract value after colon if present\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Extract numeric age using regex\n",
    "    import re\n",
    "    match = re.search(r'(\\d+(\\.\\d+)?)', value)\n",
    "    if match:\n",
    "        return float(match.group(1))\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    if value is None:\n",
    "        return None\n",
    "    \n",
    "    value = str(value).lower()\n",
    "    # Extract 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 'female' in value or 'f' == value.strip():\n",
    "        return 0\n",
    "    elif 'male' in value or 'm' == value.strip():\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# Use validate_and_save_cohort_info 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 data is available\n",
    "if trait_row is not None and clinical_data is not None:\n",
    "    # Extract clinical features using the geo_select_clinical_features function\n",
    "    selected_clinical_df = geo_select_clinical_features(\n",
    "        clinical_df=clinical_data,\n",
    "        trait=trait,\n",
    "        trait_row\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "27313159",
   "metadata": {},
   "source": [
    "### Step 4: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "31f56ec1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Re-identify the SOFT and matrix files to ensure we have the correct paths\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. Extract the gene expression 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)\n",
    "print(\"\\nFirst 20 gene/probe identifiers:\")\n",
    "print(gene_data.index[:20])\n",
    "\n",
    "# 4. Print the dimensions of the gene expression data\n",
    "print(f\"\\nGene data dimensions: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
    "\n",
    "# Note: we keep is_gene_available as True since we successfully extracted gene expression data\n",
    "is_gene_available = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c463287f",
   "metadata": {},
   "source": [
    "### Step 5: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2b3b6757",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Analyzing the gene identifiers from the previous step\n",
    "\n",
    "# These appear to be microarray probe IDs (likely Affymetrix Human Gene 1.0 ST Array)\n",
    "# They are 7-digit numeric IDs (7892501, 7892502, etc.) which are typical for\n",
    "# probesets in microarray platforms, not standard human gene symbols\n",
    "# Human gene symbols would be alphanumeric (like BRCA1, TP53, etc.)\n",
    "\n",
    "# Since these are probe IDs and not human gene symbols, they will need to be mapped\n",
    "# to standard gene symbols for proper biological interpretation\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0fd33e6b",
   "metadata": {},
   "source": [
    "### Step 6: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "01cd7f56",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. First get the file paths using geo_get_relevant_filepaths function\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. 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",
    "# 3. 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": "acc24bfc",
   "metadata": {},
   "source": [
    "### Step 7: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8bea9ace",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Identify the columns that contain gene identifiers and gene symbols\n",
    "# From the gene annotation preview, I can see:\n",
    "# - 'ID' column has identifiers like '7896736' which match the format in gene expression data\n",
    "# - 'gene_assignment' column contains gene symbols and annotations\n",
    "\n",
    "# 2. Create a gene mapping dataframe\n",
    "# The 'gene_assignment' column contains complex text with gene symbols\n",
    "# Using get_gene_mapping to extract IDs and gene symbols\n",
    "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='gene_assignment')\n",
    "\n",
    "# Print the mapping dataframe to verify\n",
    "print(\"Gene mapping dataframe preview:\")\n",
    "print(preview_df(mapping_df))\n",
    "\n",
    "# 3. Convert probe-level measurements to gene expression data\n",
    "# Using the library function to apply gene mapping\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
    "\n",
    "# Print the dimensions and preview of the gene expression data after mapping\n",
    "print(f\"\\nGene expression data after mapping: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
    "print(\"First few rows of the mapped gene expression data:\")\n",
    "print(preview_df(gene_data))\n",
    "\n",
    "# Normalize gene symbols\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"\\nAfter normalizing gene symbols: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2b61d458",
   "metadata": {},
   "source": [
    "### Step 8: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "809544ee",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Re-identify the SOFT and matrix files to ensure we have the correct paths\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# Extract the gene expression data from the matrix file \n",
    "gene_expression_data = get_genetic_data(matrix_file)\n",
    "\n",
    "# Extract gene annotation data from the SOFT file\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='gene_assignment')\n",
    "\n",
    "# Apply gene mapping and normalize gene symbols\n",
    "gene_data = apply_gene_mapping(gene_expression_data, mapping_df)\n",
    "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "\n",
    "# 1. Save the normalized gene data\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 data saved to {out_gene_data_file}\")\n",
    "\n",
    "# 2. Process clinical data\n",
    "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n",
    "\n",
    "# Determine trait row (from previous step)\n",
    "trait_row = 0  # 'diagnosis: healthy control' or 'diagnosis: fibromyalgia'\n",
    "\n",
    "# Define conversion function for trait\n",
    "def convert_trait(value):\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip().lower()\n",
    "    \n",
    "    # Convert to binary (0 for control, 1 for fibromyalgia)\n",
    "    if value == 'fibromyalgia':\n",
    "        return 1\n",
    "    elif value == 'healthy control':\n",
    "        return 0\n",
    "    return None\n",
    "\n",
    "# Extract clinical features\n",
    "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=None,\n",
    "    convert_age=None,\n",
    "    gender_row=None,\n",
    "    convert_gender=None\n",
    ")\n",
    "\n",
    "# Save clinical data\n",
    "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "clinical_features.to_csv(out_clinical_data_file)\n",
    "print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "print(\"Clinical features preview:\")\n",
    "print(preview_df(clinical_features))\n",
    "\n",
    "# 2. Link clinical and genetic data\n",
    "if not clinical_features.empty:\n",
    "    linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n",
    "    print(f\"Linked data shape before handling missing values: {linked_data.shape}\")\n",
    "    \n",
    "    # 3. Handle missing values\n",
    "    linked_data = handle_missing_values(linked_data, trait)\n",
    "    print(f\"Data shape after handling missing values: {linked_data.shape}\")\n",
    "    \n",
    "    # 4. Determine if trait and demographic features are biased\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",
    "    \n",
    "    # 5. Validate and save cohort info\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=\"Dataset contains gene expression data from peripheral blood of Fibromyalgia patients and healthy controls.\"\n",
    "    )\n",
    "    \n",
    "    # 6. Save 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 deemed not usable for associational studies.\")\n",
    "else:\n",
    "    # No clinical data available\n",
    "    print(\"Clinical data is empty. Dataset not usable for association studies.\")\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=None,\n",
    "        df=pd.DataFrame(index=normalized_gene_data.columns),\n",
    "        note=\"Dataset contains gene expression data but lacks usable clinical metadata for Fibromyalgia studies.\"\n",
    "    )"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}