{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "3bb473bc", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:05:00.669438Z", "iopub.status.busy": "2025-03-25T08:05:00.669330Z", "iopub.status.idle": "2025-03-25T08:05:00.831450Z", "shell.execute_reply": "2025-03-25T08:05:00.831035Z" } }, "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 = \"Hypothyroidism\"\n", "cohort = \"GSE75685\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Hypothyroidism\"\n", "in_cohort_dir = \"../../input/GEO/Hypothyroidism/GSE75685\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Hypothyroidism/GSE75685.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Hypothyroidism/gene_data/GSE75685.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Hypothyroidism/clinical_data/GSE75685.csv\"\n", "json_path = \"../../output/preprocess/Hypothyroidism/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "8c0983a0", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "ef8079f1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:05:00.832656Z", "iopub.status.busy": "2025-03-25T08:05:00.832510Z", "iopub.status.idle": "2025-03-25T08:05:00.994283Z", "shell.execute_reply": "2025-03-25T08:05:00.993865Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Mexican Patients with Breast Cancer\"\n", "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n", "!Series_overall_design\t\"Refer to individual Series\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: Tumor Sample of Breast Cancer'], 1: ['gender: Female'], 2: ['rna ng/ul: 1083', 'rna ng/ul: 343', 'rna ng/ul: 111', 'rna ng/ul: 307', 'rna ng/ul: 401', 'rna ng/ul: 475', 'rna ng/ul: 728', 'rna ng/ul: 143.6', 'rna ng/ul: 224.7', 'rna ng/ul: 1458.3', 'rna ng/ul: 164', 'rna ng/ul: 370.2', 'rna ng/ul: 419.5', 'rna ng/ul: 693.6', 'rna ng/ul: 291.4', 'rna ng/ul: 1566.4', 'rna ng/ul: 69', 'rna ng/ul: 625.4', 'rna ng/ul: 151.6', 'rna ng/ul: 127.7', 'rna ng/ul: 1116.8', 'rna ng/ul: 333.9', 'rna ng/ul: 182.1', 'rna ng/ul: 437.4', 'rna ng/ul: 439', 'rna ng/ul: 178.2', 'rna ng/ul: 1365', 'rna ng/ul: 670', 'rna ng/ul: 840.6', 'rna ng/ul: 725'], 3: ['rna 260/280 (nanodrop): 2.15', 'rna 260/280 (nanodrop): 2.16', 'rna 260/280 (nanodrop): 2.19', 'rna 260/280 (nanodrop): 2.09', 'rna 260/280 (nanodrop): 2.35', 'rna 260/280 (nanodrop): 2.24', 'rna 260/280 (nanodrop): 2.17', 'rna 260/280 (nanodrop): 2.14', 'rna 260/280 (nanodrop): 2.07', 'rna 260/280 (nanodrop): 2.13', 'rna 260/280 (nanodrop): 2.11', 'rna 260/280 (nanodrop): 2.18', 'rna 260/280 (nanodrop): 2.1', 'rna 260/280 (nanodrop): 2.06', 'rna 260/280 (nanodrop): 2.08', 'rna 260/280 (nanodrop): 2.12', 'rna 260/280 (nanodrop): 1.96', 'rna 260/280 (nanodrop): 1.79', 'rna 260/280 (nanodrop): 2.05'], 4: ['rna 260/230 (nanodrop): 2.15', 'rna 260/230 (nanodrop): 1.18', 'rna 260/230 (nanodrop): 1.03', 'rna 260/230 (nanodrop): 2.32', 'rna 260/230 (nanodrop): 2.11', 'rna 260/230 (nanodrop): 2.16', 'rna 260/230 (nanodrop): 2.27', 'rna 260/230 (nanodrop): 1.27', 'rna 260/230 (nanodrop): 2.3', 'rna 260/230 (nanodrop): 2.18', 'rna 260/230 (nanodrop): 1.65', 'rna 260/230 (nanodrop): 1.63', 'rna 260/230 (nanodrop): 2.06', 'rna 260/230 (nanodrop): 1.52', 'rna 260/230 (nanodrop): 2.21', 'rna 260/230 (nanodrop): 1.69', 'rna 260/230 (nanodrop): 1.94', 'rna 260/230 (nanodrop): 1.01', 'rna 260/230 (nanodrop): 1.78', 'rna 260/230 (nanodrop): 1.7', 'rna 260/230 (nanodrop): 1.06', 'rna 260/230 (nanodrop): 1.22', 'rna 260/230 (nanodrop): 2.22', 'rna 260/230 (nanodrop): 1.79', 'rna 260/230 (nanodrop): 1.89', 'rna 260/230 (nanodrop): 2.08', 'rna 260/230 (nanodrop): 1.82', 'rna 260/230 (nanodrop): 2.01', 'rna 260/230 (nanodrop): 2.1', 'rna 260/230 (nanodrop): 2.25'], 5: ['rqi experion: 9.6', 'rqi experion: 8.9', 'rqi experion: 8.6', 'rqi experion: 8.1', 'rqi experion: 8.2', 'rqi experion: 8.5', 'rqi experion: 8.4', 'rqi experion: 7.7', 'rqi experion: 9.4', 'rqi experion: 8.8', 'rqi experion: 8', 'rqi experion: 9', 'rqi experion: 7.9', 'rqi experion: 6.8', 'rqi experion: 7.6', 'rqi experion: 8.7', 'rqi experion: 7.8', 'rqi experion: 10', 'rqi experion: 9.2', 'rqi experion: 8.3', 'rqi experion: 6.4', 'rqi experion: 7.2', 'rqi experion: 7.4', 'rqi experion: 6.6', 'rqi experion: 9.3', 'rqi experion: 9.9', 'rqi experion: 9.1'], 6: ['diagnosis: High grade invasive ductal carcinoma', 'diagnosis: Poorly differentiated ductal adenocarcinoma', 'diagnosis: Infiltrating ductal carcinoma high', 'diagnosis: Infiltrating ductal adenocarcinoma', 'diagnosis: Poorly differentiated invasive carcinoma with chondroid metaplasia', 'diagnosis: Poorly differentiated infiltrating ductal adenocarcinoma', 'diagnosis: Poorly differentiated invasive ductal adenocarcinoma', 'diagnosis: Invasive ductal carcinoma', 'diagnosis: Right Breast Ductal carcinoma in situ Left Breast infiltrating ductal adenocarcinoma poorly differentiated', 'diagnosis: Infiltrating lobular carcinoma high nuclear grade', 'diagnosis: Poorly differentiated invasive ductal carcinoma', 'diagnosis: High nuclear grade ductal carcinoma associated with carcinoma in situ', 'diagnosis: Invasive ductal adenocarcinoma', 'diagnosis: Poorly differentiated infiltrating ductal carcinoma', 'diagnosis: Moderately differentiated invasive ductal carcinoma', 'diagnosis: Undifferentiated carcinoma', 'diagnosis: Ductal carcinoma in situ comedonicus type', 'diagnosis: Moderately differentiated infiltrating ductal adenocarcinoma', 'diagnosis: Carcinoma in situ associated with comedo necrosis', 'diagnosis: Invasive ductal adenocarcinoma high nuclear grade', 'diagnosis: Infiltrating ductal carcinoma', 'diagnosis: Invasive ductal carcinoma, carcinoma in situ associated with comedo necrosis'], 7: ['histological grade: 3', 'histological grade: 2', 'histological grade: N/A', 'histological grade: 1'], 8: ['estrogen receptor immunohistochemestry: Neg', 'estrogen receptor immunohistochemestry: Pos'], 9: ['progesteron receptor immunohistochemestry: Neg', 'progesteron receptor immunohistochemestry: Pos', 'progesteron receptor immunohistochemestry: POs'], 10: ['her2 immunohistochemestry: Neg', 'her2 immunohistochemestry: Pos', 'her2 immunohistochemestry: N/A'], 11: ['her2 fish: N/A', 'her2 fish: Neg', 'her2 fish: Pos'], 12: ['percentage ki67 ihc: 0.7', 'percentage ki67 ihc: 0.05', 'percentage ki67 ihc: 0.03', 'percentage ki67 ihc: 0.07', 'percentage ki67 ihc: 0.02', 'percentage ki67 ihc: 0.0022', 'percentage ki67 ihc: N/A', 'percentage ki67 ihc: 0.1', 'percentage ki67 ihc: 0.12', 'percentage ki67 ihc: 0.85', 'percentage ki67 ihc: 0.01', 'percentage ki67 ihc: 0.8', 'percentage ki67 ihc: 0.15', 'percentage ki67 ihc: 0.08', 'percentage ki67 ihc: 0.4', 'percentage ki67 ihc: 0.6', 'percentage ki67 ihc: 0.04', 'percentage ki67 ihc: 0.06', 'percentage ki67 ihc: 0.22', 'percentage ki67 ihc: 0.35', 'percentage ki67 ihc: 0.25', 'percentage ki67 ihc: 0.2', 'percentage ki67 ihc: 0.45'], 13: ['p63 ihc: Absent', 'p63 ihc: N/A', 'p63 ihc: Neg', 'p63 ihc: Pos'], 14: ['e-cadherina ihc: N/A', 'e-cadherina ihc: Pos'], 15: ['t: 3', 't: 1', 't: 2', 't: 4'], 16: ['n: 1', 'n: 0', 'n: 2', 'n: 3'], 17: ['m: 0', 'm: x', 'm: 1'], 18: ['data at diagnosis: 2013-05-29', 'data at diagnosis: 2013-06-06', 'data at diagnosis: 2013-06-04', 'data at diagnosis: 2013-08-06', 'data at diagnosis: 2013-06-17', 'data at diagnosis: 2013-06-18', 'data at diagnosis: 2013-07-11', 'data at diagnosis: 2013-07-08', 'data at diagnosis: 2013-07-23', 'data at diagnosis: 2013-07-29', 'data at diagnosis: 2013-08-01', 'data at diagnosis: 2013-09-02', 'data at diagnosis: 2013-09-10', 'data at diagnosis: 2013-09-03', 'data at diagnosis: 2013-10-03', 'data at diagnosis: 2013-10-02', 'data at diagnosis: 2013-10-15', 'data at diagnosis: 2013-11-12', 'data at diagnosis: 2012-12-05', 'data at diagnosis: 2013-12-09', 'data at diagnosis: NA', 'data at diagnosis: 2013-11-20', 'data at diagnosis: 2014-02-21', 'data at diagnosis: 2014-03-10', 'data at diagnosis: 2014-03-18', 'data at diagnosis: 2014-04-02', 'data at diagnosis: 2014-05-14', 'data at diagnosis: 2014-03-25', 'data at diagnosis: 2014-04-04', 'data at diagnosis: 2014-04-01'], 19: ['age at diagnosis: 45', 'age at diagnosis: 41', 'age at diagnosis: 59', 'age at diagnosis: 57', 'age at diagnosis: 42', 'age at diagnosis: 49', 'age at diagnosis: 54', 'age at diagnosis: 31', 'age at diagnosis: 70', 'age at diagnosis: 44', 'age at diagnosis: 50', 'age at diagnosis: 56', 'age at diagnosis: 51', 'age at diagnosis: 58', 'age at diagnosis: 55', 'age at diagnosis: 71', 'age at diagnosis: 40', 'age at diagnosis: 62', 'age at diagnosis: 87', 'age at diagnosis: 36', 'age at diagnosis: 43', 'age at diagnosis: 48', 'age at diagnosis: 66', 'age at diagnosis: 53', 'age at diagnosis: 35', 'age at diagnosis: 68', 'age at diagnosis: 46'], 20: ['pathological family history: Maternal Aunt Breast Cancer', 'pathological family history: Neg', 'pathological family history: Mother Breast Cancer', 'pathological family history: Hypertension', 'pathological family history: Diabetes', 'pathological family history: Liver Cancer', 'pathological family history: Nev', 'pathological family history: Father Pancreas Cancer. Maternal Aunt Breast Cancer. Father Aunts Ovarian Cancer. Cousin Breast Cancer', 'pathological family history: Father Laringeal Cancer', 'pathological family history: Fater Liver Cancer', 'pathological family history: Sister Brain Cancer', 'pathological family history: Mother and Sister Ovarian Cancer', 'pathological family history: Paternal Grandmother Breast Cancer', 'pathological family history: Father Lung Cancer', 'pathological family history: Mother Endometrial Cancer', 'pathological family history: Diabetes and Heart Disease', 'pathological family history: Sister Liver Cancer', 'pathological family history: Sister Pancreatic Cancer', 'pathological family history: Sister GBM and Breast Cancer', 'pathological family history: Pos', 'pathological family history: Sister Breast Cancer, Brother Prostate Cancer'], 21: ['personal pathological hystory: Neg', 'personal pathological hystory: Rheumatoid Arthritis', 'personal pathological hystory: Hypertension', 'personal pathological hystory: Apendicitis', 'personal pathological hystory: Hypertension and Diabetes', 'personal pathological hystory: Hypothyroidism', 'personal pathological hystory: Diabetes', 'personal pathological hystory: Ocular Surgery', 'personal pathological hystory: 3 C sections', 'personal pathological hystory: 0', 'personal pathological hystory: C section', 'personal pathological hystory: Hysterechtomy', 'personal pathological hystory: Dyslipidemia', 'personal pathological hystory: Hypertension and Rheumatoid Artritis', 'personal pathological hystory: Knee Surgery', 'personal pathological hystory: Venous insuficiency'], 22: ['tabaquism: Neg', 'tabaquism: Pos'], 23: ['age at menarche: 14', 'age at menarche: 13', 'age at menarche: 11', 'age at menarche: 15', 'age at menarche: 12', 'age at menarche: 18'], 24: ['birads: 6', 'birads: 4', 'birads: 5', 'birads: 2', 'birads: N/A'], 25: ['breast affected: Right', 'breast affected: Left', 'breast affected: Both'], 26: ['initial highest diameter in mm by image: 51', 'initial highest diameter in mm by image: 7', 'initial highest diameter in mm by image: 40', 'initial highest diameter in mm by image: 60', 'initial highest diameter in mm by image: 22', 'initial highest diameter in mm by image: 25', 'initial highest diameter in mm by image: 20', 'initial highest diameter in mm by image: 35', 'initial highest diameter in mm by image: 70', 'initial highest diameter in mm by image: 86', 'initial highest diameter in mm by image: 80', 'initial highest diameter in mm by image: 50', 'initial highest diameter in mm by image: 16', 'initial highest diameter in mm by image: 30', 'initial highest diameter in mm by image: 39', 'initial highest diameter in mm by image: 41', 'initial highest diameter in mm by image: 90', 'initial highest diameter in mm by image: 67', 'initial highest diameter in mm by image: 150', 'initial highest diameter in mm by image: 42', 'initial highest diameter in mm by image: 48', 'initial highest diameter in mm by image: 100', 'initial highest diameter in mm by image: 36', 'initial highest diameter in mm by image: 57', 'initial highest diameter in mm by image: 4', 'initial highest diameter in mm by image: 37', 'initial highest diameter in mm by image: 33', 'initial highest diameter in mm by image: 32', 'initial highest diameter in mm by image: 14', 'initial highest diameter in mm by image: 200'], 27: ['initial clinical size in mm by palpation: 70', 'initial clinical size in mm by palpation: 20', 'initial clinical size in mm by palpation: 35', 'initial clinical size in mm by palpation: 60', 'initial clinical size in mm by palpation: 90', 'initial clinical size in mm by palpation: 40', 'initial clinical size in mm by palpation: 80', 'initial clinical size in mm by palpation: 0', 'initial clinical size in mm by palpation: 150', 'initial clinical size in mm by palpation: 15', 'initial clinical size in mm by palpation: 50', 'initial clinical size in mm by palpation: 100', 'initial clinical size in mm by palpation: 30'], 28: ['final pathology size in mm: 10', 'final pathology size in mm: 30', 'final pathology size in mm: 15', 'final pathology size in mm: 35', 'final pathology size in mm: 20', 'final pathology size in mm: 55', 'final pathology size in mm: 80', 'final pathology size in mm: 18', 'final pathology size in mm: 0', 'final pathology size in mm: 45', 'final pathology size in mm: 50', 'final pathology size in mm: 25', 'final pathology size in mm: 110', 'final pathology size in mm: 40', 'final pathology size in mm: 2', 'final pathology size in mm: 7', 'final pathology size in mm: 38', 'final pathology size in mm: 5'], 29: ['final clinical size in mm by palpation: 10', 'final clinical size in mm by palpation: 0', 'final clinical size in mm by palpation: 30', 'final clinical size in mm by palpation: 150', 'final clinical size in mm by palpation: 50', 'final clinical size in mm by palpation: 80'], 30: ['final number of positive ganglia: 0', 'final number of positive ganglia: 3', 'final number of positive ganglia: 4', 'final number of positive ganglia: 17', 'final number of positive ganglia: 12', 'final number of positive ganglia: 8', 'final number of positive ganglia: 2', 'final number of positive ganglia: 1', 'final number of positive ganglia: 5', 'final number of positive ganglia: 6', 'final number of positive ganglia: 9', 'final number of positive ganglia: 7'], 31: ['final number of resected ganglia: 20', 'final number of resected ganglia: 3', 'final number of resected ganglia: 22', 'final number of resected ganglia: 0', 'final number of resected ganglia: 37', 'final number of resected ganglia: 10', 'final number of resected ganglia: 15', 'final number of resected ganglia: 26', 'final number of resected ganglia: 11', 'final number of resected ganglia: 12', 'final number of resected ganglia: 17', 'final number of resected ganglia: 2', 'final number of resected ganglia: 33', 'final number of resected ganglia: 14', 'final number of resected ganglia: 16', 'final number of resected ganglia: 6', 'final number of resected ganglia: 24', 'final number of resected ganglia: 18', 'final number of resected ganglia: 4', 'final number of resected ganglia: 5', 'final number of resected ganglia: 41', 'final number of resected ganglia: 13', 'final number of resected ganglia: 34', 'final number of resected ganglia: 27', 'final number of resected ganglia: 29', 'final number of resected ganglia: 19', 'final number of resected ganglia: 23'], 32: ['response to treatment: Partial', 'response to treatment: Progresive', 'response to treatment: Poor', 'response to treatment: Complete'], 33: ['final surgery date: 2014-06-02', 'final surgery date: 2014-04-26', 'final surgery date: 2014-10-10', 'final surgery date: 2014-01-27', 'final surgery date: 2014-07-23', 'final surgery date: 2014-02-04', 'final surgery date: 2014-03-10', 'final surgery date: 2014-02-24', 'final surgery date: 2014-10-07', 'final surgery date: 2014-03-20', 'final surgery date: 2014-02-17', 'final surgery date: 2014-02-21', 'final surgery date: 2014-02-11', 'final surgery date: 2014-04-19', 'final surgery date: 2014-04-25', 'final surgery date: 2014-04-29', 'final surgery date: 2014-02-05', 'final surgery date: NA', 'final surgery date: 2014-07-14', 'final surgery date: 2014-06-20', 'final surgery date: 2014-07-16', 'final surgery date: 2014-07-31', 'final surgery date: 2014-08-22', 'final surgery date: 2014-10-15', 'final surgery date: 2014-10-22', 'final surgery date: 2014-09-06', 'final surgery date: 2014-10-20', 'final surgery date: 2014-05-19', 'final surgery date: 2014-10-27', 'final surgery date: 2014-10-29'], 34: ['chemotherapy1: Doxorubicin', 'chemotherapy1: Paclitaxel', 'chemotherapy1: Adriamicin', 'chemotherapy1: N/A', 'chemotherapy1: Taxol', 'chemotherapy1: Epirubicin', 'chemotherapy1: Trastuzumab', 'chemotherapy1: Tamoxifen'], 35: ['chemotherapy2: Cyclophosphamide', 'chemotherapy2: N/A', 'chemotherapy2: Trastazumab', 'chemotherapy2: Adriamicin', 'chemotherapy2: Doxorubicin', 'chemotherapy2: Taxol', 'chemotherapy2: Epirrubicin'], 36: ['chemotherapy3: N/A', 'chemotherapy3: Cyclophosphamide', 'chemotherapy3: Trastuzumab', 'chemotherapy3: Taxol', 'chemotherapy3: Adramicin', 'chemotherapy3: Paclitaxel', 'chemotherapy3: Adriamicin'], 37: ['chemotherapy4: N/A', 'chemotherapy4: Taxol', 'chemotherapy4: Trastuzumab'], 38: ['radiotherapy: Yes', 'radiotherapy: No', 'radiotherapy: N/A'], 39: ['date at relapse: N/A', 'date at relapse: 2014-04-24', 'date at relapse: 2014-09-09', 'date at relapse: 2014-10-15'], 40: ['place to metastasis: N/A', 'place to metastasis: Liver', 'place to metastasis: Lung'], 41: ['date at death: N/A', 'date at death: 2014-08-01', nan]}\n" ] } ], "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": "6866206b", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "0128142e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:05:00.995536Z", "iopub.status.busy": "2025-03-25T08:05:00.995413Z", "iopub.status.idle": "2025-03-25T08:05:01.019649Z", "shell.execute_reply": "2025-03-25T08:05:01.019330Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of extracted clinical features:\n", "{'GSM1963528': [0.0, 45.0], 'GSM1963529': [0.0, 41.0], 'GSM1963530': [0.0, 59.0], 'GSM1963531': [0.0, 57.0], 'GSM1963532': [0.0, 42.0], 'GSM1963533': [0.0, 49.0], 'GSM1963534': [0.0, 59.0], 'GSM1963535': [0.0, 54.0], 'GSM1963536': [0.0, 54.0], 'GSM1963537': [0.0, 31.0], 'GSM1963538': [0.0, 70.0], 'GSM1963539': [0.0, 44.0], 'GSM1963540': [0.0, 50.0], 'GSM1963541': [0.0, 42.0], 'GSM1963542': [0.0, 56.0], 'GSM1963543': [1.0, 51.0], 'GSM1963544': [0.0, 58.0], 'GSM1963545': [0.0, 55.0], 'GSM1963546': [0.0, 71.0], 'GSM1963547': [0.0, 42.0], 'GSM1963548': [0.0, 41.0], 'GSM1963549': [0.0, 40.0], 'GSM1963550': [0.0, 57.0], 'GSM1963551': [0.0, 62.0], 'GSM1963552': [0.0, 87.0], 'GSM1963553': [0.0, 36.0], 'GSM1963554': [0.0, 50.0], 'GSM1963555': [0.0, 45.0], 'GSM1963556': [0.0, 43.0], 'GSM1963557': [0.0, 42.0], 'GSM1963558': [0.0, 43.0], 'GSM1963559': [0.0, 44.0], 'GSM1963560': [0.0, 43.0], 'GSM1963561': [0.0, 48.0], 'GSM1963562': [0.0, 45.0], 'GSM1963563': [0.0, 51.0], 'GSM1963564': [0.0, 56.0], 'GSM1963565': [0.0, 57.0], 'GSM1963566': [0.0, 41.0], 'GSM1963567': [0.0, 48.0], 'GSM1963568': [0.0, 66.0], 'GSM1963569': [0.0, 53.0], 'GSM1963570': [0.0, 36.0], 'GSM1963571': [0.0, 51.0], 'GSM1963572': [0.0, 57.0], 'GSM1963573': [0.0, 45.0], 'GSM1963574': [0.0, 55.0], 'GSM1963575': [0.0, 35.0], 'GSM1963576': [0.0, 44.0], 'GSM1963577': [0.0, 68.0], 'GSM1963578': [0.0, 46.0], 'GSM1963579': [0.0, 58.0], 'GSM1963580': [0.0, 45.0], 'GSM1963581': [0.0, 54.0]}\n", "Clinical data saved to ../../output/preprocess/Hypothyroidism/clinical_data/GSE75685.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Looking at background and sample characteristics, this appears to be a breast cancer dataset\n", "# There's no explicit mention of gene expression, but as a SuperSeries from GEO, it likely contains gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait (Hypothyroidism), examining row 21 which contains personal pathological history\n", "# There is a value \"personal pathological hystory: Hypothyroidism\" in row 21\n", "trait_row = 21\n", "\n", "# For age, examining row 19 which contains \"age at diagnosis\" values\n", "age_row = 19\n", "\n", "# For gender, examining row 1 which contains \"gender: Female\"\n", "# All samples are female, which means gender is a constant feature (not useful for association studies)\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert trait value to binary (1 for Hypothyroidism, 0 for others)\"\"\"\n", " if value is None or pd.isna(value):\n", " return None\n", " # Extract the part after colon if it exists\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " # Check if \"Hypothyroidism\" is mentioned in the value\n", " if \"Hypothyroidism\" in value:\n", " return 1\n", " else:\n", " return 0\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to continuous numeric value\"\"\"\n", " if value is None or pd.isna(value):\n", " return None\n", " # Extract the part after colon if it exists\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " # Try to convert to integer\n", " try:\n", " return int(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "# Not needed since gender data is constant, but for completeness:\n", "def convert_gender(value):\n", " \"\"\"Convert gender value to binary (0 for female, 1 for male)\"\"\"\n", " if value is None or pd.isna(value):\n", " return None\n", " # Extract the part after colon if it exists\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " # Convert to binary\n", " if value == 'female':\n", " return 0\n", " elif value == 'male':\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Trait data is available (trait_row is not None)\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", "# Since trait_row is not None, we should extract clinical features\n", "if trait_row is not None and 'clinical_data' in locals():\n", " # Use the helper function to 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=None # No need for gender conversion since it's constant\n", " )\n", " \n", " # Preview the extracted clinical features\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of extracted clinical features:\")\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, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "39193b04", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "465b25da", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:05:01.020829Z", "iopub.status.busy": "2025-03-25T08:05:01.020721Z", "iopub.status.idle": "2025-03-25T08:05:01.276416Z", "shell.execute_reply": "2025-03-25T08:05:01.275773Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting gene data from matrix file:\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully extracted gene data with 45220 rows\n", "First 20 gene IDs:\n", "Index(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13',\n", " '14', '15', '16', '17', '18', '19', '20'],\n", " dtype='object', name='ID')\n", "\n", "Gene expression data available: True\n" ] } ], "source": [ "# 1. Get the file paths for the SOFT file and matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Extract gene expression data from the matrix file\n", "try:\n", " print(\"Extracting gene data from matrix file:\")\n", " gene_data = get_genetic_data(matrix_file)\n", " if gene_data.empty:\n", " print(\"Extracted gene expression data is empty\")\n", " is_gene_available = False\n", " else:\n", " print(f\"Successfully extracted gene data with {len(gene_data.index)} rows\")\n", " print(\"First 20 gene IDs:\")\n", " print(gene_data.index[:20])\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n", " print(\"This dataset appears to have an empty or malformed gene expression matrix\")\n", " is_gene_available = False\n", "\n", "print(f\"\\nGene expression data available: {is_gene_available}\")\n" ] }, { "cell_type": "markdown", "id": "f614cedf", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "27a85807", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:05:01.278207Z", "iopub.status.busy": "2025-03-25T08:05:01.278081Z", "iopub.status.idle": "2025-03-25T08:05:01.280355Z", "shell.execute_reply": "2025-03-25T08:05:01.279921Z" } }, "outputs": [], "source": [ "# The gene identifiers shown in the previous step (1, 2, 3, etc.) are numeric identifiers\n", "# and not standard human gene symbols like BRCA1, TP53, etc.\n", "# These numeric identifiers need to be mapped to proper gene symbols for biological interpretation.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "b8c0357d", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "e0fb0041", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:05:01.282012Z", "iopub.status.busy": "2025-03-25T08:05:01.281901Z", "iopub.status.idle": "2025-03-25T08:05:05.770058Z", "shell.execute_reply": "2025-03-25T08:05:05.769384Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting gene annotation data from SOFT file...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully extracted gene annotation data with 3353129 rows\n", "\n", "Gene annotation preview (first few rows):\n", "{'ID': ['1', '2', '3', '4', '5'], 'COL': ['266', '266', '266', '266', '266'], 'ROW': ['170', '168', '166', '164', '162'], 'NAME': ['GE_BrightCorner', 'DarkCorner', 'DarkCorner', 'DarkCorner', 'DarkCorner'], 'SPOT_ID': ['GE_BrightCorner', 'DarkCorner', 'DarkCorner', 'DarkCorner', 'DarkCorner'], 'CONTROL_TYPE': ['pos', 'pos', 'pos', 'pos', 'pos'], 'REFSEQ': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan], 'GENE': [nan, nan, nan, nan, nan], 'GENE_SYMBOL': [nan, nan, nan, nan, nan], 'GENE_NAME': [nan, nan, nan, nan, nan], 'UNIGENE_ID': [nan, nan, nan, nan, nan], 'ENSEMBL_ID': [nan, nan, nan, nan, nan], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': [nan, nan, nan, nan, nan], 'CHROMOSOMAL_LOCATION': [nan, nan, nan, nan, nan], 'CYTOBAND': [nan, nan, nan, nan, nan], 'DESCRIPTION': [nan, nan, nan, nan, nan], 'GO_ID': [nan, nan, nan, nan, nan], 'SEQUENCE': [nan, nan, nan, nan, nan], 'SPOT_ID.1': [nan, nan, nan, nan, nan], 'ORDER': [1.0, 2.0, 3.0, 4.0, 5.0]}\n", "\n", "Column names in gene annotation data:\n", "['ID', 'COL', 'ROW', 'NAME', 'SPOT_ID', 'CONTROL_TYPE', 'REFSEQ', 'GB_ACC', 'GENE', 'GENE_SYMBOL', 'GENE_NAME', 'UNIGENE_ID', 'ENSEMBL_ID', 'TIGR_ID', 'ACCESSION_STRING', 'CHROMOSOMAL_LOCATION', 'CYTOBAND', 'DESCRIPTION', 'GO_ID', 'SEQUENCE', 'SPOT_ID.1', 'ORDER']\n", "\n", "The dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\n", "Number of rows with GenBank accessions: 50964 out of 3353129\n", "\n", "The dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\n", "Example SPOT_ID format: GE_BrightCorner\n" ] } ], "source": [ "# 1. Extract gene annotation data from the SOFT file\n", "print(\"Extracting gene annotation data from SOFT file...\")\n", "try:\n", " # Use the library function to extract gene annotation\n", " gene_annotation = get_gene_annotation(soft_file)\n", " print(f\"Successfully extracted gene annotation data with {len(gene_annotation.index)} rows\")\n", " \n", " # Preview the annotation DataFrame\n", " print(\"\\nGene annotation preview (first few rows):\")\n", " print(preview_df(gene_annotation))\n", " \n", " # Show column names to help identify which columns we need for mapping\n", " print(\"\\nColumn names in gene annotation data:\")\n", " print(gene_annotation.columns.tolist())\n", " \n", " # Check for relevant mapping columns\n", " if 'GB_ACC' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\")\n", " # Count non-null values in GB_ACC column\n", " non_null_count = gene_annotation['GB_ACC'].count()\n", " print(f\"Number of rows with GenBank accessions: {non_null_count} out of {len(gene_annotation)}\")\n", " \n", " if 'SPOT_ID' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\")\n", " print(\"Example SPOT_ID format:\", gene_annotation['SPOT_ID'].iloc[0])\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation data: {e}\")\n", " is_gene_available = False\n" ] }, { "cell_type": "markdown", "id": "cbc87d0a", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "ff3915d8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:05:05.771984Z", "iopub.status.busy": "2025-03-25T08:05:05.771856Z", "iopub.status.idle": "2025-03-25T08:05:06.673896Z", "shell.execute_reply": "2025-03-25T08:05:06.673258Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Identifying mapping columns...\n", "Found ID and GENE_SYMBOL columns for mapping\n", "Creating gene mapping dataframe...\n", "Created mapping dataframe with 35657 rows\n", "First few rows of mapping dataframe:\n", "{'ID': ['12', '14', '15', '16', '18'], 'Gene': ['APOBEC3B', 'ATP11B', 'LOC100132006', 'DNAJA1', 'EHMT2']}\n", "\n", "Converting probe-level measurements to gene expression data...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Converted to gene expression data with 18380 genes\n", "First few gene symbols:\n", "['A1BG', 'A1CF', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAAS']\n", "\n", "Normalizing gene symbols...\n", "After normalization: 17901 genes\n", "First few normalized gene symbols:\n", "['A1BG', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAAS', 'AACS', 'AADAC']\n", "\n", "Saving gene expression data...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data saved to ../../output/preprocess/Hypothyroidism/gene_data/GSE75685.csv\n" ] } ], "source": [ "# 1. Identify mapping columns\n", "# From previous output, we can see the gene expression data uses 'ID' as identifiers\n", "# The annotation data has 'ID' and 'GENE_SYMBOL' columns that we need for mapping\n", "\n", "print(\"Identifying mapping columns...\")\n", "# Check if the relevant columns exist in gene_annotation\n", "if 'ID' in gene_annotation.columns and 'GENE_SYMBOL' in gene_annotation.columns:\n", " print(\"Found ID and GENE_SYMBOL columns for mapping\")\n", " \n", " # 2. Get gene mapping dataframe\n", " print(\"Creating gene mapping dataframe...\")\n", " # Extract ID and GENE_SYMBOL columns for mapping\n", " mapping_df = get_gene_mapping(gene_annotation, 'ID', 'GENE_SYMBOL')\n", " print(f\"Created mapping dataframe with {len(mapping_df)} rows\")\n", " print(\"First few rows of mapping dataframe:\")\n", " print(preview_df(mapping_df))\n", " \n", " # 3. Apply gene mapping to convert probe-level data to gene expression data\n", " print(\"\\nConverting probe-level measurements to gene expression data...\")\n", " gene_data = apply_gene_mapping(gene_data, mapping_df)\n", " print(f\"Converted to gene expression data with {len(gene_data)} genes\")\n", " print(\"First few gene symbols:\")\n", " print(gene_data.index[:10].tolist())\n", " \n", " # Check if we have any mapped genes\n", " if len(gene_data) == 0:\n", " print(\"Warning: No genes were mapped. Check if the annotation data is correct.\")\n", " is_gene_available = False\n", " else:\n", " # Normalize gene symbols to ensure consistency\n", " print(\"\\nNormalizing gene symbols...\")\n", " gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"After normalization: {len(gene_data)} genes\")\n", " print(\"First few normalized gene symbols:\")\n", " print(gene_data.index[:10].tolist())\n", " \n", " # Save the gene expression data\n", " print(\"\\nSaving 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 data saved to {out_gene_data_file}\")\n", " \n", "else:\n", " print(\"Error: Required columns for mapping not found in annotation data\")\n", " is_gene_available = False\n" ] }, { "cell_type": "markdown", "id": "0d19942f", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "f6a3fa40", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:05:06.675787Z", "iopub.status.busy": "2025-03-25T08:05:06.675662Z", "iopub.status.idle": "2025-03-25T08:05:12.185474Z", "shell.execute_reply": "2025-03-25T08:05:12.185023Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (17901, 54)\n", "Gene data shape after normalization: (17901, 54)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Hypothyroidism/gene_data/GSE75685.csv\n", "Clinical data saved to ../../output/preprocess/Hypothyroidism/clinical_data/GSE75685.csv\n", "Linked data shape: (54, 17903)\n", "\n", "Handling missing values...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After missing value handling, linked data shape: (54, 17903)\n", "\n", "Evaluating feature bias...\n", "For the feature 'Hypothyroidism', the least common label is '1.0' with 1 occurrences. This represents 1.85% of the dataset.\n", "The distribution of the feature 'Hypothyroidism' in this dataset is severely biased.\n", "\n", "Quartiles for 'Age':\n", " 25%: 43.0\n", " 50% (Median): 49.5\n", " 75%: 56.75\n", "Min: 31.0\n", "Max: 87.0\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n", "Trait bias evaluation result: True\n", "\n", "Dataset usability: False\n", "Dataset is not usable for Hypothyroidism association studies. Data not saved.\n" ] } ], "source": [ "# 1. Normalize gene symbols and extract from step 3 and 6\n", "# Load the gene expression data (already loaded from Step 6)\n", "print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", "\n", "try:\n", " # Normalize gene symbols using the NCBI Gene database information\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " \n", " if normalized_gene_data.empty:\n", " print(\"Normalization resulted in empty dataframe. Using original gene data instead.\")\n", " normalized_gene_data = gene_data\n", " \n", " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", " \n", " # Save the normalized gene data to the output file\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " normalized_gene_data.to_csv(out_gene_data_file)\n", " print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "except Exception as e:\n", " print(f\"Error normalizing gene data: {e}. Using original gene data instead.\")\n", " normalized_gene_data = gene_data\n", " # Save the original gene data if normalization fails\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " normalized_gene_data.to_csv(out_gene_data_file)\n", "\n", "# 2. Link clinical and genetic data\n", "# Use the trait_row identified in Step 2 (trait_row = 1) to extract trait data\n", "is_trait_available = trait_row is not None\n", "\n", "if is_trait_available:\n", " # Extract clinical features using the function and conversion methods from Step 2\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", " # Save clinical features\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", " # Link 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", "else:\n", " # Create a minimal dataframe with just the trait column\n", " linked_data = pd.DataFrame({trait: [np.nan]})\n", " print(\"No trait data available, creating minimal dataframe for validation.\")\n", "\n", "# 3. Handle missing values in the linked data\n", "if is_trait_available:\n", " print(\"\\nHandling missing values...\")\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"After missing value handling, linked data shape: {linked_data.shape}\")\n", "\n", "# 4. Determine whether trait and demographic features are biased\n", "if is_trait_available and not linked_data.empty and len(linked_data.columns) > 1:\n", " print(\"\\nEvaluating feature bias...\")\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " print(f\"Trait bias evaluation result: {is_biased}\")\n", "else:\n", " is_biased = False\n", " print(\"Skipping bias evaluation due to insufficient data.\")\n", "\n", "# 5. Final validation and save metadata\n", "note = \"\"\n", "if not is_trait_available:\n", " note = f\"Dataset contains gene expression data but no {trait} measurements.\"\n", "elif is_biased:\n", " note = f\"Dataset contains {trait} data but its distribution is severely biased.\"\n", "\n", "# 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=is_gene_available, \n", " is_trait_available=is_trait_available, \n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=note\n", ")\n", "\n", "# 6. Save the linked data if usable\n", "print(f\"\\nDataset usability: {is_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(f\"Dataset is not usable for {trait} association studies. Data not saved.\")" ] } ], "metadata": { "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.16" } }, "nbformat": 4, "nbformat_minor": 5 }