File size: 29,030 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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "91ddd6cc",
   "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 = \"Rectal_Cancer\"\n",
    "cohort = \"GSE40492\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Rectal_Cancer\"\n",
    "in_cohort_dir = \"../../input/GEO/Rectal_Cancer/GSE40492\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Rectal_Cancer/GSE40492.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Rectal_Cancer/gene_data/GSE40492.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Rectal_Cancer/clinical_data/GSE40492.csv\"\n",
    "json_path = \"../../output/preprocess/Rectal_Cancer/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f4ceeee5",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8260aad4",
   "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": "72982944",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5c0e4ade",
   "metadata": {},
   "outputs": [],
   "source": [
    "I analyzed the patient data for this rectal cancer dataset. The corrections focus on properly handling the clinical data without relying on a pre-existing CSV file.\n",
    "\n",
    "```python\n",
    "# 1. Gene Expression Data Availability\n",
    "# Based on the background info, this dataset contains gene expression data for rectal cancer patients.\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "\n",
    "# For trait (Rectal Cancer)\n",
    "# Looking at the clinical features, we can use pathological lymph node status after treatment\n",
    "# From row 9: 'pathological lymphnode status after neoadjuvant treatment and surgery (0,1,2 - according to uicc tnm classification)'\n",
    "trait_row = 9\n",
    "\n",
    "# For age\n",
    "# Age is available in row 1\n",
    "age_row = 1\n",
    "\n",
    "# For gender\n",
    "# Gender is available in row 2 as 'Sex'\n",
    "gender_row = 2\n",
    "\n",
    "# 2.2 Data Type Conversion Functions\n",
    "\n",
    "def convert_trait(value_str):\n",
    "    \"\"\"Convert lymph node status to binary value.\n",
    "    0 = No positive lymph nodes, 1 = Positive lymph nodes\"\"\"\n",
    "    if value_str is None or 'NA' in value_str:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if ':' in value_str:\n",
    "        value = value_str.split(':', 1)[1].strip()\n",
    "    else:\n",
    "        value = value_str.strip()\n",
    "    \n",
    "    # Status 0 means no positive lymph nodes\n",
    "    if value == '0':\n",
    "        return 0\n",
    "    # Status 1 or 2 means positive lymph nodes\n",
    "    elif value in ['1', '2']:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value_str):\n",
    "    \"\"\"Convert age to continuous value.\"\"\"\n",
    "    if value_str is None or 'NA' in value_str:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if ':' in value_str:\n",
    "        value = value_str.split(':', 1)[1].strip()\n",
    "    else:\n",
    "        value = value_str.strip()\n",
    "    \n",
    "    try:\n",
    "        return float(value)\n",
    "    except ValueError:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value_str):\n",
    "    \"\"\"Convert gender to binary value. 0 = female, 1 = male\"\"\"\n",
    "    if value_str is None or 'NA' in value_str:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if ':' in value_str:\n",
    "        value = value_str.split(':', 1)[1].strip().lower()\n",
    "    else:\n",
    "        value = value_str.strip().lower()\n",
    "    \n",
    "    if 'female' in value:\n",
    "        return 0\n",
    "    elif 'male' in value:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "is_trait_available = trait_row is not None\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. Clinical Feature Extraction\n",
    "# We'll proceed only if trait_row is not None\n",
    "if trait_row is not None:\n",
    "    # Create the clinical data DataFrame from the sample characteristics dictionary\n",
    "    sample_chars_dict = {0: ['dataset: Training', 'dataset: Validation'], 1: ['age: 55.5', 'age: 65.6', 'age: 62.6', 'age: 61.8', 'age: 52.1', 'age: 59.1', 'age: 70.6', 'age: 60.6', 'age: 55', 'age: 53.1', 'age: 58.5', 'age: 68.4', 'age: 58.8', 'age: 70', 'age: 77.5', 'age: 75.2', 'age: 76.3', 'age: 38.2', 'age: 61.1', 'age: 69.4', 'age: 54.2', 'age: 77.7', 'age: 57.4', 'age: 61.2', 'age: 56.5', 'age: 47', 'age: 62.7', 'age: 51.2', 'age: 73.2', 'age: 47.2'], 2: ['Sex: female', 'Sex: male'], 3: ['therapy: 5-FU + Oxaliplatin + RT', 'therapy: 5-FU + RT'], 4: ['surgery type: deep anterior resection (TAbdominoperineal resection (APR))', 'surgery type: Other', 'surgery type: Abdominoperineal excision (APE)', 'surgery type: NA', 'surgery type: Abdominoperineal resection (APR)'], 5: ['clinical tumor category (0,i,ii,iii,iv - according to uicc tnm classification): 3', 'clinical tumor category (0,i,ii,iii,iv - according to uicc tnm classification): 2', 'clinical tumor category (0,i,ii,iii,iv - according to uicc tnm classification): NA', 'clinical tumor category (0,i,ii,iii,iv - according to uicc tnm classification): 4'], 6: ['clinical lymphnode status (0,1 - according to uicc tnm classification): 1', 'clinical lymphnode status (0,1 - according to uicc tnm classification): 0', 'clinical lymphnode status (0,1 - according to uicc tnm classification): NA'], 7: ['clinical tumor stage (0,i,ii,iii,iv - according to uicc tnm classification): IV', 'clinical tumor stage (0,i,ii,iii,iv - according to uicc tnm classification): III', 'clinical tumor stage (0,i,ii,iii,iv - according to uicc tnm classification): II', 'clinical tumor stage (0,i,ii,iii,iv - according to uicc tnm classification): III A', 'clinical tumor stage (0,i,ii,iii,iv - according to uicc tnm classification): III B', 'clinical tumor stage (0,i,ii,iii,iv - according to uicc tnm classification): II A', 'clinical tumor stage (0,i,ii,iii,iv - according to uicc tnm classification): III C'], 8: ['pathological tumor category after neoadjuvant treatment and surgery (0,i,ii,iii,iv - according to uicc tnm classification): 3', 'pathological tumor category after neoadjuvant treatment and surgery (0,i,ii,iii,iv - according to uicc tnm classification): 0', 'pathological tumor category after neoadjuvant treatment and surgery (0,i,ii,iii,iv - according to uicc tnm classification): 2', 'pathological tumor category after neoadjuvant treatment and surgery (0,i,ii,iii,iv - according to uicc tnm classification): 4', 'pathological tumor category after neoadjuvant treatment and surgery (0,i,ii,iii,iv - according to uicc tnm classification): 1'], 9: ['pathological lymphnode status after neoadjuvant treatment and surgery (0,1,2 - according to uicc tnm classification): 1', 'pathological lymphnode status after neoadjuvant treatment and surgery (0,1,2 - according to uicc tnm classification): 0', 'pathological lymphnode status after neoadjuvant treatment and surgery (0,1,2 - according to uicc tnm classification): 2']}\n",
    "\n",
    "    # Convert the sample characteristics dictionary to a DataFrame\n",
    "    clinical_data = pd.DataFrame.from_dict(sample_chars_dict, orient='index')\n",
    "    \n",
    "    # Extract clinical features\n",
    "    selected_clinical_df = geo_select_clinical_features(\n",
    "        clinical_df=clinical_data,\n",
    "        trait=trait,\n",
    "        trait_row=trait_row,\n",
    "        convert_trait=convert_trait,\n",
    "        age\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e4c22109",
   "metadata": {},
   "source": [
    "### Step 3: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "199b6cfa",
   "metadata": {},
   "outputs": [],
   "source": [
    "I'll analyze the dataset and extract the clinical features as requested:\n",
    "\n",
    "```python\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import os\n",
    "import json\n",
    "import gzip\n",
    "import re\n",
    "\n",
    "# Let's first look at what files we have in the cohort directory to understand the dataset\n",
    "print(f\"Files in {in_cohort_dir}:\")\n",
    "for file in os.listdir(in_cohort_dir):\n",
    "    print(f\"- {file}\")\n",
    "\n",
    "# Function to extract sample characteristics from series matrix file\n",
    "def extract_sample_characteristics(file_path):\n",
    "    sample_char_dict = {}\n",
    "    current_row = None\n",
    "    \n",
    "    with gzip.open(file_path, 'rt') as f:\n",
    "        lines = []\n",
    "        in_char_section = False\n",
    "        samples = []\n",
    "        \n",
    "        for line in f:\n",
    "            if line.startswith('!Sample_geo_accession'):\n",
    "                samples = line.strip().split('\\t')[1:]\n",
    "                \n",
    "            elif line.startswith('!Sample_characteristics_ch1'):\n",
    "                if not in_char_section:\n",
    "                    in_char_section = True\n",
    "                \n",
    "                parts = line.strip().split('\\t')\n",
    "                char_value = parts[0].split('!Sample_characteristics_ch1')[1].strip()\n",
    "                if char_value:  # If there's a label in the line\n",
    "                    current_row = len(sample_char_dict)\n",
    "                    sample_char_dict[current_row] = {'label': char_value, 'values': parts[1:]}\n",
    "                else:  # If it's a continuation line\n",
    "                    if current_row is not None:\n",
    "                        sample_char_dict[current_row]['values'].extend(parts[1:])\n",
    "            \n",
    "            elif in_char_section and not line.startswith('!Sample_'):\n",
    "                in_char_section = False\n",
    "            \n",
    "            # Check for data type description\n",
    "            if line.startswith('!Series_summary'):\n",
    "                lines.append(line)\n",
    "            if line.startswith('!Series_title'):\n",
    "                lines.append(line)\n",
    "            if line.startswith('!Series_overall_design'):\n",
    "                lines.append(line)\n",
    "                \n",
    "    # Create DataFrame from the dictionary\n",
    "    df_columns = samples\n",
    "    df_index = list(range(len(sample_char_dict)))\n",
    "    df = pd.DataFrame(index=df_index, columns=df_columns)\n",
    "    \n",
    "    for row_idx, row_data in sample_char_dict.items():\n",
    "        for col_idx, value in enumerate(row_data['values']):\n",
    "            if col_idx < len(df_columns):\n",
    "                df.iloc[row_idx, col_idx] = value\n",
    "    \n",
    "    return df, lines\n",
    "\n",
    "# Load the matrix file to check if gene expression data is available\n",
    "matrix_file = os.path.join(in_cohort_dir, \"GSE40492_series_matrix.txt.gz\")\n",
    "is_gene_available = False\n",
    "clinical_data = None\n",
    "background_info = []\n",
    "\n",
    "if os.path.exists(matrix_file):\n",
    "    # Extract sample characteristics from the matrix file\n",
    "    clinical_data, background_info = extract_sample_characteristics(matrix_file)\n",
    "    \n",
    "    # Check for gene expression data by reading the first few lines of the file\n",
    "    with gzip.open(matrix_file, 'rt') as f:\n",
    "        # Skip header lines\n",
    "        for line in f:\n",
    "            if line.startswith('!series_matrix_table_begin'):\n",
    "                break\n",
    "        \n",
    "        # Read column headers (should be sample IDs)\n",
    "        header = next(f)\n",
    "        \n",
    "        # Check a few data rows to see if they contain gene expression data\n",
    "        for _ in range(5):\n",
    "            line = next(f)\n",
    "            # If the line contains gene IDs and numeric values, it's likely gene expression data\n",
    "            if re.match(r'^[A-Za-z0-9_-]+\\t[-+]?[0-9]*\\.?[0-9]+', line):\n",
    "                is_gene_available = True\n",
    "                break\n",
    "\n",
    "# Print background information\n",
    "print(\"\\nBackground information:\")\n",
    "for line in background_info:\n",
    "    print(line.strip())\n",
    "\n",
    "# Print sample characteristics if available\n",
    "if clinical_data is not None:\n",
    "    print(\"\\nSample characteristics shape:\", clinical_data.shape)\n",
    "    print(\"\\nSample characteristics preview:\")\n",
    "    print(clinical_data.head(3))\n",
    "    \n",
    "    # Print unique values for each row to identify clinical features\n",
    "    for i in range(len(clinical_data)):\n",
    "        unique_values = clinical_data.iloc[i].unique()\n",
    "        print(f\"\\nRow {i}: {len(unique_values)} unique values:\")\n",
    "        print(unique_values[:10])\n",
    "\n",
    "# Based on the data exploration, determine clinical features\n",
    "# For trait (Rectal Cancer - looking for response status)\n",
    "trait_row = None\n",
    "age_row = None\n",
    "gender_row = None\n",
    "\n",
    "# Scan through the rows to find relevant clinical features\n",
    "if clinical_data is not None:\n",
    "    for i in range(len(clinical_data)):\n",
    "        row_values = [str(val).lower() for val in clinical_data.iloc[i] if not pd.isna(val)]\n",
    "        row_text = ' '.join(row_values)\n",
    "        \n",
    "        # Check for response information (trait)\n",
    "        if any('responder' in val for val in row_values):\n",
    "            trait_row = i\n",
    "        \n",
    "        # Check for age information\n",
    "        if any('age' in val for val in row_values):\n",
    "            age_row = i\n",
    "        \n",
    "        # Check for gender/sex information\n",
    "        if any(gender_term in row_text for gender_term in ['gender', 'sex', 'male', 'female']):\n",
    "            gender_row = i\n",
    "\n",
    "print(f\"\\nIdentified rows - trait: {trait_row}, age: {age_row}, gender: {gender_row}\")\n",
    "\n",
    "# Define conversion functions for clinical features\n",
    "def convert_trait(value):\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    value = str(value).lower()\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    if 'responder' in value:\n",
    "        return 1  # Responder\n",
    "    elif 'non-responder' in value:\n",
    "        return 0  # Non-responder\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    value = str(value).lower()\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    # Try to extract numeric age\n",
    "    match = re.search(r'(\\d+)', value)\n",
    "    if match:\n",
    "        return float(match.group(1))\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    if pd.isna(value):\n",
    "        return None\n",
    "    value = str(value).lower()\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    if any(female_term in value for female_term in ['female', 'f', 'woman']):\n",
    "        return 0\n",
    "    elif any(male_term in value for male_term in ['male', 'm', 'man']):\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# Validate and save cohort info\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",
    "# Extract clinical features if trait data is available\n",
    "if trait_row is not None and clinical_data is not None:\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 extracted clinical features\n",
    "    print(\"\\nExtracted clinical features preview:\")\n",
    "    preview = preview_df(clinical_features)\n",
    "    print(preview)\n",
    "    \n",
    "    # Create directory if it doesn't exist\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    \n",
    "    # Save clinical features to CSV\n",
    "    clinical_features.to_csv(out_clinical_data_file)\n",
    "    print(f\"\\nClinical\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "394abeb6",
   "metadata": {},
   "source": [
    "### Step 4: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "59183ede",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. First get the file paths\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. Use the get_genetic_data function from the library to get the gene_data\n",
    "gene_data = get_genetic_data(matrix_file)\n",
    "\n",
    "# 3. Print the first 20 row IDs (gene or probe identifiers) for future observation\n",
    "print(gene_data.index[:20])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "faaf9393",
   "metadata": {},
   "source": [
    "### Step 5: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "390e74e8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Examining the gene identifiers revealed numeric values ('12', '13', '14', etc.)\n",
    "# These are clearly not standard human gene symbols (which would be alphanumeric like BRCA1, TP53, etc.)\n",
    "# These appear to be probe or array identifiers that will need to be mapped to proper gene symbols\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cf97a7be",
   "metadata": {},
   "source": [
    "### Step 6: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "efc22ded",
   "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": "762d35e2",
   "metadata": {},
   "source": [
    "### Step 7: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9ef11ef6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Determine which columns in gene_annotation contain probe IDs and gene symbols\n",
    "# Looking at the gene_annotation preview, the 'ID' column contains numeric identifiers similar to \n",
    "# the gene_data index. For gene symbols, the 'GENE_SYMBOL' column appears to be the appropriate one.\n",
    "prob_col = 'ID'\n",
    "gene_col = 'GENE_SYMBOL'\n",
    "\n",
    "# 2. Get gene mapping dataframe with the two columns\n",
    "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n",
    "\n",
    "# 3. Convert probe-level measurements to gene-level expression data\n",
    "# The apply_gene_mapping function splits probe signals equally among mapped genes\n",
    "# and then sums up contributions to each gene\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
    "\n",
    "# Let's check the first few rows of the mapped gene data to verify the transformation\n",
    "print(\"Gene expression data after mapping to gene symbols:\")\n",
    "print(gene_data.head())\n",
    "print(f\"Shape of gene expression data: {gene_data.shape}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a91e5ce9",
   "metadata": {},
   "source": [
    "### Step 8: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b5324b32",
   "metadata": {},
   "outputs": [],
   "source": [
    "# First, we need to re-establish all the required variables and data from previous steps\n",
    "\n",
    "# 1. Get file paths\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. Get background info and clinical data\n",
    "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n",
    "\n",
    "# 3. Define the necessary row indices based on analysis of clinical data\n",
    "# From the sample characteristics dictionary, we can determine:\n",
    "# Trait: pathological lymph node status is at row 9\n",
    "# Age: age information is at row 1\n",
    "# Gender: sex information is at row 2\n",
    "trait_row = 9\n",
    "age_row = 1\n",
    "gender_row = 2\n",
    "\n",
    "# 4. Define conversion functions for clinical features\n",
    "def convert_trait(value_str):\n",
    "    \"\"\"Convert lymph node status to binary value.\n",
    "    0 = No positive lymph nodes, 1 = Positive lymph nodes\"\"\"\n",
    "    if value_str is None or 'NA' in value_str:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if ':' in value_str:\n",
    "        value = value_str.split(':', 1)[1].strip()\n",
    "    else:\n",
    "        value = value_str.strip()\n",
    "    \n",
    "    # Status 0 means no positive lymph nodes\n",
    "    if value == '0':\n",
    "        return 0\n",
    "    # Status 1 or 2 means positive lymph nodes\n",
    "    elif value in ['1', '2']:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value_str):\n",
    "    \"\"\"Convert age to continuous value.\"\"\"\n",
    "    if value_str is None or 'NA' in value_str:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if ':' in value_str:\n",
    "        value = value_str.split(':', 1)[1].strip()\n",
    "    else:\n",
    "        value = value_str.strip()\n",
    "    \n",
    "    try:\n",
    "        return float(value)\n",
    "    except ValueError:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value_str):\n",
    "    \"\"\"Convert gender to binary value. 0 = female, 1 = male\"\"\"\n",
    "    if value_str is None or 'NA' in value_str:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon\n",
    "    if ':' in value_str:\n",
    "        value = value_str.split(':', 1)[1].strip().lower()\n",
    "    else:\n",
    "        value = value_str.strip().lower()\n",
    "    \n",
    "    if 'female' in value:\n",
    "        return 0\n",
    "    elif 'male' in value:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# Reload the gene expression data from the matrix file\n",
    "gene_data = get_genetic_data(matrix_file)\n",
    "\n",
    "# Get gene annotation data\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "prob_col = 'ID'\n",
    "gene_col = 'GENE_SYMBOL'\n",
    "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n",
    "\n",
    "# Apply gene mapping to convert probe-level data to gene-level\n",
    "gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
    "\n",
    "# Now proceed with the data normalization and linking steps\n",
    "\n",
    "# 1. Extract clinical features\n",
    "clinical_features = geo_select_clinical_features(\n",
    "    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",
    "# Save the clinical features 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",
    "\n",
    "# Normalize gene symbols in the gene expression data\n",
    "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n",
    "print(f\"First few normalized gene symbols: {list(normalized_gene_data.index[:10])}\")\n",
    "\n",
    "# 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. Link the clinical and genetic data\n",
    "linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "print(linked_data.head())\n",
    "\n",
    "# 3. Handle missing values in the linked data\n",
    "linked_data = handle_missing_values(linked_data, trait)\n",
    "print(f\"Shape after handling missing values: {linked_data.shape}\")\n",
    "\n",
    "# 4. Determine whether the trait and demographic features are severely biased\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=f\"Dataset contains rectal cancer patients with clinical annotations including pathological lymph node status.\"\n",
    ")\n",
    "\n",
    "# 6. Save the data if it's usable\n",
    "if is_usable:\n",
    "    # Create directory if it doesn't exist\n",
    "    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "    # Save the data\n",
    "    unbiased_linked_data.to_csv(out_data_file)\n",
    "    print(f\"Linked data saved to {out_data_file}\")\n",
    "else:\n",
    "    print(f\"Data quality check failed. The dataset is not suitable for association studies.\")"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}