{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "fcda06d7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:42:20.850907Z", "iopub.status.busy": "2025-03-25T07:42:20.850483Z", "iopub.status.idle": "2025-03-25T07:42:21.014781Z", "shell.execute_reply": "2025-03-25T07:42:21.014456Z" } }, "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 = \"Lung_Cancer\"\n", "cohort = \"GSE248830\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Lung_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Lung_Cancer/GSE248830\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Lung_Cancer/GSE248830.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Lung_Cancer/gene_data/GSE248830.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Lung_Cancer/clinical_data/GSE248830.csv\"\n", "json_path = \"../../output/preprocess/Lung_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "a10979a6", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "dba223dd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:42:21.016193Z", "iopub.status.busy": "2025-03-25T07:42:21.016055Z", "iopub.status.idle": "2025-03-25T07:42:21.037188Z", "shell.execute_reply": "2025-03-25T07:42:21.036887Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Unlocking Molecular mechanisms and identifying druggable targets in matched-paired brain metastasis of Breast and Lung cancers \"\n", "!Series_summary\t\"Introduction: The incidence of brain metastases in cancer patients is increasing, with lung and breast cancer being the most common sources. Despite advancements in targeted therapies, the prognosis remains poor, highlighting the importance to investigate the underlying mechanisms in brain metastases. The aim of this study was to investigate the differences in the molecular mechanisms involved in brain metastasis of breast and lung cancers. In addition, we aimed to identify cancer lineage-specific druggable targets in the brain metastasis. Methods: To that aim, a cohort of 44 FFPE tissue samples, including 22 breast cancer and 22 lung adenocarcinoma (LUAD) and their matched-paired brain metastases were collected. Targeted gene expression profiles of primary tumors were compared to their matched-paired brain metastases samples using nCounter PanCancer IO 360™ Panel of NanoString technologies. Pathway analysis was performed using gene set analysis (GSA) and gene set enrichment analysis (GSEA). The validation was performed by using Immunohistochemistry (IHC) to confirm the expression of immune checkpoint inhibitors. Results: Our results revealed the significant upregulation of cancer-related genes in primary tumors compared to their matched-paired brain metastases (adj. p ≤ 0.05). We found that upregulated differentially expressed genes in breast cancer brain metastasis (BM-BC) and brain metastasis from lung adenocarcinoma (BM-LUAD) were associated with the metabolic stress pathway, particularly related to the glycolysis. Additionally, we found that the upregulated genes in BM-BC and BM-LUAD played roles in immune response regulation, tumor growth, and proliferation. Importantly, we identified high expression of the immune checkpoint VTCN1 in BM-BC, and VISTA, IDO1, NT5E, and HDAC3 in BM-LUAD. Validation using immunohistochemistry further supported these findings. Conclusion: In conclusion, the findings highlight the significance of using matched-paired samples to identify cancer lineage-specific therapies that may improve brain metastasis patients outcomes.\"\n", "!Series_overall_design\t\"RNA was extracted from FFPE samples of (primary LUAD and their matched paired brain metastasis n=22, primary BC and their matched paired brain metastasis n=22)\"\n", "Sample Characteristics Dictionary:\n", "{0: ['age at diagnosis: 49', 'age at diagnosis: 44', 'age at diagnosis: 41', 'age at diagnosis: 40', 'age at diagnosis: 48', 'age at diagnosis: 42', 'age at diagnosis: 47', 'age at diagnosis: 53', 'age at diagnosis: 74', 'age at diagnosis: 58', 'age at diagnosis: 51', 'age at diagnosis: 55', 'age at diagnosis: 46', 'age at diagnosis: 59', 'age at diagnosis: 50', 'age at diagnosis: 57', 'age at diagnosis: 60', 'age at diagnosis: 69', 'age at diagnosis: n.a.', 'age at diagnosis: 65', 'age at diagnosis: 37', 'age at diagnosis: 63', 'age at diagnosis: 70', 'age at diagnosis: 66', 'age at diagnosis: 64'], 1: ['Sex: female', 'Sex: male'], 2: ['histology: TNBC', 'histology: ER+ PR+ HER2-', 'histology: Unknown', 'histology: ER- PR- HER2+', 'histology: ER+ PR-HER2+', 'histology: ER+ PR- HER2-', 'histology: ER- PR+ HER2-', 'histology: adenocaricnoma'], 3: ['smoking status: n.a', 'smoking status: former-smoker', 'smoking status: smoker', 'smoking status: Never smoking', 'smoking status: unknown', 'smoking status: former-roker'], 4: ['treatment after surgery of bm: surgery + chemotherpy', 'treatment after surgery of bm: surgery + chemotherpy + Radiotherapy', 'treatment after surgery of bm: surgery + chemotherapy + Radiotherapy', 'treatment after surgery of bm: surgery', 'treatment after surgery of bm: surgery + chemotherapy + Radiotherapy', 'treatment after surgery of bm: surgery + chemotherapy', 'treatment after surgery of bm: surgery + chemotherpy + Radiotherapy', 'treatment after surgery of bm: surgery + chemotheapy + Radiotherapy', 'treatment after surgery of bm: Chemoterapy', 'treatment after surgery of bm: Radiotherapy & Chemoterapy', 'treatment after surgery of bm: Radiotherapy', 'treatment after surgery of bm: Other', 'treatment after surgery of bm: Surgery & Chemotherapy & Radiotherapy', 'treatment after surgery of bm: surgery & Radiotherapy', 'treatment after surgery of bm: surgery & Radiochemotherapy', 'treatment after surgery of bm: No treatment', 'treatment after surgery of bm: WBRT', 'treatment after surgery of bm: SRT']}\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": "94011863", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "6cb93492", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:42:21.038200Z", "iopub.status.busy": "2025-03-25T07:42:21.038095Z", "iopub.status.idle": "2025-03-25T07:42:21.049457Z", "shell.execute_reply": "2025-03-25T07:42:21.049173Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical data:\n", "{'GSM7920782': [0.0, 49.0, 0.0], 'GSM7920783': [0.0, 44.0, 0.0], 'GSM7920784': [nan, 41.0, 0.0], 'GSM7920785': [0.0, 40.0, 0.0], 'GSM7920786': [0.0, 48.0, 0.0], 'GSM7920787': [nan, 42.0, 0.0], 'GSM7920788': [0.0, 47.0, 0.0], 'GSM7920789': [0.0, 53.0, 0.0], 'GSM7920790': [0.0, 41.0, 0.0], 'GSM7920791': [0.0, 74.0, 0.0], 'GSM7920792': [0.0, 58.0, 0.0], 'GSM7920793': [0.0, 51.0, 0.0], 'GSM7920794': [0.0, 55.0, 0.0], 'GSM7920795': [nan, 46.0, 0.0], 'GSM7920796': [0.0, 46.0, 0.0], 'GSM7920797': [0.0, 48.0, 0.0], 'GSM7920798': [0.0, 44.0, 0.0], 'GSM7920799': [0.0, 49.0, 0.0], 'GSM7920800': [0.0, 59.0, 0.0], 'GSM7920801': [0.0, 50.0, 0.0], 'GSM7920802': [0.0, 74.0, 0.0], 'GSM7920803': [0.0, 46.0, 0.0], 'GSM7920804': [1.0, 40.0, 0.0], 'GSM7920805': [1.0, 57.0, 1.0], 'GSM7920806': [1.0, 60.0, 1.0], 'GSM7920807': [1.0, 55.0, 0.0], 'GSM7920808': [1.0, 69.0, 0.0], 'GSM7920809': [1.0, nan, 0.0], 'GSM7920810': [1.0, nan, 1.0], 'GSM7920811': [1.0, 57.0, 1.0], 'GSM7920812': [1.0, nan, 0.0], 'GSM7920813': [1.0, 65.0, 1.0], 'GSM7920814': [1.0, 37.0, 1.0], 'GSM7920815': [1.0, 46.0, 0.0], 'GSM7920816': [1.0, 63.0, 1.0], 'GSM7920817': [1.0, 60.0, 1.0], 'GSM7920818': [1.0, 58.0, 0.0], 'GSM7920819': [1.0, 70.0, 0.0], 'GSM7920820': [1.0, 66.0, 0.0], 'GSM7920821': [1.0, 64.0, 1.0], 'GSM7920822': [1.0, 60.0, 1.0], 'GSM7920823': [1.0, 50.0, 0.0], 'GSM7920824': [1.0, 66.0, 1.0], 'GSM7920825': [1.0, 74.0, 1.0]}\n", "Clinical data saved to ../../output/preprocess/Lung_Cancer/clinical_data/GSE248830.csv\n" ] } ], "source": [ "# Step 1: Gene Expression Data Availability\n", "is_gene_available = True # The dataset appears to contain gene expression data (they mention RNA was extracted from samples)\n", "\n", "# Step 2: Variable Availability and Data Type Conversion\n", "\n", "# 2.1 Data Availability\n", "trait_row = 2 # Histology information can be used to determine lung cancer\n", "age_row = 0 # Age at diagnosis is available\n", "gender_row = 1 # Sex information is available\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert histology information to binary trait for lung cancer\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after the colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Determine if the histology relates to lung cancer\n", " if 'adenocaricnoma' in value.lower(): # Lung adenocarcinoma\n", " return 1\n", " elif any(term in value.lower() for term in ['tnbc', 'er+', 'er-', 'pr+', 'pr-', 'her2', 'breast']):\n", " return 0 # Breast cancer types\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age at diagnosis to numeric (continuous) value\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after the colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Handle non-available or special cases\n", " if value.lower() in ['n.a.', 'n.a', 'unknown', 'na']:\n", " return None\n", " \n", " # Try to convert to numeric\n", " try:\n", " return float(value)\n", " except ValueError:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender information to binary (0 for female, 1 for male)\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after the colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " \n", " if 'female' in value:\n", " return 0\n", " elif 'male' in value:\n", " return 1\n", " return None\n", "\n", "# Step 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", "# Step 4: Clinical Feature Extraction (only if trait_row is not None)\n", "if trait_row 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=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 data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical data:\")\n", " print(preview)\n", " \n", " # Save the clinical data to the designated output file\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": "4f8aeb89", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "aa9a058d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:42:21.050462Z", "iopub.status.busy": "2025-03-25T07:42:21.050357Z", "iopub.status.idle": "2025-03-25T07:42:21.064792Z", "shell.execute_reply": "2025-03-25T07:42:21.064520Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining matrix file structure...\n", "Line 0: !Series_title\t\"Unlocking Molecular mechanisms and identifying druggable targets in matched-paired brain metastasis of Breast and Lung cancers \"\n", "Line 1: !Series_geo_accession\t\"GSE248830\"\n", "Line 2: !Series_status\t\"Public on Dec 03 2023\"\n", "Line 3: !Series_submission_date\t\"Nov 28 2023\"\n", "Line 4: !Series_last_update_date\t\"Dec 03 2023\"\n", "Line 5: !Series_summary\t\"Introduction: The incidence of brain metastases in cancer patients is increasing, with lung and breast cancer being the most common sources. Despite advancements in targeted therapies, the prognosis remains poor, highlighting the importance to investigate the underlying mechanisms in brain metastases. The aim of this study was to investigate the differences in the molecular mechanisms involved in brain metastasis of breast and lung cancers. In addition, we aimed to identify cancer lineage-specific druggable targets in the brain metastasis. Methods: To that aim, a cohort of 44 FFPE tissue samples, including 22 breast cancer and 22 lung adenocarcinoma (LUAD) and their matched-paired brain metastases were collected. Targeted gene expression profiles of primary tumors were compared to their matched-paired brain metastases samples using nCounter PanCancer IO 360™ Panel of NanoString technologies. Pathway analysis was performed using gene set analysis (GSA) and gene set enrichment analysis (GSEA). The validation was performed by using Immunohistochemistry (IHC) to confirm the expression of immune checkpoint inhibitors. Results: Our results revealed the significant upregulation of cancer-related genes in primary tumors compared to their matched-paired brain metastases (adj. p ≤ 0.05). We found that upregulated differentially expressed genes in breast cancer brain metastasis (BM-BC) and brain metastasis from lung adenocarcinoma (BM-LUAD) were associated with the metabolic stress pathway, particularly related to the glycolysis. Additionally, we found that the upregulated genes in BM-BC and BM-LUAD played roles in immune response regulation, tumor growth, and proliferation. Importantly, we identified high expression of the immune checkpoint VTCN1 in BM-BC, and VISTA, IDO1, NT5E, and HDAC3 in BM-LUAD. Validation using immunohistochemistry further supported these findings. Conclusion: In conclusion, the findings highlight the significance of using matched-paired samples to identify cancer lineage-specific therapies that may improve brain metastasis patients outcomes.\"\n", "Line 6: !Series_overall_design\t\"RNA was extracted from FFPE samples of (primary LUAD and their matched paired brain metastasis n=22, primary BC and their matched paired brain metastasis n=22)\"\n", "Line 7: !Series_type\t\"Expression profiling by array\"\n", "Line 8: !Series_contributor\t\"Shiva,,Najjary\"\n", "Line 9: !Series_contributor\t\"Willem,,de Koning\"\n", "Found table marker at line 58\n", "First few lines after marker:\n", "\"ID_REF\"\t\"GSM7920782\"\t\"GSM7920783\"\t\"GSM7920784\"\t\"GSM7920785\"\t\"GSM7920786\"\t\"GSM7920787\"\t\"GSM7920788\"\t\"GSM7920789\"\t\"GSM7920790\"\t\"GSM7920791\"\t\"GSM7920792\"\t\"GSM7920793\"\t\"GSM7920794\"\t\"GSM7920795\"\t\"GSM7920796\"\t\"GSM7920797\"\t\"GSM7920798\"\t\"GSM7920799\"\t\"GSM7920800\"\t\"GSM7920801\"\t\"GSM7920802\"\t\"GSM7920803\"\t\"GSM7920804\"\t\"GSM7920805\"\t\"GSM7920806\"\t\"GSM7920807\"\t\"GSM7920808\"\t\"GSM7920809\"\t\"GSM7920810\"\t\"GSM7920811\"\t\"GSM7920812\"\t\"GSM7920813\"\t\"GSM7920814\"\t\"GSM7920815\"\t\"GSM7920816\"\t\"GSM7920817\"\t\"GSM7920818\"\t\"GSM7920819\"\t\"GSM7920820\"\t\"GSM7920821\"\t\"GSM7920822\"\t\"GSM7920823\"\t\"GSM7920824\"\t\"GSM7920825\"\n", "\"A2M\"\t13.21010181\t13.23796856\t14.72887794\t15.39966291\t12.9704642\t13.01480653\t12.52196701\t13.05548078\t13.21953796\t14.5433698\t13.56653683\t14.04009171\t12.24690257\t16.04180734\t13.02195006\t13.00398137\t12.29540866\t14.50931667\t12.71635563\t14.29272778\t13.39671666\t13.15857521\t11.99312399\t12.16231576\t12.75834508\t13.65664657\t12.2452909\t15.58159263\t13.98246295\t14.43351877\t13.62530162\t16.28517182\t13.86200686\t12.39949969\t12.63580212\t12.48708972\t11.74326099\t13.21937594\t12.49951258\t11.71945179\t12.50919386\t11.68252331\t10.88563213\t11.27723517\n", "\"ACVR1C\"\t5.128485232\t5.33685026\t5.611523438\t5.0417111\t6.342262311\t5.005300871\t4.148599881\t5.665522635\t5.548820676\t5.081208389\t5.838984267\t7.510046494\t6.094091585\t7.801141524\t5.372857226\t4.916850071\t4.940875903\t4.675189176\t5.105666299\t6.181648829\t7.639470969\t5.053745237\t3.082856032\t5.395786847\t5.657238092\t5.624061755\t7.96359265\t6.02495885\t7.01333872\t4.091856995\t5.953662277\t4.290159553\t6.227383555\t4.909104597\t5.756038706\t6.795791942\t6.873777306\t6.848304003\t5.106050619\t6.790117351\t3.936120513\t2.998025133\t6.339292445\t4.463216519\n", "\"ADAM12\"\t9.806557137\t12.37439721\t9.953351091\t8.507091985\t11.40215554\t10.73948938\t9.114680073\t11.09572918\t8.762302044\t9.60096376\t10.83532415\t6.905018371\t8.007620822\t9.31052825\t7.86296054\t8.406698031\t9.610874508\t9.862433654\t8.390395776\t9.489394117\t9.504641343\t9.417493508\t8.270208105\t7.668805341\t10.45823752\t6.492817221\t8.165226511\t7.918968154\t8.266225171\t9.687940236\t10.32289609\t6.338522575\t10.5678476\t6.82471241\t8.280338425\t6.973884264\t7.113935845\t8.036965567\t8.398832368\t5.346282587\t9.429915325\t7.863095553\t10.77408418\t4.708329017\n", "\"ADGRE1\"\t4.128485232\t3.751887759\t4.611523438\t4.582279482\t3.77151367\t4.420338371\t2.863197662\t4.800452215\t3.860764683\t3.844169192\t3.799455903\t6.998885294\t3.481648348\t5.000672987\t3.29193723\t3.309167493\t3.899055728\t5.399554734\t2.783738204\t4.358526591\t5.27617244\t3.425714014\t2.54228765\t3.132752441\t3.094301897\t3.559931417\t5.96359265\t5.247351271\t3.731303353\t4.577283822\t3.783737275\t6.256992689\t4.276293155\t5.494067098\t2.806079389\t5.92657855\t2.066422384\t6.447341689\t4.286622864\t3.665104771\t3.415288349\t1.190670211\t2.251829604\t-0.291670983\n", "Total lines examined: 59\n", "\n", "Attempting to extract gene data from matrix file...\n", "Successfully extracted gene data with 754 rows\n", "First 20 gene IDs:\n", "Index(['A2M', 'ACVR1C', 'ADAM12', 'ADGRE1', 'ADM', 'ADORA2A', 'AKT1', 'ALDOA',\n", " 'ALDOC', 'ANGPT1', 'ANGPT2', 'ANGPTL4', 'ANLN', 'APC', 'APH1B', 'API5',\n", " 'APLNR', 'APOE', 'APOL6', 'AQP9'],\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", "# Add diagnostic code to check file content and structure\n", "print(\"Examining matrix file structure...\")\n", "with gzip.open(matrix_file, 'rt') as file:\n", " table_marker_found = False\n", " lines_read = 0\n", " for i, line in enumerate(file):\n", " lines_read += 1\n", " if '!series_matrix_table_begin' in line:\n", " table_marker_found = True\n", " print(f\"Found table marker at line {i}\")\n", " # Read a few lines after the marker to check data structure\n", " next_lines = [next(file, \"\").strip() for _ in range(5)]\n", " print(\"First few lines after marker:\")\n", " for next_line in next_lines:\n", " print(next_line)\n", " break\n", " if i < 10: # Print first few lines to see file structure\n", " print(f\"Line {i}: {line.strip()}\")\n", " if i > 100: # Don't read the entire file\n", " break\n", " \n", " if not table_marker_found:\n", " print(\"Table marker '!series_matrix_table_begin' not found in first 100 lines\")\n", " print(f\"Total lines examined: {lines_read}\")\n", "\n", "# 2. Try extracting gene expression data from the matrix file again with better diagnostics\n", "try:\n", " print(\"\\nAttempting to extract 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: {str(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", "\n", "# If data extraction failed, try an alternative approach using pandas directly\n", "if not is_gene_available:\n", " print(\"\\nTrying alternative approach to read gene expression data...\")\n", " try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Skip lines until we find the marker\n", " for line in file:\n", " if '!series_matrix_table_begin' in line:\n", " break\n", " \n", " # Try to read the data directly with pandas\n", " gene_data = pd.read_csv(file, sep='\\t', index_col=0)\n", " \n", " if not gene_data.empty:\n", " print(f\"Successfully extracted gene data with alternative method: {gene_data.shape}\")\n", " print(\"First 20 gene IDs:\")\n", " print(gene_data.index[:20])\n", " is_gene_available = True\n", " else:\n", " print(\"Alternative extraction method also produced empty data\")\n", " except Exception as e:\n", " print(f\"Alternative extraction failed: {str(e)}\")\n" ] }, { "cell_type": "markdown", "id": "27f2b0e3", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "813cacef", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:42:21.065764Z", "iopub.status.busy": "2025-03-25T07:42:21.065658Z", "iopub.status.idle": "2025-03-25T07:42:21.067408Z", "shell.execute_reply": "2025-03-25T07:42:21.067126Z" } }, "outputs": [], "source": [ "# Examining the first few gene identifiers from the data\n", "# These look like standard human gene symbols (A2M, ACVR1C, ADAM12, etc.)\n", "# These are not probe IDs, Ensembl IDs, or other identifiers that would require mapping\n", "\n", "# Based on biomedical knowledge, these are standard HGNC gene symbols:\n", "# A2M = Alpha-2-Macroglobulin\n", "# ACVR1C = Activin A Receptor Type 1C\n", "# ADAM12 = ADAM Metallopeptidase Domain 12\n", "# etc.\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "52bec0f6", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 6, "id": "2dae4564", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:42:21.068397Z", "iopub.status.busy": "2025-03-25T07:42:21.068294Z", "iopub.status.idle": "2025-03-25T07:42:21.340741Z", "shell.execute_reply": "2025-03-25T07:42:21.340402Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Normalizing gene symbols using NCBI Gene database...\n", "After normalization: 746 unique genes remain\n", "Normalized gene expression data saved to ../../output/preprocess/Lung_Cancer/gene_data/GSE248830.csv\n", "\n", "Extracting clinical data directly from the matrix file...\n", "\n", "Processing clinical data...\n", "Extracted clinical data with shape: (3, 44)\n", "Clinical data saved to: ../../output/preprocess/Lung_Cancer/clinical_data/GSE248830.csv\n", "\n", "Linking clinical and genetic data...\n", "Found 44 common samples between clinical and genetic data\n", "Linked data shape: (44, 749)\n", "\n", "Handling missing values in linked data...\n", "Data shape after handling missing values: (41, 749)\n", "\n", "Evaluating trait and demographic feature bias...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "For the feature 'Lung_Cancer', the least common label is '0.0' with 19 occurrences. This represents 46.34% of the dataset.\n", "The distribution of the feature 'Lung_Cancer' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Quartiles for 'Age':\n", " 25%: 48.0\n", " 50% (Median): 55.078947368421055\n", " 75%: 60.0\n", "Min: 37.0\n", "Max: 74.0\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n", "For the feature 'Gender', the least common label is '1.0' with 12 occurrences. This represents 29.27% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n", "\n", "Saving linked data to ../../output/preprocess/Lung_Cancer/GSE248830.csv\n", "Linked data saved successfully!\n" ] } ], "source": [ "# 1. Normalize gene symbols using NCBI Gene database\n", "print(\"\\nNormalizing gene symbols using NCBI Gene database...\")\n", "try:\n", " gene_data_normalized = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"After normalization: {len(gene_data_normalized)} unique genes remain\")\n", " gene_data_cleaned = gene_data_normalized\n", " \n", " # Save the normalized gene expression data\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " gene_data_cleaned.to_csv(out_gene_data_file)\n", " print(f\"Normalized gene expression data saved to {out_gene_data_file}\")\n", "except Exception as e:\n", " print(f\"Error during gene symbol normalization: {str(e)}\")\n", " print(\"Falling back to original gene data\")\n", " gene_data_cleaned = gene_data.copy()\n", "\n", "# 2. We need to recreate the clinical data from the original matrix file\n", "print(\"\\nExtracting clinical data directly from the matrix file...\")\n", "# Extract clinical data from the matrix file again\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", "# Process clinical data\n", "print(\"\\nProcessing clinical data...\")\n", "# Create clinical features dataframe \n", "if trait_row is not None:\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 if age_row is not None else None,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender if gender_row is not None else None\n", " )\n", " \n", " print(f\"Extracted clinical data with shape: {selected_clinical_df.shape}\")\n", " # Save clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to: {out_clinical_data_file}\")\n", " \n", " is_trait_available = True\n", "else:\n", " selected_clinical_df = pd.DataFrame()\n", " is_trait_available = False\n", " print(\"No trait data available in clinical information.\")\n", "\n", "# 3. Link clinical and genetic data\n", "if is_trait_available and is_gene_available:\n", " print(\"\\nLinking clinical and genetic data...\")\n", " try:\n", " # Ensure the sample IDs match between clinical and genetic data\n", " common_samples = list(set(selected_clinical_df.columns).intersection(set(gene_data_cleaned.columns)))\n", " \n", " if len(common_samples) == 0:\n", " print(\"Warning: No common samples between clinical and genetic data\")\n", " linked_data = pd.DataFrame()\n", " is_biased = True\n", " else:\n", " print(f\"Found {len(common_samples)} common samples between clinical and genetic data\")\n", " \n", " # Filter data to include only common samples\n", " clinical_subset = selected_clinical_df[common_samples]\n", " genetic_subset = gene_data_cleaned[common_samples]\n", " \n", " # Link the data\n", " linked_data = pd.concat([clinical_subset, genetic_subset], axis=0).T\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " \n", " # 4. Handle missing values\n", " print(\"\\nHandling missing values in linked data...\")\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", " \n", " # 5. Determine if trait and demographic features are severely biased\n", " print(\"\\nEvaluating trait and demographic feature bias...\")\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " except Exception as e:\n", " print(f\"Error during data linking: {str(e)}\")\n", " linked_data = pd.DataFrame()\n", " is_biased = True\n", "else:\n", " print(\"\\nCannot create linked data: missing clinical or gene data\")\n", " linked_data = pd.DataFrame()\n", " is_biased = True\n", "\n", "# 6. Final validation and saving\n", "note = \"This dataset contains gene expression data from astrocytoma cell lines with modified GFAP isoform expression. The trait represents different experimental conditions related to the GFAPδ/GFAPα ratio.\"\n", "\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=is_biased if len(linked_data) > 0 else True,\n", " df=linked_data,\n", " note=note\n", ")\n", "\n", "# Save the linked data if it's usable\n", "if is_usable and len(linked_data) > 0:\n", " print(f\"\\nSaving linked data to {out_data_file}\")\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 successfully!\")\n", "else:\n", " print(f\"\\nDataset not usable for {trait} association studies due to bias or quality issues.\")" ] } ], "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 }