{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "47adfbfc", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:17:19.343409Z", "iopub.status.busy": "2025-03-25T07:17:19.343308Z", "iopub.status.idle": "2025-03-25T07:17:19.505138Z", "shell.execute_reply": "2025-03-25T07:17:19.504770Z" } }, "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 = \"Kidney_Clear_Cell_Carcinoma\"\n", "cohort = \"GSE117230\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Kidney_Clear_Cell_Carcinoma\"\n", "in_cohort_dir = \"../../input/GEO/Kidney_Clear_Cell_Carcinoma/GSE117230\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Kidney_Clear_Cell_Carcinoma/GSE117230.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Kidney_Clear_Cell_Carcinoma/gene_data/GSE117230.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Kidney_Clear_Cell_Carcinoma/clinical_data/GSE117230.csv\"\n", "json_path = \"../../output/preprocess/Kidney_Clear_Cell_Carcinoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "f237dbbc", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "7736454d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:17:19.506583Z", "iopub.status.busy": "2025-03-25T07:17:19.506445Z", "iopub.status.idle": "2025-03-25T07:17:19.668565Z", "shell.execute_reply": "2025-03-25T07:17:19.668256Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Transcriptional profiling of paired ccRCC patient CD8+ and CD19+ lymphocytes isolated from tumors, normal tissues, and circulating peripheral blood\"\n", "!Series_summary\t\"Tumor infiltrating lymphocytes are widely associated with positive outcomes, but are still markers of a systemic failed immune response against unresolved cancer. Cancer immunotherapies can reverse their tolerance phenotypes, while preserving tumor-reactivity and neoantigen-specificity shared with circulating immune cells. We performed comprehensive transcriptomic analyses to identify gene signatures common to circulating and tumor infiltrating lymphocytes in the context of clear cell renal cell carcinoma. Modulated genes also associated with disease outcome were validated in other cancer types. Using bioinformatics we identified practical diagnostic markers and actionable targets of the failed immune response. On circulating lymphocytes, three genes could efficiently stratify patients from healthy control donors. From their associations with resistance to cancer immunotherapies as well as viral and bacterial infections, we have uncovered not only pan-cancer, but pan-pathology failed immune response gene signatures.\"\n", "!Series_overall_design\t\"CRCHUM kidney biobank consented, TNM stages I-III clear cell renal cell carcinoma (ccRCC) patients underwent resection at the CHUM, Montreal, Quebec from 2013 to 2017. Microarray analysis was performed on paired patient (pt) CD8+ T cells and CD19+ B cells isolated from ccRCC tumors (TIL, TIL-B), normal tumor-adjacent tissue infiltrating immune cells (TIIC), peripheral blood mononuclear cells (PBMC) from patients (ptPBL), and from age-matched healthy control donors (cdPBL).\"\n", "Sample Characteristics Dictionary:\n", "{0: ['disease state: Healthy control donor', 'disease state: ccRCC patient'], 1: ['tissue: CD8+ T cell from blood', 'tissue: CD8+ T cell from tissue', 'tissue: CD8+ T cell from tumor', 'tissue: CD19+ T cell from blood', 'tissue: CD19+ T cell from tissue', 'tissue: CD19+ T cell from tumor']}\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": "0390e6b1", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "808e8f6e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:17:19.669813Z", "iopub.status.busy": "2025-03-25T07:17:19.669702Z", "iopub.status.idle": "2025-03-25T07:17:19.677049Z", "shell.execute_reply": "2025-03-25T07:17:19.676750Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{'GSM3288712': [0.0], 'GSM3288713': [0.0], 'GSM3288714': [0.0], 'GSM3288715': [0.0], 'GSM3288716': [0.0], 'GSM3288717': [1.0], 'GSM3288718': [1.0], 'GSM3288719': [1.0], 'GSM3288720': [1.0], 'GSM3288721': [1.0], 'GSM3288722': [1.0], 'GSM3288723': [1.0], 'GSM3288724': [1.0], 'GSM3288725': [1.0], 'GSM3288726': [1.0], 'GSM3288727': [1.0], 'GSM3288728': [1.0], 'GSM3288729': [1.0], 'GSM3288730': [1.0], 'GSM3288731': [1.0], 'GSM3288732': [0.0], 'GSM3288733': [0.0], 'GSM3288734': [0.0], 'GSM3288735': [0.0], 'GSM3288736': [0.0], 'GSM3288737': [1.0], 'GSM3288738': [1.0], 'GSM3288739': [1.0], 'GSM3288740': [1.0], 'GSM3288741': [1.0], 'GSM3288742': [1.0], 'GSM3288743': [1.0], 'GSM3288744': [1.0], 'GSM3288746': [1.0], 'GSM3288747': [1.0], 'GSM3288749': [1.0], 'GSM3288751': [1.0], 'GSM3288753': [1.0], 'GSM3288755': [1.0], 'GSM3288757': [1.0]}\n", "Clinical data saved to ../../output/preprocess/Kidney_Clear_Cell_Carcinoma/clinical_data/GSE117230.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# This dataset appears to be about transcriptional profiling, which indicates gene expression data is likely available\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "# Extract trait information from the sample characteristics dictionary\n", "# The disease state is in row 0, indicating clear cell renal cell carcinoma (ccRCC) status\n", "trait_row = 0\n", "\n", "# No age information is provided in the sample characteristics\n", "age_row = None\n", "\n", "# No gender information is provided in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert disease state to binary: 1 for ccRCC patient, 0 for healthy control\n", " \"\"\"\n", " if value is None or \":\" not in value:\n", " return None\n", " \n", " value = value.split(\":\", 1)[1].strip().lower()\n", " \n", " if \"ccrcc patient\" in value:\n", " return 1\n", " elif \"healthy control\" in value:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"\n", " Convert age to continuous value\n", " \"\"\"\n", " # Not used in this dataset, but defined for completeness\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"\n", " Convert gender to binary: 1 for male, 0 for female\n", " \"\"\"\n", " # Not used in this dataset, but defined for completeness\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and save cohort info (initial filtering)\n", "validate_and_save_cohort_info(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", "# 4. Clinical Feature Extraction\n", "# We confirmed trait_row is not None, so we proceed with clinical feature extraction\n", "if trait_row is not None:\n", " # Extract clinical features using the existing clinical_data variable\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 selected clinical features\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Save the 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": "378a7e68", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "a0614524", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:17:19.678271Z", "iopub.status.busy": "2025-03-25T07:17:19.678165Z", "iopub.status.idle": "2025-03-25T07:17:19.910722Z", "shell.execute_reply": "2025-03-25T07:17:19.910341Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining matrix file structure...\n", "Line 0: !Series_title\t\"Transcriptional profiling of paired ccRCC patient CD8+ and CD19+ lymphocytes isolated from tumors, normal tissues, and circulating peripheral blood\"\n", "Line 1: !Series_geo_accession\t\"GSE117230\"\n", "Line 2: !Series_status\t\"Public on Oct 17 2020\"\n", "Line 3: !Series_submission_date\t\"Jul 17 2018\"\n", "Line 4: !Series_last_update_date\t\"Oct 24 2020\"\n", "Line 5: !Series_summary\t\"Tumor infiltrating lymphocytes are widely associated with positive outcomes, but are still markers of a systemic failed immune response against unresolved cancer. Cancer immunotherapies can reverse their tolerance phenotypes, while preserving tumor-reactivity and neoantigen-specificity shared with circulating immune cells. We performed comprehensive transcriptomic analyses to identify gene signatures common to circulating and tumor infiltrating lymphocytes in the context of clear cell renal cell carcinoma. Modulated genes also associated with disease outcome were validated in other cancer types. Using bioinformatics we identified practical diagnostic markers and actionable targets of the failed immune response. On circulating lymphocytes, three genes could efficiently stratify patients from healthy control donors. From their associations with resistance to cancer immunotherapies as well as viral and bacterial infections, we have uncovered not only pan-cancer, but pan-pathology failed immune response gene signatures.\"\n", "Line 6: !Series_overall_design\t\"CRCHUM kidney biobank consented, TNM stages I-III clear cell renal cell carcinoma (ccRCC) patients underwent resection at the CHUM, Montreal, Quebec from 2013 to 2017. Microarray analysis was performed on paired patient (pt) CD8+ T cells and CD19+ B cells isolated from ccRCC tumors (TIL, TIL-B), normal tumor-adjacent tissue infiltrating immune cells (TIIC), peripheral blood mononuclear cells (PBMC) from patients (ptPBL), and from age-matched healthy control donors (cdPBL).\"\n", "Line 7: !Series_type\t\"Expression profiling by array\"\n", "Line 8: !Series_contributor\t\"Anne,,Monette\"\n", "Line 9: !Series_contributor\t\"Nadia,A,Al-Banna\"\n", "Found table marker at line 66\n", "First few lines after marker:\n", "\"ID_REF\"\t\"GSM3288712\"\t\"GSM3288713\"\t\"GSM3288714\"\t\"GSM3288715\"\t\"GSM3288716\"\t\"GSM3288717\"\t\"GSM3288718\"\t\"GSM3288719\"\t\"GSM3288720\"\t\"GSM3288721\"\t\"GSM3288722\"\t\"GSM3288723\"\t\"GSM3288724\"\t\"GSM3288725\"\t\"GSM3288726\"\t\"GSM3288727\"\t\"GSM3288728\"\t\"GSM3288729\"\t\"GSM3288730\"\t\"GSM3288731\"\t\"GSM3288732\"\t\"GSM3288733\"\t\"GSM3288734\"\t\"GSM3288735\"\t\"GSM3288736\"\t\"GSM3288737\"\t\"GSM3288738\"\t\"GSM3288739\"\t\"GSM3288740\"\t\"GSM3288741\"\t\"GSM3288742\"\t\"GSM3288743\"\t\"GSM3288744\"\t\"GSM3288746\"\t\"GSM3288747\"\t\"GSM3288749\"\t\"GSM3288751\"\t\"GSM3288753\"\t\"GSM3288755\"\t\"GSM3288757\"\n", "\"2824546_st\"\t18.6342\t19.0542\t18.6035\t18.9332\t19.2311\t18.164\t18.7272\t17.4594\t17.5372\t17.3\t16.9987\t15.6102\t17.018\t17.3834\t14.8346\t14.5328\t16.764\t16.1544\t16.1184\t16.2807\t18.6945\t18.8745\t18.9343\t19.6116\t19.0679\t17.4775\t17.6069\t18.5135\t17.8265\t17.4907\t18.1062\t16.092\t17.9597\t16.9357\t15.7306\t17.6588\t17.449\t17.0598\t15.4188\t13.7693\n", "\"2824549_st\"\t19.6455\t19.9169\t19.5091\t19.9258\t19.9104\t19.7114\t19.8291\t18.4751\t19.0521\t18.3677\t18.8614\t16.6115\t17.726\t19.168\t15.6469\t15.2985\t18.1849\t17.5017\t17.5419\t18.3436\t19.5163\t19.3483\t19.4217\t19.9183\t19.5575\t18.3556\t18.2691\t19.2592\t18.9258\t18.3855\t19.3603\t16.9504\t18.9816\t17.5824\t17.7137\t18.4439\t18.5777\t18.4191\t17.2249\t14.3625\n", "\"2824551_st\"\t19.9315\t19.9169\t19.9315\t19.9258\t19.9104\t19.9315\t19.8291\t19.9119\t19.927\t19.8974\t19.9104\t19.7772\t19.8335\t19.8927\t19.3308\t19.1087\t19.8974\t19.7337\t19.8991\t19.8665\t19.9315\t19.9315\t19.9315\t19.9183\t19.9298\t19.9053\t19.928\t19.9152\t19.928\t19.9267\t19.9203\t19.5245\t19.9192\t19.9183\t19.7823\t19.9192\t19.9249\t19.901\t19.701\t18.2088\n", "\"2824554_st\"\t19.9315\t19.9169\t19.9315\t19.9258\t19.9104\t19.9185\t19.8291\t19.7764\t19.927\t19.8974\t19.9104\t19.7772\t19.8335\t19.8927\t19.6132\t19.6866\t19.8974\t19.9192\t19.8991\t19.8665\t19.9315\t19.9315\t19.9315\t19.9183\t19.9298\t19.9306\t19.928\t19.9152\t19.928\t19.8991\t19.7325\t19.8474\t19.9192\t19.8463\t19.9083\t19.9192\t19.9249\t19.901\t19.8296\t19.5069\n", "Total lines examined: 67\n", "\n", "Attempting to extract gene data from matrix file...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully extracted gene data with 70523 rows\n", "First 20 gene IDs:\n", "Index(['2824546_st', '2824549_st', '2824551_st', '2824554_st', '2827992_st',\n", " '2827995_st', '2827996_st', '2828010_st', '2828012_st', '2835442_st',\n", " '2835447_st', '2835453_st', '2835456_st', '2835459_st', '2835461_st',\n", " '2839509_st', '2839511_st', '2839513_st', '2839515_st', '2839517_st'],\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": "2ebe1e8a", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "8b837acf", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:17:19.911887Z", "iopub.status.busy": "2025-03-25T07:17:19.911774Z", "iopub.status.idle": "2025-03-25T07:17:19.913684Z", "shell.execute_reply": "2025-03-25T07:17:19.913408Z" } }, "outputs": [], "source": [ "# Examining the gene identifiers in the gene expression data\n", "\n", "# The gene identifiers in this dataset appear to be probe IDs (e.g., \"2824546_st\")\n", "# rather than standard human gene symbols like BRCA1, TP53, etc.\n", "\n", "# The suffix \"_st\" suggests these are likely Affymetrix probe IDs\n", "# These identifiers need to be mapped to standard gene symbols for proper analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "20aea9f2", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "0eab8c9b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:17:19.914775Z", "iopub.status.busy": "2025-03-25T07:17:19.914671Z", "iopub.status.idle": "2025-03-25T07:17:26.005289Z", "shell.execute_reply": "2025-03-25T07:17:26.004881Z" } }, "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 2891713 rows\n", "\n", "Gene annotation preview (first few rows):\n", "{'ID': ['TC01000001.hg.1', 'TC01000002.hg.1', 'TC01000003.hg.1', 'TC01000004.hg.1', 'TC01000005.hg.1'], 'probeset_id': ['TC01000001.hg.1', 'TC01000002.hg.1', 'TC01000003.hg.1', 'TC01000004.hg.1', 'TC01000005.hg.1'], 'seqname': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], 'strand': ['+', '+', '+', '+', '+'], 'start': ['11869', '29554', '69091', '160446', '317811'], 'stop': ['14409', '31109', '70008', '161525', '328581'], 'total_probes': [49.0, 60.0, 30.0, 30.0, 191.0], 'gene_assignment': ['NR_046018 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102 /// ENST00000456328 // DDX11L5 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 5 // 9p24.3 // 100287596 /// ENST00000456328 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102', 'ENST00000408384 // MIR1302-11 // microRNA 1302-11 // --- // 100422919 /// ENST00000408384 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000408384 // MIR1302-9 // microRNA 1302-9 // --- // 100422831 /// ENST00000408384 // MIR1302-2 // microRNA 1302-2 // --- // 100302278 /// ENST00000469289 // MIR1302-11 // microRNA 1302-11 // --- // 100422919 /// ENST00000469289 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000469289 // MIR1302-9 // microRNA 1302-9 // --- // 100422831 /// ENST00000469289 // MIR1302-2 // microRNA 1302-2 // --- // 100302278 /// ENST00000473358 // MIR1302-11 // microRNA 1302-11 // --- // 100422919 /// ENST00000473358 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000473358 // MIR1302-9 // microRNA 1302-9 // --- // 100422831 /// ENST00000473358 // MIR1302-2 // microRNA 1302-2 // --- // 100302278 /// OTTHUMT00000002841 // OTTHUMG00000000959 // NULL // --- // --- /// OTTHUMT00000002841 // RP11-34P13.3 // NULL // --- // --- /// OTTHUMT00000002840 // OTTHUMG00000000959 // NULL // --- // --- /// OTTHUMT00000002840 // RP11-34P13.3 // NULL // --- // ---', 'NM_001005484 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// ENST00000335137 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// OTTHUMT00000003223 // OR4F5 // NULL // --- // ---', 'OTTHUMT00000007169 // OTTHUMG00000002525 // NULL // --- // --- /// OTTHUMT00000007169 // RP11-34P13.9 // NULL // --- // ---', 'NR_028322 // LOC100132287 // uncharacterized LOC100132287 // 1p36.33 // 100132287 /// NR_028327 // LOC100133331 // uncharacterized LOC100133331 // 1p36.33 // 100133331 /// ENST00000425496 // LOC101060495 // uncharacterized LOC101060495 // --- // 101060495 /// ENST00000425496 // LOC101060494 // uncharacterized LOC101060494 // --- // 101060494 /// ENST00000425496 // LOC101059936 // uncharacterized LOC101059936 // --- // 101059936 /// ENST00000425496 // LOC100996502 // uncharacterized LOC100996502 // --- // 100996502 /// ENST00000425496 // LOC100996328 // uncharacterized LOC100996328 // --- // 100996328 /// ENST00000425496 // LOC100287894 // uncharacterized LOC100287894 // 7q11.21 // 100287894 /// NR_028325 // LOC100132062 // uncharacterized LOC100132062 // 5q35.3 // 100132062 /// OTTHUMT00000346878 // OTTHUMG00000156968 // NULL // --- // --- /// OTTHUMT00000346878 // RP4-669L17.10 // NULL // --- // --- /// OTTHUMT00000346879 // OTTHUMG00000156968 // NULL // --- // --- /// OTTHUMT00000346879 // RP4-669L17.10 // NULL // --- // --- /// OTTHUMT00000346880 // OTTHUMG00000156968 // NULL // --- // --- /// OTTHUMT00000346880 // RP4-669L17.10 // NULL // --- // --- /// OTTHUMT00000346881 // OTTHUMG00000156968 // NULL // --- // --- /// OTTHUMT00000346881 // RP4-669L17.10 // NULL // --- // ---'], 'mrna_assignment': ['NR_046018 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 (DDX11L1), non-coding RNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000456328 // ENSEMBL // cdna:known chromosome:GRCh37:1:11869:14409:1 gene:ENSG00000223972 gene_biotype:pseudogene transcript_biotype:processed_transcript // chr1 // 100 // 100 // 0 // --- // 0 /// uc001aaa.3 // UCSC Genes // --- // chr1 // 100 // 100 // 0 // --- // 0 /// uc010nxq.1 // UCSC Genes // --- // chr1 // 100 // 100 // 0 // --- // 0 /// uc010nxr.1 // UCSC Genes // --- // chr1 // 100 // 100 // 0 // --- // 0', 'ENST00000408384 // ENSEMBL // ncrna:miRNA chromosome:GRCh37:1:30366:30503:1 gene:ENSG00000221311 gene_biotype:miRNA transcript_biotype:miRNA // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000469289 // ENSEMBL // havana:lincRNA chromosome:GRCh37:1:30267:31109:1 gene:ENSG00000243485 gene_biotype:lincRNA transcript_biotype:lincRNA // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000473358 // ENSEMBL // havana:lincRNA chromosome:GRCh37:1:29554:31097:1 gene:ENSG00000243485 gene_biotype:lincRNA transcript_biotype:lincRNA // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000002841 // Havana transcript // cdna:all chromosome:VEGA52:1:30267:31109:1 Gene:OTTHUMG00000000959 // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000002840 // Havana transcript // cdna:all chromosome:VEGA52:1:29554:31097:1 Gene:OTTHUMG00000000959 // chr1 // 100 // 100 // 0 // --- // 0', 'NM_001005484 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 5 (OR4F5), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000335137 // ENSEMBL // cdna:known chromosome:GRCh37:1:69091:70008:1 gene:ENSG00000186092 gene_biotype:protein_coding transcript_biotype:protein_coding // chr1 // 100 // 100 // 0 // --- // 0 /// uc001aal.1 // UCSC Genes // --- // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000003223 // Havana transcript // cdna:all chromosome:VEGA52:1:69091:70008:1 Gene:OTTHUMG00000001094 // chr1 // 100 // 100 // 0 // --- // 0', 'ENST00000496488 // ENSEMBL // havana:lincRNA chromosome:GRCh37:1:160446:161525:1 gene:ENSG00000241599 gene_biotype:lincRNA transcript_biotype:lincRNA // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000007169 // Havana transcript // cdna:all chromosome:VEGA52:1:160446:161525:1 Gene:OTTHUMG00000002525 // chr1 // 100 // 100 // 0 // --- // 0', 'NR_028322 // RefSeq // Homo sapiens uncharacterized LOC100132287 (LOC100132287), non-coding RNA. // chr1 // 100 // 100 // 0 // --- // 0 /// NR_028327 // RefSeq // Homo sapiens uncharacterized LOC100133331 (LOC100133331), non-coding RNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000425496 // ENSEMBL // ensembl:lincRNA chromosome:GRCh37:1:324756:328453:1 gene:ENSG00000237094 gene_biotype:lincRNA transcript_biotype:lincRNA // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000426316 // ENSEMBL // [retired] cdna:known chromosome:GRCh37:1:317811:328455:1 gene:ENSG00000240876 gene_biotype:processed_transcript transcript_biotype:processed_transcript // chr1 // 100 // 100 // 0 // --- // 0 /// NR_028325 // RefSeq // Homo sapiens uncharacterized LOC100132062 (LOC100132062), non-coding RNA. // chr1 // 100 // 100 // 0 // --- // 0 /// uc009vjk.2 // UCSC Genes // --- // chr1 // 100 // 100 // 0 // --- // 0 /// uc021oeh.1 // UCSC Genes // --- // chr1 // 100 // 100 // 0 // --- // 0 /// uc021oei.1 // UCSC Genes // --- // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000346906 // Havana transcript // [retired] cdna:all chromosome:VEGA50:1:317811:328455:1 Gene:OTTHUMG00000156972 // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000346878 // Havana transcript // cdna:all chromosome:VEGA52:1:320162:321056:1 Gene:OTTHUMG00000156968 // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000346879 // Havana transcript // cdna:all chromosome:VEGA52:1:320162:324461:1 Gene:OTTHUMG00000156968 // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000346880 // Havana transcript // cdna:all chromosome:VEGA52:1:317720:324873:1 Gene:OTTHUMG00000156968 // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000346881 // Havana transcript // cdna:all chromosome:VEGA52:1:322672:324955:1 Gene:OTTHUMG00000156968 // chr1 // 100 // 100 // 0 // --- // 0'], 'swissprot': ['NR_046018 // B7ZGX0 /// NR_046018 // B7ZGX2 /// NR_046018 // B7ZGX7 /// NR_046018 // B7ZGX8 /// ENST00000456328 // B7ZGX0 /// ENST00000456328 // B7ZGX2 /// ENST00000456328 // B7ZGX3 /// ENST00000456328 // B7ZGX7 /// ENST00000456328 // B7ZGX8 /// ENST00000456328 // Q6ZU42', '---', 'NM_001005484 // Q8NH21 /// ENST00000335137 // Q8NH21', '---', 'NR_028325 // B4DYM5 /// NR_028325 // B4E0H4 /// NR_028325 // B4E3X0 /// NR_028325 // B4E3X2 /// NR_028325 // Q6ZQS4'], 'unigene': ['NR_046018 // Hs.714157 // testis| normal| adult /// ENST00000456328 // Hs.719844 // brain| testis| normal /// ENST00000456328 // Hs.714157 // testis| normal| adult /// ENST00000456328 // Hs.618434 // testis| normal', 'ENST00000469289 // Hs.622486 // eye| normal| adult /// ENST00000469289 // Hs.729632 // testis| normal /// ENST00000469289 // Hs.742718 // testis /// ENST00000473358 // Hs.622486 // eye| normal| adult /// ENST00000473358 // Hs.729632 // testis| normal /// ENST00000473358 // Hs.742718 // testis', 'NM_001005484 // Hs.554500 // --- /// ENST00000335137 // Hs.554500 // ---', '---', 'NR_028322 // Hs.446409 // adrenal gland| blood| bone| brain| connective tissue| embryonic tissue| eye| intestine| kidney| larynx| lung| lymph node| mouth| pharynx| placenta| prostate| skin| testis| thymus| thyroid| uterus| bladder carcinoma| chondrosarcoma| colorectal tumor| germ cell tumor| head and neck tumor| kidney tumor| leukemia| lung tumor| normal| primitive neuroectodermal tumor of the CNS| uterine tumor|embryoid body| blastocyst| fetus| neonate| adult /// NR_028327 // Hs.733048 // ascites| bladder| blood| brain| embryonic tissue| eye| intestine| kidney| larynx| liver| lung| mammary gland| mouth| pancreas| placenta| prostate| skin| stomach| testis| thymus| thyroid| trachea| uterus| bladder carcinoma| breast (mammary gland) tumor| colorectal tumor| gastrointestinal tumor| head and neck tumor| kidney tumor| leukemia| liver tumor| lung tumor| normal| pancreatic tumor| prostate cancer| retinoblastoma| skin tumor| soft tissue/muscle tissue tumor| uterine tumor|embryoid body| blastocyst| fetus| adult /// ENST00000425496 // Hs.744556 // mammary gland| normal| adult /// ENST00000425496 // Hs.660700 // eye| placenta| testis| normal| adult /// ENST00000425496 // Hs.518952 // blood| brain| intestine| lung| mammary gland| mouth| muscle| pharynx| placenta| prostate| spleen| testis| thymus| thyroid| trachea| breast (mammary gland) tumor| colorectal tumor| head and neck tumor| leukemia| lung tumor| normal| prostate cancer| fetus| adult /// ENST00000425496 // Hs.742131 // testis| normal| adult /// ENST00000425496 // Hs.636102 // uterus| uterine tumor /// ENST00000425496 // Hs.646112 // brain| intestine| larynx| lung| mouth| prostate| testis| thyroid| colorectal tumor| head and neck tumor| lung tumor| normal| prostate cancer| adult /// ENST00000425496 // Hs.647795 // brain| lung| lung tumor| adult /// ENST00000425496 // Hs.684307 // --- /// ENST00000425496 // Hs.720881 // testis| normal /// ENST00000425496 // Hs.729353 // brain| lung| placenta| testis| trachea| lung tumor| normal| fetus| adult /// ENST00000425496 // Hs.735014 // ovary| ovarian tumor /// NR_028325 // Hs.732199 // ascites| blood| brain| connective tissue| embryonic tissue| eye| intestine| kidney| lung| ovary| placenta| prostate| stomach| testis| thymus| uterus| chondrosarcoma| colorectal tumor| gastrointestinal tumor| kidney tumor| leukemia| lung tumor| normal| ovarian tumor| fetus| adult'], 'category': ['main', 'main', 'main', 'main', 'main'], 'locus type': ['Coding', 'Coding', 'Coding', 'Coding', 'Coding'], 'notes': ['---', '---', '---', '---', '2 retired transcript(s) from ENSEMBL, Havana transcript'], 'SPOT_ID': ['chr1(+):11869-14409', 'chr1(+):29554-31109', 'chr1(+):69091-70008', 'chr1(+):160446-161525', 'chr1(+):317811-328581']}\n", "\n", "Column names in gene annotation data:\n", "['ID', 'probeset_id', 'seqname', 'strand', 'start', 'stop', 'total_probes', 'gene_assignment', 'mrna_assignment', 'swissprot', 'unigene', 'category', 'locus type', 'notes', 'SPOT_ID']\n", "\n", "The dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\n", "Example SPOT_ID format: chr1(+):11869-14409\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": "b4d35a56", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "a0f34785", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:17:26.006664Z", "iopub.status.busy": "2025-03-25T07:17:26.006537Z", "iopub.status.idle": "2025-03-25T07:17:28.603955Z", "shell.execute_reply": "2025-03-25T07:17:28.603559Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Creating gene mapping from annotation data...\n", "Created gene mapping with 70753 rows\n", "\n", "Mapping dataframe preview:\n", "{'ID': ['TC01000001.hg.1', 'TC01000002.hg.1', 'TC01000003.hg.1'], 'Gene': ['NR_046018 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102 /// ENST00000456328 // DDX11L5 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 5 // 9p24.3 // 100287596 /// ENST00000456328 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102', 'ENST00000408384 // MIR1302-11 // microRNA 1302-11 // --- // 100422919 /// ENST00000408384 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000408384 // MIR1302-9 // microRNA 1302-9 // --- // 100422831 /// ENST00000408384 // MIR1302-2 // microRNA 1302-2 // --- // 100302278 /// ENST00000469289 // MIR1302-11 // microRNA 1302-11 // --- // 100422919 /// ENST00000469289 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000469289 // MIR1302-9 // microRNA 1302-9 // --- // 100422831 /// ENST00000469289 // MIR1302-2 // microRNA 1302-2 // --- // 100302278 /// ENST00000473358 // MIR1302-11 // microRNA 1302-11 // --- // 100422919 /// ENST00000473358 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000473358 // MIR1302-9 // microRNA 1302-9 // --- // 100422831 /// ENST00000473358 // MIR1302-2 // microRNA 1302-2 // --- // 100302278 /// OTTHUMT00000002841 // OTTHUMG00000000959 // NULL // --- // --- /// OTTHUMT00000002841 // RP11-34P13.3 // NULL // --- // --- /// OTTHUMT00000002840 // OTTHUMG00000000959 // NULL // --- // --- /// OTTHUMT00000002840 // RP11-34P13.3 // NULL // --- // ---', 'NM_001005484 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// ENST00000335137 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// OTTHUMT00000003223 // OR4F5 // NULL // --- // ---']}\n", "\n", "Applying gene mapping to convert probe data to gene expression data...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Converted to gene expression data with 71528 genes\n", "First few gene symbols:\n", "['A-', 'A-2', 'A-52', 'A-575C2', 'A-E', 'A-I', 'A-II', 'A-IV', 'A-V', 'A0']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Kidney_Clear_Cell_Carcinoma/gene_data/GSE117230.csv\n" ] } ], "source": [ "# 1. Identify relevant columns for gene mapping\n", "print(\"Creating gene mapping from annotation data...\")\n", "\n", "# Looking at the column names and data in gene_annotation, \n", "# 'ID' appears to match the probe ids in gene_expression data\n", "# 'gene_assignment' contains gene symbol information\n", "\n", "# 2. Create a gene mapping dataframe\n", "mapping_df = get_gene_mapping(gene_annotation, 'ID', 'gene_assignment')\n", "print(f\"Created gene mapping with {len(mapping_df)} rows\")\n", "\n", "# Preview the mapping\n", "print(\"\\nMapping dataframe preview:\")\n", "print(preview_df(mapping_df, n=3))\n", "\n", "# 3. Apply gene mapping to convert probe-level data to gene expression data\n", "print(\"\\nApplying gene mapping to convert probe data to gene expression data...\")\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Verify the conversion was successful\n", "print(f\"Converted to gene expression data with {len(gene_data)} genes\")\n", "print(\"First few gene symbols:\")\n", "print(list(gene_data.index[:10]))\n", "\n", "# Save the processed gene data\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"Gene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "a3478b13", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "08393a24", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:17:28.605407Z", "iopub.status.busy": "2025-03-25T07:17:28.605279Z", "iopub.status.idle": "2025-03-25T07:17:29.351418Z", "shell.execute_reply": "2025-03-25T07:17:29.350948Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Normalizing gene symbols...\n", "After normalization: 24018 unique gene symbols\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Kidney_Clear_Cell_Carcinoma/gene_data/GSE117230.csv\n", "\n", "Linking clinical and genetic data...\n", "Loaded clinical data with shape: (1, 40)\n", "Correctly formatted clinical data shape: (40, 2)\n", "Clinical data columns: ['Kidney_Clear_Cell_Carcinoma', 0]\n", "Linked data shape: (42, 24058)\n", "Trait column 'Kidney_Clear_Cell_Carcinoma' not found in linked data.\n", "\n", "Performing final validation...\n", "Dataset not usable for Kidney_Clear_Cell_Carcinoma association studies. Data not saved.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "print(\"\\nNormalizing gene symbols...\")\n", "try:\n", " # Check if gene_data is empty before normalization\n", " if gene_data.empty:\n", " print(\"Gene data is empty. Skipping normalization.\")\n", " normalized_gene_data = gene_data\n", " else:\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"After normalization: {len(normalized_gene_data.index)} unique gene symbols\")\n", " \n", " # Save the normalized gene data (even if empty, to maintain consistent workflow)\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 expression data saved to {out_gene_data_file}\")\n", "except Exception as e:\n", " print(f\"Error normalizing gene symbols: {e}\")\n", " normalized_gene_data = gene_data # Use original data if normalization fails\n", "\n", "# 2. Link clinical and genetic data\n", "print(\"\\nLinking clinical and genetic data...\")\n", "try:\n", " # Load the clinical data from the previously saved file\n", " clinical_df = pd.read_csv(out_clinical_data_file)\n", " print(f\"Loaded clinical data with shape: {clinical_df.shape}\")\n", " \n", " # Create proper trait column \n", " clinical_df_t = clinical_df.T\n", " clinical_df_t.reset_index(inplace=True)\n", " clinical_df_t.columns = [trait] + [col for col in clinical_df_t.columns[1:]]\n", " clinical_df = clinical_df_t\n", " \n", " print(f\"Correctly formatted clinical data shape: {clinical_df.shape}\")\n", " print(f\"Clinical data columns: {clinical_df.columns.tolist()}\")\n", " is_trait_available = trait in clinical_df.columns\n", " \n", " if is_trait_available and not normalized_gene_data.empty:\n", " # Link the data\n", " linked_data = geo_link_clinical_genetic_data(clinical_df, normalized_gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " \n", " # Check if we have at least one sample with trait value\n", " if trait in linked_data.columns:\n", " trait_count = linked_data[trait].count()\n", " print(f\"Number of samples with trait values: {trait_count}\")\n", " \n", " if trait_count > 0:\n", " # 3. Handle missing values systematically\n", " print(\"\\nHandling missing values...\")\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"After handling missing values, data shape: {linked_data.shape}\")\n", " \n", " # Check if we still have samples after missing value handling\n", " if linked_data.shape[0] > 0:\n", " # 4. Determine whether the trait and demographic features are biased\n", " print(\"\\nChecking for bias in features...\")\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " else:\n", " print(\"Error: All samples were removed during missing value handling.\")\n", " is_biased = True\n", " else:\n", " print(\"No samples have valid trait values. Dataset cannot be used.\")\n", " is_biased = True\n", " else:\n", " print(f\"Trait column '{trait}' not found in linked data.\")\n", " is_biased = True\n", " else:\n", " print(\"Cannot link data: clinical or genetic data is missing.\")\n", " if not is_trait_available:\n", " print(f\"Reason: Trait column '{trait}' is not available in clinical data.\")\n", " if normalized_gene_data.empty:\n", " print(\"Reason: Gene expression data is empty.\")\n", " linked_data = pd.DataFrame()\n", " is_biased = True\n", " \n", "except Exception as e:\n", " print(f\"Error in linking clinical and genetic data: {e}\")\n", " linked_data = pd.DataFrame()\n", " is_biased = True\n", "\n", "# 5. Final quality validation\n", "print(\"\\nPerforming final validation...\")\n", "note = \"\"\n", "if 'linked_data' in locals() and linked_data.empty:\n", " if not normalized_gene_data.empty and not clinical_df.empty:\n", " note = \"Dataset failed in linking phase. Clinical data structure could not be properly matched with gene expression data.\"\n", " elif normalized_gene_data.empty:\n", " note = \"Dataset failed in gene mapping phase. Could not properly map probe IDs to gene symbols.\"\n", " elif clinical_df.empty:\n", " note = \"Dataset failed in clinical data extraction. No valid trait information available.\"\n", "elif 'is_biased' in locals() and is_biased:\n", " note = \"Dataset passed initial processing but contains severely biased trait distribution.\"\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=not normalized_gene_data.empty, # Set based on actual gene data availability\n", " is_trait_available=is_trait_available,\n", " is_biased=is_biased if 'is_biased' in locals() else True,\n", " df=linked_data if 'linked_data' in locals() and not linked_data.empty else pd.DataFrame(),\n", " note=note\n", ")\n", "\n", "# 6. Save linked data if usable\n", "if is_usable and 'linked_data' in locals() and not linked_data.empty:\n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " \n", " # Save linked data\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(f\"Dataset 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 }