{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "0ecc8271", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:21:33.408452Z", "iopub.status.busy": "2025-03-25T07:21:33.408224Z", "iopub.status.idle": "2025-03-25T07:21:33.572703Z", "shell.execute_reply": "2025-03-25T07:21:33.572259Z" } }, "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_Papillary_Cell_Carcinoma\"\n", "cohort = \"GSE68606\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Kidney_Papillary_Cell_Carcinoma\"\n", "in_cohort_dir = \"../../input/GEO/Kidney_Papillary_Cell_Carcinoma/GSE68606\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/GSE68606.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/gene_data/GSE68606.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/clinical_data/GSE68606.csv\"\n", "json_path = \"../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "42ab10d0", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "cc06bfb6", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:21:33.574037Z", "iopub.status.busy": "2025-03-25T07:21:33.573888Z", "iopub.status.idle": "2025-03-25T07:21:33.703265Z", "shell.execute_reply": "2025-03-25T07:21:33.702851Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"caArray_dobbi-00100: Interlaboratory comparability study of cancer gene expression analysis using oligonucleotide microarrays\"\n", "!Series_summary\t\"A key step in bringing gene expression data into clinical practice is the conduct of large studies to confirm preliminary models. The performance of such confirmatory studies and the transition to clinical practice requires that microarray data from different laboratories are comparable and reproducible. We designed a study to assess the comparability of data from four laboratories that will conduct a larger microarray profiling confirmation project in lung adenocarcinomas. To test the feasibility of combining data across laboratories, frozen tumor tissues, cell line pellets, and purified RNA samples were analyzed at each of the four laboratories. Samples of each type and several subsamples from each tumor and each cell line were blinded before being distributed. The laboratories followed a common protocol for all steps of tissue processing, RNA extraction, and microarray analysis using Affymetrix Human Genome U133A arrays. High within-laboratory and between-laboratory correlations were observed on the purified RNA samples, the cell lines, and the frozen tumor tissues. Intraclass correlation within laboratories was only slightly stronger than between laboratories, and the intraclass correlation tended to be weakest for genes expressed at low levels and showing small variation. Finally, hierarchical cluster analysis revealed that the repeated samples clustered together regardless of the laboratory in which the experiments were done. The findings indicate that under properly controlled conditions it is feasible to perform complete tumor microarray analysis, from tissue processing to hybridization and scanning, at multiple independent laboratories for a single study.\"\n", "!Series_overall_design\t\"dobbi-00100\"\n", "!Series_overall_design\t\"Assay Type: Gene Expression\"\n", "!Series_overall_design\t\"Provider: Affymetrix\"\n", "!Series_overall_design\t\"Array Designs: HG-U133A\"\n", "!Series_overall_design\t\"Organism: Homo sapiens (ncbitax)\"\n", "!Series_overall_design\t\"Tissue Sites: Kidney, Lung, Stomach, Uterus, Liver, Lymphoid tissue, Ovary, Skin, Adrenal Gland, Lymph_Node\"\n", "!Series_overall_design\t\"Material Types: cell, nuclear_RNA, synthetic_RNA, organism_part, total_RNA\"\n", "!Series_overall_design\t\"Disease States: Recurrent Renal Cell Carcinoma, Squamous Cell Carcinoma,Conventional_Clear_Cell_Renal_Cell_Carcinoma,Gastrointestinal_Stromal_Tumor, Lung_Adenocarcinoma, Leiomyoma, Non neoplastic liver with cirrosis, Stomach Adenocarcinoma, Large Cell Lymphoma, Ovarian Adenocarcinoma, Melanoma, Malignant G1 Stromal Tumor, Adrenal Cortical Adenoma, Metastatic Renal Cell Carcinoma, Malignant Melanoma\"\n", "Sample Characteristics Dictionary:\n", "{0: ['cell line: H2347', 'cell line: H1437', 'cell line: HCC78', 'cell line: H2087', 'cell line: H2009', 'cell line: --'], 1: ['disease state: --', 'disease state: Leiomyoma', 'disease state: Lung_Adenocarcinoma', 'disease state: Conventional_Clear_Cell_Renal_Cell_Carcinoma', 'disease state: Squamous Cell Carcinoma', 'disease state: Stomach Adenocarcinoma', 'disease state: Large Cell Lymphoma', 'disease state: Malignant Melanoma', 'disease state: Recurrent Renal Cell Carcinoma', 'disease state: Adrenal Cortical Adenoma', 'disease state: Ovarian Adenocarcinoma', 'disease state: Gastrointestinal_Stromal_Tumor', 'disease state: Metastatic Renal Cell Carcinoma', 'disease state: Non neoplastic liver with cirrosis', 'disease state: Malignant G1 Stromal Tumor', 'disease state: melanoma'], 2: ['tumor grading: --', 'tumor grading: G2/pT1pN0pMX', 'tumor grading: G3/pT2pN0pMX', 'tumor grading: G2/pT2pN0pMX', 'tumor grading: G3/pT4pNXpMX'], 3: ['disease stage: --', 'disease stage: Stage IA', 'disease stage: Stage IB', 'disease stage: Stage IIIB'], 4: ['organism part: --', 'organism part: Uterus', 'organism part: Lung', 'organism part: Stomach', 'organism part: Lymphoid tissue', 'organism part: Liver', 'organism part: Adrenal Gland', 'organism part: Ovary', 'organism part: Kidney', 'organism part: Skin', 'organism part: Lymph_Node'], 5: ['Sex: --', 'Sex: female', 'Sex: male'], 6: ['age: --', 'age: 67', 'age: 66', 'age: 72', 'age: 56', 'age: 48'], 7: ['histology: --', 'histology: Leiomyoma', 'histology: Lung_Adenocarcinoma', 'histology: Conventional_Clear_Cell_Renal_Cell_Carcinoma', 'histology: Stomach Adenocarcinoma', 'histology: Large Cell Lymphoma', 'histology: Metastatic Malignant Melanoma', 'histology: Recurrent Renal Cell Carcinoma, chromophobe cell type', 'histology: Non neoplastic liver with cirrosis', 'histology: Adrenal Cortical Adenoma', 'histology: Papillary Serous Adenocarcinoma', 'histology: Squamous cell carcinoma 85% tumor 15% Stroma', 'histology: Squamous Cell Carcinoma', 'histology: Malignant G1 Stromal Tumor', 'histology: metastatic renal cell carcinoma', 'histology: Lung Adenocarcinoma', 'histology: carcinoma', 'histology: Adenocarcinoma', 'histology: Squamous Cell carcinoma', 'histology: Metastatic Renal Cell Carcinoma, clear cell type', 'histology: Ovarian Adenocarcinoma', 'histology: Malignant G1 stromal tumor', 'histology: Adenocartcinoma of Lung', 'histology: Squamoous Cell Carcinoma', 'histology: Renal Cell Carcinoma', 'histology: Non neeoplastic liver with cirrosis', 'histology: Metastatic Renal Cell Carcinoma']}\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": "98db4620", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "01ac6cf4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:21:33.704697Z", "iopub.status.busy": "2025-03-25T07:21:33.704584Z", "iopub.status.idle": "2025-03-25T07:21:33.727470Z", "shell.execute_reply": "2025-03-25T07:21:33.727154Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of extracted clinical features:\n", "{'GSM1676864': [nan, nan, nan], 'GSM1676865': [nan, nan, nan], 'GSM1676866': [nan, nan, 0.0], 'GSM1676867': [nan, nan, nan], 'GSM1676868': [nan, nan, nan], 'GSM1676869': [nan, nan, nan], 'GSM1676870': [nan, nan, nan], 'GSM1676871': [nan, nan, nan], 'GSM1676872': [nan, nan, nan], 'GSM1676873': [nan, nan, nan], 'GSM1676874': [nan, 67.0, 1.0], 'GSM1676875': [nan, 66.0, 1.0], 'GSM1676876': [nan, 72.0, 1.0], 'GSM1676877': [nan, 56.0, 0.0], 'GSM1676878': [nan, 48.0, 0.0], 'GSM1676879': [nan, nan, nan], 'GSM1676880': [nan, nan, nan], 'GSM1676881': [nan, nan, nan], 'GSM1676882': [nan, nan, nan], 'GSM1676883': [nan, nan, nan], 'GSM1676884': [nan, nan, nan], 'GSM1676885': [nan, nan, nan], 'GSM1676886': [nan, nan, nan], 'GSM1676887': [0.0, nan, nan], 'GSM1676888': [nan, nan, nan], 'GSM1676889': [nan, nan, nan], 'GSM1676890': [1.0, nan, nan], 'GSM1676891': [nan, nan, nan], 'GSM1676892': [nan, nan, nan], 'GSM1676893': [nan, nan, nan], 'GSM1676894': [nan, nan, nan], 'GSM1676895': [nan, nan, nan], 'GSM1676896': [nan, nan, nan], 'GSM1676897': [nan, nan, nan], 'GSM1676898': [nan, nan, nan], 'GSM1676899': [nan, nan, nan], 'GSM1676900': [nan, nan, nan], 'GSM1676901': [0.0, nan, nan], 'GSM1676902': [nan, 48.0, 0.0], 'GSM1676903': [nan, nan, nan], 'GSM1676904': [nan, nan, nan], 'GSM1676905': [nan, 66.0, 1.0], 'GSM1676906': [nan, 56.0, 0.0], 'GSM1676907': [nan, 72.0, 1.0], 'GSM1676908': [nan, nan, nan], 'GSM1676909': [nan, 67.0, 1.0], 'GSM1676910': [0.0, nan, nan], 'GSM1676911': [nan, nan, nan], 'GSM1676912': [nan, nan, nan], 'GSM1676913': [nan, nan, nan], 'GSM1676914': [nan, nan, nan], 'GSM1676915': [0.0, nan, nan], 'GSM1676916': [nan, nan, nan], 'GSM1676917': [nan, nan, nan], 'GSM1676918': [nan, nan, nan], 'GSM1676919': [nan, nan, nan], 'GSM1676920': [nan, nan, nan], 'GSM1676921': [nan, nan, nan], 'GSM1676922': [nan, nan, nan], 'GSM1676923': [nan, nan, nan], 'GSM1676924': [nan, nan, nan], 'GSM1676925': [nan, nan, nan], 'GSM1676926': [nan, nan, nan], 'GSM1676927': [nan, nan, nan], 'GSM1676928': [nan, nan, nan], 'GSM1676929': [nan, nan, nan], 'GSM1676930': [nan, nan, nan], 'GSM1676931': [nan, nan, nan], 'GSM1676932': [nan, nan, nan], 'GSM1676933': [nan, nan, nan], 'GSM1676934': [nan, nan, nan], 'GSM1676935': [nan, nan, nan], 'GSM1676936': [nan, nan, nan], 'GSM1676937': [nan, nan, nan], 'GSM1676938': [nan, nan, nan], 'GSM1676939': [nan, nan, nan], 'GSM1676940': [nan, nan, nan], 'GSM1676941': [nan, nan, nan], 'GSM1676942': [nan, nan, nan], 'GSM1676943': [0.0, nan, nan], 'GSM1676944': [nan, nan, nan], 'GSM1676945': [nan, nan, nan], 'GSM1676946': [1.0, nan, nan], 'GSM1676947': [0.0, nan, nan], 'GSM1676948': [nan, nan, nan], 'GSM1676949': [nan, 67.0, 1.0], 'GSM1676950': [nan, 56.0, 0.0], 'GSM1676951': [nan, 48.0, 0.0], 'GSM1676952': [nan, nan, nan], 'GSM1676953': [nan, nan, nan], 'GSM1676954': [nan, nan, nan], 'GSM1676955': [nan, nan, nan], 'GSM1676956': [nan, nan, nan], 'GSM1676957': [nan, nan, nan], 'GSM1676958': [nan, nan, nan], 'GSM1676959': [nan, nan, nan], 'GSM1676960': [nan, 66.0, 1.0], 'GSM1676961': [nan, 72.0, 1.0], 'GSM1676962': [nan, nan, nan], 'GSM1676963': [nan, nan, nan], 'GSM1676964': [nan, nan, nan], 'GSM1676965': [nan, nan, nan], 'GSM1676966': [nan, nan, nan], 'GSM1676967': [nan, nan, nan], 'GSM1676968': [nan, nan, nan], 'GSM1676969': [nan, nan, nan], 'GSM1676970': [nan, nan, nan], 'GSM1676971': [nan, 67.0, 1.0], 'GSM1676972': [nan, 56.0, 0.0], 'GSM1676973': [0.0, nan, nan], 'GSM1676974': [nan, 66.0, 1.0], 'GSM1676975': [nan, nan, nan], 'GSM1676976': [nan, nan, nan], 'GSM1676977': [nan, 48.0, 0.0], 'GSM1676978': [0.0, nan, nan], 'GSM1676979': [nan, 72.0, 1.0], 'GSM1676980': [nan, nan, nan], 'GSM1676981': [nan, nan, nan], 'GSM1676982': [nan, nan, nan], 'GSM1676983': [0.0, nan, nan], 'GSM1676984': [nan, nan, nan], 'GSM1676985': [nan, nan, nan], 'GSM1676986': [0.0, nan, nan], 'GSM1676987': [1.0, nan, nan], 'GSM1676988': [nan, nan, nan], 'GSM1676989': [nan, nan, nan], 'GSM1676990': [nan, nan, nan], 'GSM1676991': [nan, nan, nan], 'GSM1676992': [nan, nan, nan], 'GSM1676993': [nan, nan, nan], 'GSM1676994': [nan, nan, nan], 'GSM1676995': [nan, nan, nan], 'GSM1676996': [nan, nan, nan], 'GSM1676997': [nan, nan, nan], 'GSM1676998': [nan, nan, nan], 'GSM1676999': [nan, nan, nan], 'GSM1677000': [nan, nan, nan]}\n", "Clinical features saved to ../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/clinical_data/GSE68606.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import numpy as np\n", "from typing import Optional, Callable, Dict, Any, List\n", "import json\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset appears to contain gene expression data\n", "# It mentions \"cancer gene expression analysis using oligonucleotide microarrays\" and \"Affymetrix Human Genome U133A arrays\"\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait: We're looking for Kidney_Papillary_Cell_Carcinoma\n", "# Looking at histology (key 7), there is \"histology: Papillary Serous Adenocarcinoma\"\n", "# and row 1 has \"disease state: Conventional_Clear_Cell_Renal_Cell_Carcinoma\" and \"disease state: Recurrent Renal Cell Carcinoma\"\n", "# From rows 1 and 7, we can infer information about kidney cancer subtypes\n", "trait_row = 7 # Using histology as it contains more detailed information\n", "\n", "# For age: Available in key 6\n", "age_row = 6\n", "\n", "# For gender: Available in key 5 (labeled as \"Sex\")\n", "gender_row = 5\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value: str) -> Optional[int]:\n", " \"\"\"\n", " Convert trait values to binary (0: not papillary carcinoma, 1: papillary carcinoma)\n", " \"\"\"\n", " if value is None or value == \"--\":\n", " return None\n", " \n", " # Extract the value part after the colon and trim whitespace\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Check for papillary renal cell carcinoma mentions\n", " if \"papillary\" in value.lower() and (\"renal\" in value.lower() or \"kidney\" in value.lower()):\n", " return 1\n", " # Check specifically for \"Papillary Serous Adenocarcinoma\" which might be kidney-related in this context\n", " elif \"papillary serous adenocarcinoma\" in value.lower():\n", " return 1\n", " # Other kidney carcinomas that are non-papillary\n", " elif (\"renal cell carcinoma\" in value.lower() or \"kidney\" in value.lower()) and \"carcinoma\" in value.lower():\n", " return 0\n", " # Not a kidney cancer or unspecified\n", " else:\n", " return None\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"\n", " Convert age values to continuous numeric values\n", " \"\"\"\n", " if value is None or value == \"--\":\n", " return None\n", " \n", " # Extract the value part after the colon and trim whitespace\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except ValueError:\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"\n", " Convert gender values to binary (0: female, 1: male)\n", " \"\"\"\n", " if value is None or value == \"--\":\n", " return None\n", " \n", " # Extract the value part after the colon and trim whitespace\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip().lower()\n", " \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", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Initial filtering and metadata saving\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "# If trait_row is not None, extract and save clinical features\n", "if trait_row is not None:\n", " # Load clinical data (assuming it was loaded in a previous step)\n", " # We need to check if the variables are defined and clinical_data exists\n", " try:\n", " # Use the geo_select_clinical_features function to extract features\n", " clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the extracted features\n", " print(\"Preview of extracted clinical features:\")\n", " preview = preview_df(clinical_features)\n", " print(preview)\n", " \n", " # Create the directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the clinical features to the specified output file\n", " clinical_features.to_csv(out_clinical_data_file)\n", " print(f\"Clinical features saved to {out_clinical_data_file}\")\n", " except NameError:\n", " print(\"Clinical data not available from previous steps.\")\n" ] }, { "cell_type": "markdown", "id": "9d69e5ed", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "cd36175e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:21:33.728678Z", "iopub.status.busy": "2025-03-25T07:21:33.728567Z", "iopub.status.idle": "2025-03-25T07:21:33.995239Z", "shell.execute_reply": "2025-03-25T07:21:33.994885Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining matrix file structure...\n", "Line 0: !Series_title\t\"caArray_dobbi-00100: Interlaboratory comparability study of cancer gene expression analysis using oligonucleotide microarrays\"\n", "Line 1: !Series_geo_accession\t\"GSE68606\"\n", "Line 2: !Series_status\t\"Public on May 07 2015\"\n", "Line 3: !Series_submission_date\t\"May 06 2015\"\n", "Line 4: !Series_last_update_date\t\"Aug 10 2018\"\n", "Line 5: !Series_pubmed_id\t\"15701842\"\n", "Line 6: !Series_summary\t\"A key step in bringing gene expression data into clinical practice is the conduct of large studies to confirm preliminary models. The performance of such confirmatory studies and the transition to clinical practice requires that microarray data from different laboratories are comparable and reproducible. We designed a study to assess the comparability of data from four laboratories that will conduct a larger microarray profiling confirmation project in lung adenocarcinomas. To test the feasibility of combining data across laboratories, frozen tumor tissues, cell line pellets, and purified RNA samples were analyzed at each of the four laboratories. Samples of each type and several subsamples from each tumor and each cell line were blinded before being distributed. The laboratories followed a common protocol for all steps of tissue processing, RNA extraction, and microarray analysis using Affymetrix Human Genome U133A arrays. High within-laboratory and between-laboratory correlations were observed on the purified RNA samples, the cell lines, and the frozen tumor tissues. Intraclass correlation within laboratories was only slightly stronger than between laboratories, and the intraclass correlation tended to be weakest for genes expressed at low levels and showing small variation. Finally, hierarchical cluster analysis revealed that the repeated samples clustered together regardless of the laboratory in which the experiments were done. The findings indicate that under properly controlled conditions it is feasible to perform complete tumor microarray analysis, from tissue processing to hybridization and scanning, at multiple independent laboratories for a single study.\"\n", "Line 7: !Series_overall_design\t\"dobbi-00100\"\n", "Line 8: !Series_overall_design\t\"Assay Type: Gene Expression\"\n", "Line 9: !Series_overall_design\t\"Provider: Affymetrix\"\n", "Found table marker at line 74\n", "First few lines after marker:\n", "\"ID_REF\"\t\"GSM1676864\"\t\"GSM1676865\"\t\"GSM1676866\"\t\"GSM1676867\"\t\"GSM1676868\"\t\"GSM1676869\"\t\"GSM1676870\"\t\"GSM1676871\"\t\"GSM1676872\"\t\"GSM1676873\"\t\"GSM1676874\"\t\"GSM1676875\"\t\"GSM1676876\"\t\"GSM1676877\"\t\"GSM1676878\"\t\"GSM1676879\"\t\"GSM1676880\"\t\"GSM1676881\"\t\"GSM1676882\"\t\"GSM1676883\"\t\"GSM1676884\"\t\"GSM1676885\"\t\"GSM1676886\"\t\"GSM1676887\"\t\"GSM1676888\"\t\"GSM1676889\"\t\"GSM1676890\"\t\"GSM1676891\"\t\"GSM1676892\"\t\"GSM1676893\"\t\"GSM1676894\"\t\"GSM1676895\"\t\"GSM1676896\"\t\"GSM1676897\"\t\"GSM1676898\"\t\"GSM1676899\"\t\"GSM1676900\"\t\"GSM1676901\"\t\"GSM1676902\"\t\"GSM1676903\"\t\"GSM1676904\"\t\"GSM1676905\"\t\"GSM1676906\"\t\"GSM1676907\"\t\"GSM1676908\"\t\"GSM1676909\"\t\"GSM1676910\"\t\"GSM1676911\"\t\"GSM1676912\"\t\"GSM1676913\"\t\"GSM1676914\"\t\"GSM1676915\"\t\"GSM1676916\"\t\"GSM1676917\"\t\"GSM1676918\"\t\"GSM1676919\"\t\"GSM1676920\"\t\"GSM1676921\"\t\"GSM1676922\"\t\"GSM1676923\"\t\"GSM1676924\"\t\"GSM1676925\"\t\"GSM1676926\"\t\"GSM1676927\"\t\"GSM1676928\"\t\"GSM1676929\"\t\"GSM1676930\"\t\"GSM1676931\"\t\"GSM1676932\"\t\"GSM1676933\"\t\"GSM1676934\"\t\"GSM1676935\"\t\"GSM1676936\"\t\"GSM1676937\"\t\"GSM1676938\"\t\"GSM1676939\"\t\"GSM1676940\"\t\"GSM1676941\"\t\"GSM1676942\"\t\"GSM1676943\"\t\"GSM1676944\"\t\"GSM1676945\"\t\"GSM1676946\"\t\"GSM1676947\"\t\"GSM1676948\"\t\"GSM1676949\"\t\"GSM1676950\"\t\"GSM1676951\"\t\"GSM1676952\"\t\"GSM1676953\"\t\"GSM1676954\"\t\"GSM1676955\"\t\"GSM1676956\"\t\"GSM1676957\"\t\"GSM1676958\"\t\"GSM1676959\"\t\"GSM1676960\"\t\"GSM1676961\"\t\"GSM1676962\"\t\"GSM1676963\"\t\"GSM1676964\"\t\"GSM1676965\"\t\"GSM1676966\"\t\"GSM1676967\"\t\"GSM1676968\"\t\"GSM1676969\"\t\"GSM1676970\"\t\"GSM1676971\"\t\"GSM1676972\"\t\"GSM1676973\"\t\"GSM1676974\"\t\"GSM1676975\"\t\"GSM1676976\"\t\"GSM1676977\"\t\"GSM1676978\"\t\"GSM1676979\"\t\"GSM1676980\"\t\"GSM1676981\"\t\"GSM1676982\"\t\"GSM1676983\"\t\"GSM1676984\"\t\"GSM1676985\"\t\"GSM1676986\"\t\"GSM1676987\"\t\"GSM1676988\"\t\"GSM1676989\"\t\"GSM1676990\"\t\"GSM1676991\"\t\"GSM1676992\"\t\"GSM1676993\"\t\"GSM1676994\"\t\"GSM1676995\"\t\"GSM1676996\"\t\"GSM1676997\"\t\"GSM1676998\"\t\"GSM1676999\"\t\"GSM1677000\"\n", "\"1007_s_at\"\t1932.38\t1032.65\t1282.8\t2688.61\t2189.27\t342.639\t254.996\t2225.93\t2785.7\t1785.58\t3570.04\t1501.48\t1960.55\t893.262\t1438.09\t1235.25\t1415.02\t655.438\t634.813\t2625.93\t3312.66\t303.093\t516.196\t4403.29\t501.149\t1520.62\t4324.21\t668.359\t3458.26\t342.029\t2497.4\t516.285\t3150.6\t472.852\t1410.36\t2061.12\t1843.45\t823.137\t1398.94\t559.224\t2586.26\t1322.39\t981.853\t1687.2\t1968.33\t4672.18\t6528.71\t404.146\t1623.85\t871.939\t3636.85\t716.633\t2651.02\t1537.75\t2396.11\t3742.98\t374.45\t244.22\t3158.76\t1484.13\t1950.48\t252.954\t1079.65\t1454.65\t972.47\t297.698\t1970.99\t1260.85\t1336.95\t1319.53\t928.266\t405.945\t1920.58\t1955.98\t1331.59\t1688.65\t1993.19\t3306.33\t495.471\t6237.41\t478.338\t986.711\t5260.99\t948.439\t288.448\t4378.38\t1205.18\t1447.61\t1963.06\t1124.65\t557.455\t1995.01\t3680.53\t502.448\t5865.71\t1155.31\t1374.3\t2273.33\t3066.25\t2087.27\t1929.65\t2002.37\t452.309\t1815.17\t1312.89\t282.796\t1404.48\t4824.06\t980.272\t7163.48\t1121.01\t351.138\t1015.05\t1342.94\t756.574\t1955.88\t6064.48\t486.944\t3143.08\t5697\t340.352\t301.751\t847.164\t5506.8\t3670.24\t402.279\t327.973\t2212.02\t1105.37\t1429.44\t1034.43\t1963.04\t685.843\t1038.43\t267.586\t854.456\t1051.03\n", "\"1053_at\"\t833.805\t1034.23\t647.452\t149.056\t315.934\t155.564\t312.145\t431.223\t325.092\t793.216\t256.64\t254.554\t175.594\t471.914\t213.463\t763.189\t565.432\t152.015\t177.05\t527.884\t222.939\t486.47\t38.1796\t204.175\t190.997\t160.618\t387.788\t181.709\t457.053\t345.457\t382.756\t285.237\t413.459\t243.526\t468.762\t460.566\t756.097\t268.512\t227.819\t35.4592\t230.272\t303.723\t645.031\t210.407\t404.976\t373.001\t217.483\t185.83\t180.533\t173.778\t480.624\t111.936\t221.89\t154.789\t331.704\t501.813\t132.37\t366.177\t313.79\t540.679\t576.346\t200.43\t1083.77\t493.98\t955.113\t213.752\t290.305\t745.693\t778.604\t628.435\t411.852\t256.619\t598.266\t770.632\t763.715\t525.803\t105.617\t227.382\t189.115\t201.775\t238.913\t204.133\t441.396\t208.557\t555.264\t443.933\t551.696\t256.807\t811.803\t1089.98\t299.283\t202.407\t296.87\t173.894\t162.229\t177.71\t232.603\t153.9\t464.009\t553.985\t617.895\t591.126\t266.346\t519.065\t419.007\t233.368\t30.5509\t229.704\t403.009\t97.7233\t220.839\t268.958\t63.8259\t155.153\t61.0755\t159.072\t128.035\t108.195\t297.504\t89.4713\t63.1845\t362.522\t104.285\t334.38\t156.141\t8.04209\t32.345\t199.237\t514.352\t879.663\t1314.85\t625.292\t727.305\t521.029\t205.013\t478.053\t466.558\n", "\"117_at\"\t122.255\t59.3265\t126.75\t139.899\t98.9554\t66.885\t74.1553\t131.672\t77.3771\t120.167\t121.992\t293.974\t410.908\t150.127\t321.515\t118.713\t143.278\t100.644\t285.083\t171.012\t120.965\t196.412\t69.6824\t102.788\t192.763\t335.978\t308.846\t167.135\t213.671\t145.972\t197.263\t236.435\t228.734\t297.231\t111.687\t237.517\t184.189\t409.427\t320.722\t262.921\t117.963\t263.136\t275.998\t462.308\t78.9404\t144.564\t99.8176\t614.083\t386.641\t139.875\t269.435\t251.727\t81.3178\t247.098\t258.224\t288.166\t132.794\t92.5949\t108.555\t151.999\t105.292\t90.622\t42.5212\t104.232\t38.4785\t83.7356\t425.151\t120.484\t97.8888\t110.677\t157.666\t144.181\t159.236\t112.38\t165.459\t26.4815\t414.5\t226.666\t230.129\t121.168\t318.503\t157.605\t208.371\t345.09\t118.903\t251.854\t217.983\t328.915\t163.079\t65.0018\t233.094\t396.735\t230.768\t230.874\t140.871\t200.966\t285.075\t442.118\t287.111\t289.194\t178.937\t77.2701\t416.778\t82.207\t148.126\t89.5404\t314.936\t135.993\t173.639\t101.383\t317.437\t139.406\t195.802\t202.441\t276.39\t466.396\t137.704\t458.562\t227.925\t177.125\t206.286\t140.126\t437.178\t185.261\t110.777\t78.3937\t181.616\t429.304\t101.457\t91.4308\t83.3443\t197.262\t115.299\t128.308\t84.8303\t110.795\t94.8872\n", "\"121_at\"\t1134.54\t1058.97\t1107.48\t1712\t1175.17\t1004.85\t943.422\t1246.45\t1114.25\t1289.73\t858.765\t1103.74\t1058.29\t969.612\t1377.86\t1067.78\t968.648\t1077.6\t2575.22\t1514.54\t1173.87\t1056.3\t963.08\t3252.42\t1458.2\t1220.6\t7688.69\t845.518\t1288.95\t1458.5\t1405.11\t1417.78\t1577.31\t1209.02\t909.103\t1345.16\t1252.21\t2762.92\t903.132\t1010.17\t793.427\t1028.35\t787.714\t896.383\t1280.24\t989.579\t4116.02\t888.393\t1010.76\t948.43\t987.99\t2304.8\t3284.09\t892.266\t901.612\t5580.45\t1020.12\t889.461\t1219.63\t1074.36\t850.366\t721.038\t869.968\t1066.86\t798.815\t925.858\t1230.54\t844.88\t961.583\t957.129\t881.474\t984.453\t1397.81\t1535.14\t1305.2\t1246.76\t1475.32\t1089.05\t1493.21\t3835.6\t1444.07\t1374.3\t6006.94\t3140.63\t1351.9\t1345.06\t1368.18\t1171.84\t1327.46\t1490.01\t1136.91\t1579.46\t1381.43\t1663.11\t3768.3\t1365.1\t1606.44\t1465.89\t1390.57\t1633.91\t1429.15\t1238.44\t1309.99\t631.551\t953.228\t557.93\t1008.16\t517.818\t738.783\t2826.58\t960.496\t986.361\t1108.16\t822.926\t2232.74\t852.779\t7594.61\t871.175\t1104.03\t3511.57\t638.88\t665.969\t3471.85\t6217.53\t974.453\t775.881\t910.504\t1237.05\t848.331\t760.279\t608.747\t750.602\t815.266\t822.667\t513.122\t741.422\t630.623\n", "Total lines examined: 75\n", "\n", "Attempting to extract gene data from matrix file...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully extracted gene data with 22283 rows\n", "First 20 gene IDs:\n", "Index(['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at', '1294_at',\n", " '1316_at', '1320_at', '1405_i_at', '1431_at', '1438_at', '1487_at',\n", " '1494_f_at', '1598_g_at', '160020_at', '1729_at', '1773_at', '177_at',\n", " '179_at', '1861_at'],\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": "a85be779", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "3f0a687a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:21:33.996584Z", "iopub.status.busy": "2025-03-25T07:21:33.996468Z", "iopub.status.idle": "2025-03-25T07:21:33.998435Z", "shell.execute_reply": "2025-03-25T07:21:33.998149Z" } }, "outputs": [], "source": [ "# Looking at the gene identifiers shown in the previous output\n", "# These identifiers (like '1007_s_at', '1053_at', '117_at') are Affymetrix probe IDs\n", "# from the Human Genome U133A array (as mentioned in Series_summary)\n", "# These are not standard human gene symbols and will need to be mapped to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "2b115a5f", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "6abe422b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:21:33.999648Z", "iopub.status.busy": "2025-03-25T07:21:33.999544Z", "iopub.status.idle": "2025-03-25T07:21:39.043087Z", "shell.execute_reply": "2025-03-25T07:21:39.042701Z" } }, "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 3075191 rows\n", "\n", "Gene annotation preview (first few rows):\n", "{'ID': ['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at'], 'GB_ACC': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'SPOT_ID': [nan, nan, nan, nan, nan], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014'], 'Sequence Type': ['Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence'], 'Sequence Source': ['Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database'], 'Target Description': ['U48705 /FEATURE=mRNA /DEFINITION=HSU48705 Human receptor tyrosine kinase DDR gene, complete cds', 'M87338 /FEATURE= /DEFINITION=HUMA1SBU Human replication factor C, 40-kDa subunit (A1) mRNA, complete cds', \"X51757 /FEATURE=cds /DEFINITION=HSP70B Human heat-shock protein HSP70B' gene\", 'X69699 /FEATURE= /DEFINITION=HSPAX8A H.sapiens Pax8 mRNA', 'L36861 /FEATURE=expanded_cds /DEFINITION=HUMGCAPB Homo sapiens guanylate cyclase activating protein (GCAP) gene exons 1-4, complete cds'], 'Representative Public ID': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'Gene Title': ['discoidin domain receptor tyrosine kinase 1 /// microRNA 4640', 'replication factor C (activator 1) 2, 40kDa', \"heat shock 70kDa protein 6 (HSP70B')\", 'paired box 8', 'guanylate cyclase activator 1A (retina)'], 'Gene Symbol': ['DDR1 /// MIR4640', 'RFC2', 'HSPA6', 'PAX8', 'GUCA1A'], 'ENTREZ_GENE_ID': ['780 /// 100616237', '5982', '3310', '7849', '2978'], 'RefSeq Transcript ID': ['NM_001202521 /// NM_001202522 /// NM_001202523 /// NM_001954 /// NM_013993 /// NM_013994 /// NR_039783 /// XM_005249385 /// XM_005249386 /// XM_005249387 /// XM_005249389 /// XM_005272873 /// XM_005272874 /// XM_005272875 /// XM_005272877 /// XM_005275027 /// XM_005275028 /// XM_005275030 /// XM_005275031 /// XM_005275162 /// XM_005275163 /// XM_005275164 /// XM_005275166 /// XM_005275457 /// XM_005275458 /// XM_005275459 /// XM_005275461 /// XM_006715185 /// XM_006715186 /// XM_006715187 /// XM_006715188 /// XM_006715189 /// XM_006715190 /// XM_006725501 /// XM_006725502 /// XM_006725503 /// XM_006725504 /// XM_006725505 /// XM_006725506 /// XM_006725714 /// XM_006725715 /// XM_006725716 /// XM_006725717 /// XM_006725718 /// XM_006725719 /// XM_006725720 /// XM_006725721 /// XM_006725722 /// XM_006725827 /// XM_006725828 /// XM_006725829 /// XM_006725830 /// XM_006725831 /// XM_006725832 /// XM_006726017 /// XM_006726018 /// XM_006726019 /// XM_006726020 /// XM_006726021 /// XM_006726022 /// XR_427836 /// XR_430858 /// XR_430938 /// XR_430974 /// XR_431015', 'NM_001278791 /// NM_001278792 /// NM_001278793 /// NM_002914 /// NM_181471 /// XM_006716080', 'NM_002155', 'NM_003466 /// NM_013951 /// NM_013952 /// NM_013953 /// NM_013992', 'NM_000409 /// XM_006715073'], 'Gene Ontology Biological Process': ['0001558 // regulation of cell growth // inferred from electronic annotation /// 0001952 // regulation of cell-matrix adhesion // inferred from electronic annotation /// 0006468 // protein phosphorylation // inferred from electronic annotation /// 0007155 // cell adhesion // traceable author statement /// 0007169 // transmembrane receptor protein tyrosine kinase signaling pathway // inferred from electronic annotation /// 0007565 // female pregnancy // inferred from electronic annotation /// 0007566 // embryo implantation // inferred from electronic annotation /// 0007595 // lactation // inferred from electronic annotation /// 0008285 // negative regulation of cell proliferation // inferred from electronic annotation /// 0010715 // regulation of extracellular matrix disassembly // inferred from mutant phenotype /// 0014909 // smooth muscle cell migration // inferred from mutant phenotype /// 0016310 // phosphorylation // inferred from electronic annotation /// 0018108 // peptidyl-tyrosine phosphorylation // inferred from electronic annotation /// 0030198 // extracellular matrix organization // traceable author statement /// 0038063 // collagen-activated tyrosine kinase receptor signaling pathway // inferred from direct assay /// 0038063 // collagen-activated tyrosine kinase receptor signaling pathway // inferred from mutant phenotype /// 0038083 // peptidyl-tyrosine autophosphorylation // inferred from direct assay /// 0043583 // ear development // inferred from electronic annotation /// 0044319 // wound healing, spreading of cells // inferred from mutant phenotype /// 0046777 // protein autophosphorylation // inferred from direct assay /// 0060444 // branching involved in mammary gland duct morphogenesis // inferred from electronic annotation /// 0060749 // mammary gland alveolus development // inferred from electronic annotation /// 0061302 // smooth muscle cell-matrix adhesion // inferred from mutant phenotype', '0000278 // mitotic cell cycle // traceable author statement /// 0000722 // telomere maintenance via recombination // traceable author statement /// 0000723 // telomere maintenance // traceable author statement /// 0006260 // DNA replication // traceable author statement /// 0006271 // DNA strand elongation involved in DNA replication // traceable author statement /// 0006281 // DNA repair // traceable author statement /// 0006283 // transcription-coupled nucleotide-excision repair // traceable author statement /// 0006289 // nucleotide-excision repair // traceable author statement /// 0006297 // nucleotide-excision repair, DNA gap filling // traceable author statement /// 0015979 // photosynthesis // inferred from electronic annotation /// 0015995 // chlorophyll biosynthetic process // inferred from electronic annotation /// 0032201 // telomere maintenance via semi-conservative replication // traceable author statement', '0000902 // cell morphogenesis // inferred from electronic annotation /// 0006200 // ATP catabolic process // inferred from direct assay /// 0006950 // response to stress // inferred from electronic annotation /// 0006986 // response to unfolded protein // traceable author statement /// 0034605 // cellular response to heat // inferred from direct assay /// 0042026 // protein refolding // inferred from direct assay /// 0070370 // cellular heat acclimation // inferred from mutant phenotype', '0001655 // urogenital system development // inferred from sequence or structural similarity /// 0001656 // metanephros development // inferred from electronic annotation /// 0001658 // branching involved in ureteric bud morphogenesis // inferred from expression pattern /// 0001822 // kidney development // inferred from expression pattern /// 0001823 // mesonephros development // inferred from sequence or structural similarity /// 0003337 // mesenchymal to epithelial transition involved in metanephros morphogenesis // inferred from expression pattern /// 0006351 // transcription, DNA-templated // inferred from direct assay /// 0006355 // regulation of transcription, DNA-templated // inferred from electronic annotation /// 0007275 // multicellular organismal development // inferred from electronic annotation /// 0007417 // central nervous system development // inferred from expression pattern /// 0009653 // anatomical structure morphogenesis // traceable author statement /// 0030154 // cell differentiation // inferred from electronic annotation /// 0030878 // thyroid gland development // inferred from expression pattern /// 0030878 // thyroid gland development // inferred from mutant phenotype /// 0038194 // thyroid-stimulating hormone signaling pathway // traceable author statement /// 0039003 // pronephric field specification // inferred from sequence or structural similarity /// 0042472 // inner ear morphogenesis // inferred from sequence or structural similarity /// 0042981 // regulation of apoptotic process // inferred from sequence or structural similarity /// 0045893 // positive regulation of transcription, DNA-templated // inferred from direct assay /// 0045893 // positive regulation of transcription, DNA-templated // inferred from sequence or structural similarity /// 0045944 // positive regulation of transcription from RNA polymerase II promoter // inferred from direct assay /// 0048793 // pronephros development // inferred from sequence or structural similarity /// 0071371 // cellular response to gonadotropin stimulus // inferred from direct assay /// 0071599 // otic vesicle development // inferred from expression pattern /// 0072050 // S-shaped body morphogenesis // inferred from electronic annotation /// 0072073 // kidney epithelium development // inferred from electronic annotation /// 0072108 // positive regulation of mesenchymal to epithelial transition involved in metanephros morphogenesis // inferred from sequence or structural similarity /// 0072164 // mesonephric tubule development // inferred from electronic annotation /// 0072207 // metanephric epithelium development // inferred from expression pattern /// 0072221 // metanephric distal convoluted tubule development // inferred from sequence or structural similarity /// 0072278 // metanephric comma-shaped body morphogenesis // inferred from expression pattern /// 0072284 // metanephric S-shaped body morphogenesis // inferred from expression pattern /// 0072289 // metanephric nephron tubule formation // inferred from sequence or structural similarity /// 0072305 // negative regulation of mesenchymal cell apoptotic process involved in metanephric nephron morphogenesis // inferred from sequence or structural similarity /// 0072307 // regulation of metanephric nephron tubule epithelial cell differentiation // inferred from sequence or structural similarity /// 0090190 // positive regulation of branching involved in ureteric bud morphogenesis // inferred from sequence or structural similarity /// 1900212 // negative regulation of mesenchymal cell apoptotic process involved in metanephros development // inferred from sequence or structural similarity /// 1900215 // negative regulation of apoptotic process involved in metanephric collecting duct development // inferred from sequence or structural similarity /// 1900218 // negative regulation of apoptotic process involved in metanephric nephron tubule development // inferred from sequence or structural similarity /// 2000594 // positive regulation of metanephric DCT cell differentiation // inferred from sequence or structural similarity /// 2000611 // positive regulation of thyroid hormone generation // inferred from mutant phenotype /// 2000612 // regulation of thyroid-stimulating hormone secretion // inferred from mutant phenotype', '0007165 // signal transduction // non-traceable author statement /// 0007601 // visual perception // inferred from electronic annotation /// 0007602 // phototransduction // inferred from electronic annotation /// 0007603 // phototransduction, visible light // traceable author statement /// 0016056 // rhodopsin mediated signaling pathway // traceable author statement /// 0022400 // regulation of rhodopsin mediated signaling pathway // traceable author statement /// 0030828 // positive regulation of cGMP biosynthetic process // inferred from electronic annotation /// 0031282 // regulation of guanylate cyclase activity // inferred from electronic annotation /// 0031284 // positive regulation of guanylate cyclase activity // inferred from electronic annotation /// 0050896 // response to stimulus // inferred from electronic annotation'], 'Gene Ontology Cellular Component': ['0005576 // extracellular region // inferred from electronic annotation /// 0005615 // extracellular space // inferred from direct assay /// 0005886 // plasma membrane // traceable author statement /// 0005887 // integral component of plasma membrane // traceable author statement /// 0016020 // membrane // inferred from electronic annotation /// 0016021 // integral component of membrane // inferred from electronic annotation /// 0043235 // receptor complex // inferred from direct assay /// 0070062 // extracellular vesicular exosome // inferred from direct assay', '0005634 // nucleus // inferred from electronic annotation /// 0005654 // nucleoplasm // traceable author statement /// 0005663 // DNA replication factor C complex // inferred from direct assay', '0005737 // cytoplasm // inferred from direct assay /// 0005814 // centriole // inferred from direct assay /// 0005829 // cytosol // inferred from direct assay /// 0008180 // COP9 signalosome // inferred from direct assay /// 0070062 // extracellular vesicular exosome // inferred from direct assay /// 0072562 // blood microparticle // inferred from direct assay', '0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // inferred from sequence or structural similarity /// 0005730 // nucleolus // inferred from direct assay', '0001750 // photoreceptor outer segment // inferred from electronic annotation /// 0001917 // photoreceptor inner segment // inferred from electronic annotation /// 0005578 // proteinaceous extracellular matrix // inferred from electronic annotation /// 0005886 // plasma membrane // inferred from direct assay /// 0016020 // membrane // inferred from electronic annotation /// 0097381 // photoreceptor disc membrane // traceable author statement'], 'Gene Ontology Molecular Function': ['0000166 // nucleotide binding // inferred from electronic annotation /// 0004672 // protein kinase activity // inferred from electronic annotation /// 0004713 // protein tyrosine kinase activity // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // traceable author statement /// 0005515 // protein binding // inferred from physical interaction /// 0005518 // collagen binding // inferred from direct assay /// 0005518 // collagen binding // inferred from mutant phenotype /// 0005524 // ATP binding // inferred from electronic annotation /// 0016301 // kinase activity // inferred from electronic annotation /// 0016740 // transferase activity // inferred from electronic annotation /// 0016772 // transferase activity, transferring phosphorus-containing groups // inferred from electronic annotation /// 0038062 // protein tyrosine kinase collagen receptor activity // inferred from direct assay /// 0046872 // metal ion binding // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0005524 // ATP binding // inferred from electronic annotation /// 0016851 // magnesium chelatase activity // inferred from electronic annotation /// 0017111 // nucleoside-triphosphatase activity // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation /// 0019899 // enzyme binding // inferred from physical interaction /// 0031072 // heat shock protein binding // inferred from physical interaction /// 0042623 // ATPase activity, coupled // inferred from direct assay /// 0051082 // unfolded protein binding // inferred from direct assay', '0000979 // RNA polymerase II core promoter sequence-specific DNA binding // inferred from direct assay /// 0003677 // DNA binding // inferred from direct assay /// 0003677 // DNA binding // inferred from mutant phenotype /// 0003700 // sequence-specific DNA binding transcription factor activity // inferred from direct assay /// 0004996 // thyroid-stimulating hormone receptor activity // traceable author statement /// 0005515 // protein binding // inferred from physical interaction /// 0044212 // transcription regulatory region DNA binding // inferred from direct assay', '0005509 // calcium ion binding // inferred from electronic annotation /// 0008048 // calcium sensitive guanylate cyclase activator activity // inferred from electronic annotation /// 0030249 // guanylate cyclase regulator activity // inferred from electronic annotation /// 0046872 // metal ion binding // inferred from electronic annotation']}\n", "\n", "Column names in gene annotation data:\n", "['ID', 'GB_ACC', 'SPOT_ID', 'Species Scientific Name', 'Annotation Date', 'Sequence Type', 'Sequence Source', 'Target Description', 'Representative Public ID', 'Gene Title', 'Gene Symbol', 'ENTREZ_GENE_ID', 'RefSeq Transcript ID', 'Gene Ontology Biological Process', 'Gene Ontology Cellular Component', 'Gene Ontology Molecular Function']\n", "\n", "The dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\n", "Number of rows with GenBank accessions: 3075123 out of 3075191\n", "\n", "The dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\n", "Example SPOT_ID format: nan\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": "6d54f7cd", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "4e4bd34e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:21:39.044386Z", "iopub.status.busy": "2025-03-25T07:21:39.044272Z", "iopub.status.idle": "2025-03-25T07:21:40.274664Z", "shell.execute_reply": "2025-03-25T07:21:40.274261Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Creating gene mapping dataframe...\n", "Created gene mapping with 21225 entries\n", "First few rows of mapping dataframe:\n", "{'ID': ['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at'], 'Gene': ['DDR1 /// MIR4640', 'RFC2', 'HSPA6', 'PAX8', 'GUCA1A']}\n", "\n", "Converting probe-level measurements to gene expression data...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Converted gene expression data with 13830 genes\n", "First 10 gene symbols after mapping:\n", "['A1CF', 'A2M', 'A4GALT', 'A4GNT', 'AAAS', 'AACS', 'AADAC', 'AAGAB', 'AAK1', 'AAMDC']\n", "\n", "Saving gene expression data to ../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/gene_data/GSE68606.csv...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved successfully.\n" ] } ], "source": [ "# 1. Decide which columns in the gene annotation dataframe to use for mapping\n", "# Based on the preview, the 'ID' column in gene_annotation contains the probe IDs (e.g., '1007_s_at')\n", "# The 'Gene Symbol' column contains the gene symbols (e.g., 'DDR1 /// MIR4640')\n", "prob_col = 'ID'\n", "gene_col = 'Gene Symbol'\n", "\n", "# 2. Get the gene mapping dataframe\n", "print(\"Creating gene mapping dataframe...\")\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "print(f\"Created gene mapping with {len(mapping_df)} entries\")\n", "print(\"First few rows of mapping dataframe:\")\n", "print(preview_df(mapping_df))\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements 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 gene expression data with {len(gene_data.index)} genes\")\n", "print(\"First 10 gene symbols after mapping:\")\n", "print(gene_data.index[:10].tolist())\n", "\n", "# Save the gene data to a file\n", "print(f\"\\nSaving gene expression data to {out_gene_data_file}...\")\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data.to_csv(out_gene_data_file)\n", "print(\"Gene expression data saved successfully.\")\n" ] }, { "cell_type": "markdown", "id": "40bbde9e", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "ec608a6f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:21:40.276135Z", "iopub.status.busy": "2025-03-25T07:21:40.276008Z", "iopub.status.idle": "2025-03-25T07:21:44.004194Z", "shell.execute_reply": "2025-03-25T07:21:44.003837Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Loading gene expression data...\n", "Loaded gene data with 13830 genes and 137 samples\n", "\n", "Extracting clinical features...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Sample Characteristics Dictionary:\n", "{0: ['cell line: H2347', 'cell line: H1437', 'cell line: HCC78', 'cell line: H2087', 'cell line: H2009', 'cell line: --'], 1: ['disease state: --', 'disease state: Leiomyoma', 'disease state: Lung_Adenocarcinoma', 'disease state: Conventional_Clear_Cell_Renal_Cell_Carcinoma', 'disease state: Squamous Cell Carcinoma', 'disease state: Stomach Adenocarcinoma', 'disease state: Large Cell Lymphoma', 'disease state: Malignant Melanoma', 'disease state: Recurrent Renal Cell Carcinoma', 'disease state: Adrenal Cortical Adenoma', 'disease state: Ovarian Adenocarcinoma', 'disease state: Gastrointestinal_Stromal_Tumor', 'disease state: Metastatic Renal Cell Carcinoma', 'disease state: Non neoplastic liver with cirrosis', 'disease state: Malignant G1 Stromal Tumor', 'disease state: melanoma'], 2: ['tumor grading: --', 'tumor grading: G2/pT1pN0pMX', 'tumor grading: G3/pT2pN0pMX', 'tumor grading: G2/pT2pN0pMX', 'tumor grading: G3/pT4pNXpMX'], 3: ['disease stage: --', 'disease stage: Stage IA', 'disease stage: Stage IB', 'disease stage: Stage IIIB'], 4: ['organism part: --', 'organism part: Uterus', 'organism part: Lung', 'organism part: Stomach', 'organism part: Lymphoid tissue', 'organism part: Liver', 'organism part: Adrenal Gland', 'organism part: Ovary', 'organism part: Kidney', 'organism part: Skin', 'organism part: Lymph_Node'], 5: ['Sex: --', 'Sex: female', 'Sex: male'], 6: ['age: --', 'age: 67', 'age: 66', 'age: 72', 'age: 56', 'age: 48'], 7: ['histology: --', 'histology: Leiomyoma', 'histology: Lung_Adenocarcinoma', 'histology: Conventional_Clear_Cell_Renal_Cell_Carcinoma', 'histology: Stomach Adenocarcinoma', 'histology: Large Cell Lymphoma', 'histology: Metastatic Malignant Melanoma', 'histology: Recurrent Renal Cell Carcinoma, chromophobe cell type', 'histology: Non neoplastic liver with cirrosis', 'histology: Adrenal Cortical Adenoma', 'histology: Papillary Serous Adenocarcinoma', 'histology: Squamous cell carcinoma 85% tumor 15% Stroma', 'histology: Squamous Cell Carcinoma', 'histology: Malignant G1 Stromal Tumor', 'histology: metastatic renal cell carcinoma', 'histology: Lung Adenocarcinoma', 'histology: carcinoma', 'histology: Adenocarcinoma', 'histology: Squamous Cell carcinoma', 'histology: Metastatic Renal Cell Carcinoma, clear cell type', 'histology: Ovarian Adenocarcinoma', 'histology: Malignant G1 stromal tumor', 'histology: Adenocartcinoma of Lung', 'histology: Squamoous Cell Carcinoma', 'histology: Renal Cell Carcinoma', 'histology: Non neeoplastic liver with cirrosis', 'histology: Metastatic Renal Cell Carcinoma']}\n", "Clinical data extracted and saved to ../../output/preprocess/Kidney_Papillary_Cell_Carcinoma/clinical_data/GSE68606.csv\n", "Clinical data preview:\n", "{'GSM1676864': [0.0], 'GSM1676865': [0.0], 'GSM1676866': [0.0], 'GSM1676867': [0.0], 'GSM1676868': [0.0], 'GSM1676869': [0.0], 'GSM1676870': [0.0], 'GSM1676871': [0.0], 'GSM1676872': [0.0], 'GSM1676873': [0.0], 'GSM1676874': [0.0], 'GSM1676875': [0.0], 'GSM1676876': [0.0], 'GSM1676877': [0.0], 'GSM1676878': [0.0], 'GSM1676879': [0.0], 'GSM1676880': [0.0], 'GSM1676881': [0.0], 'GSM1676882': [0.0], 'GSM1676883': [0.0], 'GSM1676884': [0.0], 'GSM1676885': [0.0], 'GSM1676886': [0.0], 'GSM1676887': [0.0], 'GSM1676888': [0.0], 'GSM1676889': [0.0], 'GSM1676890': [0.0], 'GSM1676891': [0.0], 'GSM1676892': [0.0], 'GSM1676893': [0.0], 'GSM1676894': [0.0], 'GSM1676895': [0.0], 'GSM1676896': [0.0], 'GSM1676897': [0.0], 'GSM1676898': [0.0], 'GSM1676899': [0.0], 'GSM1676900': [0.0], 'GSM1676901': [0.0], 'GSM1676902': [0.0], 'GSM1676903': [0.0], 'GSM1676904': [0.0], 'GSM1676905': [0.0], 'GSM1676906': [0.0], 'GSM1676907': [0.0], 'GSM1676908': [0.0], 'GSM1676909': [0.0], 'GSM1676910': [0.0], 'GSM1676911': [0.0], 'GSM1676912': [0.0], 'GSM1676913': [0.0], 'GSM1676914': [0.0], 'GSM1676915': [0.0], 'GSM1676916': [0.0], 'GSM1676917': [0.0], 'GSM1676918': [0.0], 'GSM1676919': [0.0], 'GSM1676920': [0.0], 'GSM1676921': [0.0], 'GSM1676922': [0.0], 'GSM1676923': [0.0], 'GSM1676924': [0.0], 'GSM1676925': [0.0], 'GSM1676926': [0.0], 'GSM1676927': [0.0], 'GSM1676928': [0.0], 'GSM1676929': [0.0], 'GSM1676930': [0.0], 'GSM1676931': [0.0], 'GSM1676932': [0.0], 'GSM1676933': [0.0], 'GSM1676934': [0.0], 'GSM1676935': [0.0], 'GSM1676936': [0.0], 'GSM1676937': [0.0], 'GSM1676938': [0.0], 'GSM1676939': [0.0], 'GSM1676940': [0.0], 'GSM1676941': [0.0], 'GSM1676942': [0.0], 'GSM1676943': [0.0], 'GSM1676944': [0.0], 'GSM1676945': [0.0], 'GSM1676946': [0.0], 'GSM1676947': [0.0], 'GSM1676948': [0.0], 'GSM1676949': [0.0], 'GSM1676950': [0.0], 'GSM1676951': [0.0], 'GSM1676952': [0.0], 'GSM1676953': [0.0], 'GSM1676954': [0.0], 'GSM1676955': [0.0], 'GSM1676956': [0.0], 'GSM1676957': [0.0], 'GSM1676958': [0.0], 'GSM1676959': [0.0], 'GSM1676960': [0.0], 'GSM1676961': [0.0], 'GSM1676962': [0.0], 'GSM1676963': [0.0], 'GSM1676964': [0.0], 'GSM1676965': [0.0], 'GSM1676966': [0.0], 'GSM1676967': [0.0], 'GSM1676968': [0.0], 'GSM1676969': [0.0], 'GSM1676970': [0.0], 'GSM1676971': [0.0], 'GSM1676972': [0.0], 'GSM1676973': [0.0], 'GSM1676974': [0.0], 'GSM1676975': [0.0], 'GSM1676976': [0.0], 'GSM1676977': [0.0], 'GSM1676978': [0.0], 'GSM1676979': [0.0], 'GSM1676980': [0.0], 'GSM1676981': [0.0], 'GSM1676982': [0.0], 'GSM1676983': [0.0], 'GSM1676984': [0.0], 'GSM1676985': [0.0], 'GSM1676986': [0.0], 'GSM1676987': [0.0], 'GSM1676988': [0.0], 'GSM1676989': [0.0], 'GSM1676990': [0.0], 'GSM1676991': [0.0], 'GSM1676992': [0.0], 'GSM1676993': [0.0], 'GSM1676994': [0.0], 'GSM1676995': [0.0], 'GSM1676996': [0.0], 'GSM1676997': [0.0], 'GSM1676998': [0.0], 'GSM1676999': [0.0], 'GSM1677000': [0.0]}\n", "\n", "Linking clinical and genetic data...\n", "Linked data shape: (137, 13831)\n", "\n", "Handling missing values...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After handling missing values, data shape: (137, 13831)\n", "\n", "Checking for bias in features...\n", "Quartiles for 'Kidney_Papillary_Cell_Carcinoma':\n", " 25%: 0.0\n", " 50% (Median): 0.0\n", " 75%: 0.0\n", "Min: 0.0\n", "Max: 0.0\n", "The distribution of the feature 'Kidney_Papillary_Cell_Carcinoma' in this dataset is severely biased.\n", "\n", "\n", "Performing final validation...\n", "Dataset not usable for Kidney_Papillary_Cell_Carcinoma association studies. Data not saved.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "# This was already done and saved in the previous step, verified in the output\n", "# We'll load it to make sure gene_data is available for the rest of the processing\n", "print(\"\\nLoading gene expression data...\")\n", "try:\n", " gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n", " print(f\"Loaded gene data with {gene_data.shape[0]} genes and {gene_data.shape[1]} samples\")\n", "except Exception as e:\n", " print(f\"Error loading gene data: {e}\")\n", " gene_data = pd.DataFrame()\n", "\n", "# 2. Extract clinical features\n", "print(\"\\nExtracting clinical features...\")\n", "try:\n", " # Get the file paths for the SOFT file and matrix file again\n", " soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " \n", " # Obtain background information and clinical dataframe from matrix file\n", " background_info, clinical_data = get_background_and_clinical_data(\n", " matrix_file, \n", " prefixes_a=['!Series_title', '!Series_summary', '!Series_overall_design'],\n", " prefixes_b=['!Sample_geo_accession', '!Sample_characteristics_ch1']\n", " )\n", " \n", " # For diagnostic purposes, check the unique values in each row\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " print(\"Sample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", " \n", " # Based on sample_characteristics_dict:\n", " # Row 1 contains disease state info\n", " # Row 2 contains disease location\n", " # We'll use both to identify kidney cancer samples\n", " trait_row = 2 # Use disease location row\n", " \n", " # Define conversion function for the trait (kidney cancer)\n", " def convert_trait(value):\n", " \"\"\"\n", " Convert disease location to binary trait values based on kidney location.\n", " 1 for kidney samples, 0 for other locations\n", " \"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value part after the colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Check if it's a kidney sample\n", " if 'kidney' in value.lower():\n", " return 1 # Kidney samples as cases\n", " else:\n", " return 0 # Other locations as controls\n", "\n", " # Extract clinical features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=None, # No age data\n", " convert_age=None,\n", " gender_row=None, # No gender data\n", " convert_gender=None\n", " )\n", " \n", " # Save the 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 extracted and saved to {out_clinical_data_file}\")\n", " \n", " # For diagnostic purposes\n", " print(\"Clinical data preview:\")\n", " print(preview_df(selected_clinical_df))\n", " \n", "except Exception as e:\n", " print(f\"Error extracting clinical features: {e}\")\n", " selected_clinical_df = pd.DataFrame()\n", "\n", "# 3. Link clinical and genetic data\n", "print(\"\\nLinking clinical and genetic data...\")\n", "try:\n", " # Check if both datasets are available\n", " if not gene_data.empty and not selected_clinical_df.empty:\n", " # Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " \n", " # 4. Handle missing values\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", " # 5. 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(\"Clinical data or gene data is not available. Cannot proceed with linking.\")\n", " linked_data = pd.DataFrame()\n", " is_biased = True\n", "except Exception as e:\n", " print(f\"Error in linking data: {e}\")\n", " linked_data = pd.DataFrame()\n", " is_biased = True\n", "\n", "# 6. Final quality validation\n", "print(\"\\nPerforming final validation...\")\n", "note = \"\"\n", "if 'linked_data' not in locals() or linked_data.empty:\n", " note = \"Dataset failed processing: no usable samples remained after filtering.\"\n", " is_biased = True\n", " linked_data = pd.DataFrame() # Ensure linked_data exists for validation\n", "elif linked_data.shape[0] < 10:\n", " note = \"Dataset has too few samples (<10) after filtering for valid analysis.\"\n", " is_biased = True\n", "elif 'is_biased' in locals() and is_biased:\n", " note = \"Dataset has severely biased trait distribution.\"\n", "\n", "is_gene_available = 'gene_data' in locals() and not gene_data.empty\n", "is_trait_available = 'selected_clinical_df' in locals() and not selected_clinical_df.empty\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 'is_biased' in locals() else True,\n", " df=linked_data,\n", " note=note\n", ")\n", "\n", "# 7. 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 }