{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "726c02be", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:14:01.525445Z", "iopub.status.busy": "2025-03-25T08:14:01.525252Z", "iopub.status.idle": "2025-03-25T08:14:01.689714Z", "shell.execute_reply": "2025-03-25T08:14:01.689354Z" } }, "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 = \"Cervical_Cancer\"\n", "cohort = \"GSE146114\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Cervical_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Cervical_Cancer/GSE146114\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Cervical_Cancer/GSE146114.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Cervical_Cancer/gene_data/GSE146114.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Cervical_Cancer/clinical_data/GSE146114.csv\"\n", "json_path = \"../../output/preprocess/Cervical_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "0cf9a872", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "85a24119", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:14:01.690924Z", "iopub.status.busy": "2025-03-25T08:14:01.690784Z", "iopub.status.idle": "2025-03-25T08:14:01.854742Z", "shell.execute_reply": "2025-03-25T08:14:01.854383Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Combining imaging- and gene-based hypoxia biomarkers in cervical cancer improves prediction of treatment failure independent of intratumor heterogeneity\"\n", "!Series_summary\t\"Emerging biomarkers based on medical images and molecular characterization of tumor biopsies open up for combining the two disciplines and exploiting their synergy in treatment planning. We compared pretreatment classification of cervical cancer patients by two previously validated imaging- and gene-based hypoxia biomarkers, evaluated the influence of intratumor heterogeneity, and investigated the benefit of combining them in prediction of treatment failure. The imaging-based biomarker was hypoxic fraction, determined from diagnostic dynamic contrast enhanced (DCE)-MR images. The gene-based biomarker was a hypoxia gene expression signature determined from tumor biopsies. Paired data were available for 118 patients. Intratumor heterogeneity was assessed by variance analysis of MR images and multiple biopsies from the same tumor. The two biomarkers were combined using a dimension-reduction procedure. The biomarkers classified 75% of the tumors with the same hypoxia status. Both intratumor heterogeneity and distribution pattern of hypoxia from imaging were unrelated to inconsistent classification by the two biomarkers, and the hypoxia status of the slice covering the biopsy region was representative of the whole tumor. Hypoxia by genes was independent on tumor cell fraction and showed minor heterogeneity across multiple biopsies in 9 tumors. This suggested that the two biomarkers could contain complementary biological information. Combination of the biomarkers into a composite score led to improved prediction of treatment failure (HR:7.3) compared to imaging (HR:3.8) and genes (HR:3.0) and prognostic impact in multivariate analysis with clinical variables. In conclusion, combining imaging- and gene-based biomarkers enables more precise and informative assessment of hypoxia-related treatment resistance in cervical cancer, independent of intratumor heterogeneity.\"\n", "!Series_overall_design\t\"Totally 118 samples using pooled RNA isolated from 1-4 biopsies (median 2) per tumor were analysed; 84 with Illumina WG-6 v3 and 34 with Illumina HT-12 v4. In addition, each of 2-4 biopsies in nine tumors (24 samples in total) were analyzed with Illumina HT-12 v4.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['histology: Squamous cell carcinoma', 'histology: Adenocarcinom', 'histology: Adenosquamous'], 1: ['gene-based hypoxia: Less hypoxic', 'gene-based hypoxia: More hypoxic'], 2: ['imaging-based hypoxia: Less hypoxic', 'imaging-based hypoxia: More hypoxic'], 3: ['combined hypoxia biomarker: Less hypoxic', 'combined hypoxia biomarker: More hypoxic', 'combined hypoxia biomarker: NA'], 4: ['figo stage: 2B', 'figo stage: 3B', 'figo stage: 1B1', 'figo stage: 2A'], 5: ['hypoxia classifier: Less hypoxic', 'hypoxia classifier: More hypoxic', 'rna isolation method: Trizol', 'rna isolation method: miRNeasy'], 6: ['cohort: Cohort 2', 'cohort: Adeno', 'biopsy: Single biopsy']}\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": "94a5f3bf", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "05731bfc", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:14:01.855985Z", "iopub.status.busy": "2025-03-25T08:14:01.855847Z", "iopub.status.idle": "2025-03-25T08:14:01.879880Z", "shell.execute_reply": "2025-03-25T08:14:01.879600Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{'Sample_1': [1.0], 'Sample_2': [0.0], 'Sample_3': [nan], 'Sample_4': [nan], 'Sample_5': [nan], 'Sample_6': [nan], 'Sample_7': [nan], 'Sample_8': [nan], 'Sample_9': [nan]}\n", "Clinical data saved to ../../output/preprocess/Cervical_Cancer/clinical_data/GSE146114.csv\n" ] } ], "source": [ "import pandas as pd\n", "import numpy as np\n", "import os\n", "from typing import Optional, Dict, Any, Callable\n", "import json\n", "\n", "# 1. Gene Expression Data Availability\n", "# From the background information, we know this is a gene expression dataset\n", "# The background mentions Illumina WG-6 v3 and Illumina HT-12 v4 which are gene expression platforms\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait (Cervical Cancer)\n", "# The key value 1 contains gene-based hypoxia status which is a binary trait related to cervical cancer hypoxia\n", "trait_row = 1\n", "\n", "# For age\n", "# There is no age information in the sample characteristics\n", "age_row = None\n", "\n", "# For gender\n", "# All patients are female (cervical cancer patients), but gender is not explicitly mentioned\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert trait value to binary (0 or 1)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract the value after the colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert based on hypoxia status\n", " if 'less hypoxic' in value.lower():\n", " return 0 # Less hypoxic\n", " elif 'more hypoxic' in value.lower():\n", " return 1 # More hypoxic\n", " else:\n", " return None # Unknown or invalid value\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to continuous\"\"\"\n", " # No age data available\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender value to binary (0 for female, 1 for male)\"\"\"\n", " # No gender data available\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Initial validation - check if both gene and trait data are available\n", "is_trait_available = trait_row is not None\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # Create a dataframe from the sample characteristics dictionary provided in the previous step\n", " # The sample characteristics dictionary contains the relevant clinical information\n", " # Sample characteristics were provided in the previous step output\n", " sample_char_dict = {0: ['histology: Squamous cell carcinoma', 'histology: Adenosquamous'], \n", " 1: ['gene-based hypoxia: More hypoxic', 'gene-based hypoxia: Less hypoxic'], \n", " 2: ['imaging-based hypoxia: Less hypoxic', 'imaging-based hypoxia: More hypoxic'], \n", " 3: ['combined hypoxia biomarker: More hypoxic', 'combined hypoxia biomarker: Less hypoxic'], \n", " 4: ['cohort (gse36562 study): DCE-MRI cohort', 'tissue: cervical tumor', 'cohort (gse36562 study): Validation cohort', 'figo stage: 2B'], \n", " 5: ['hypoxia score: High', 'hypoxia score: Low', 'figo stage: 2B', 'figo stage: 3B', 'rna isolation method: Trizol'], \n", " 6: ['tissue: cervical tumor', 'cohort (gse36562 study): DCE-MRI cohort', 'biopsy: Pooled biopsies'], \n", " 7: ['figo stage: 2B', 'figo stage: 3B', 'hypoxia score: Low', 'figo stage: 4A', 'figo stage: 3A', 'figo stage: 1B1', 'figo stage: 2A', 'figo stage: 1B2', np.nan], \n", " 8: ['cohort: Validation cohort', 'cohort: basic cohort', np.nan], \n", " 9: ['cohort (gse38964 study): Integrative cohort', 'lymph node status (gse38433 study): 1', np.nan, 'lymph node status (gse38433 study): 0', 'cohort (gse38964 study): Validation cohort'], \n", " 10: ['3p status: Loss', 'cohort (gse38964 study): Integrative cohort', np.nan, '3p status: No loss', 'cohort (gse38964 study): Validation cohort', '3p status: Not determined'], \n", " 11: [np.nan, '3p status: Loss', '3p status: No loss', '3p status: Not determined']}\n", " \n", " # Create a dataframe with the sample characteristics dictionary\n", " # The index will be the row numbers, and columns will be sample IDs (we'll create dummy IDs)\n", " max_samples = max(len(features) for features in sample_char_dict.values())\n", " sample_ids = [f\"Sample_{i+1}\" for i in range(max_samples)]\n", " \n", " clinical_data = pd.DataFrame(index=sample_char_dict.keys(), columns=sample_ids)\n", " \n", " # Fill the dataframe with the sample characteristics\n", " for row, features in sample_char_dict.items():\n", " for col, feature in enumerate(features):\n", " if col < len(sample_ids):\n", " clinical_data.loc[row, sample_ids[col]] = feature\n", " \n", " # Use geo_select_clinical_features to extract clinical features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=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 selected clinical features to the output file\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "b8a30856", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "a82ece09", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:14:01.880920Z", "iopub.status.busy": "2025-03-25T08:14:01.880814Z", "iopub.status.idle": "2025-03-25T08:14:02.130358Z", "shell.execute_reply": "2025-03-25T08:14:02.129918Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209',\n", " 'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229',\n", " 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236',\n", " 'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253',\n", " 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.\n", "print(gene_data.index[:20])\n" ] }, { "cell_type": "markdown", "id": "eab42279", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "6c438850", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:14:02.132068Z", "iopub.status.busy": "2025-03-25T08:14:02.131890Z", "iopub.status.idle": "2025-03-25T08:14:02.133724Z", "shell.execute_reply": "2025-03-25T08:14:02.133440Z" } }, "outputs": [], "source": [ "# These identifiers are Illumina probe IDs (ILMN_*), not human gene symbols. \n", "# They need to be mapped to standard gene symbols for meaningful analysis.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "dc40c6d2", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "57febdc9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:14:02.135258Z", "iopub.status.busy": "2025-03-25T08:14:02.135128Z", "iopub.status.idle": "2025-03-25T08:14:15.042213Z", "shell.execute_reply": "2025-03-25T08:14:15.041847Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['ILMN_1825594', 'ILMN_1810803', 'ILMN_1722532', 'ILMN_1884413', 'ILMN_1906034'], 'Species': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Source': ['Unigene', 'RefSeq', 'RefSeq', 'Unigene', 'Unigene'], 'Search_Key': ['ILMN_89282', 'ILMN_35826', 'ILMN_25544', 'ILMN_132331', 'ILMN_105017'], 'Transcript': ['ILMN_89282', 'ILMN_35826', 'ILMN_25544', 'ILMN_132331', 'ILMN_105017'], 'ILMN_Gene': ['HS.388528', 'LOC441782', 'JMJD1A', 'HS.580150', 'HS.540210'], 'Source_Reference_ID': ['Hs.388528', 'XM_497527.2', 'NM_018433.3', 'Hs.580150', 'Hs.540210'], 'RefSeq_ID': [nan, 'XM_497527.2', 'NM_018433.3', nan, nan], 'Unigene_ID': ['Hs.388528', nan, nan, 'Hs.580150', 'Hs.540210'], 'Entrez_Gene_ID': [nan, 441782.0, 55818.0, nan, nan], 'GI': [23525203.0, 89042416.0, 46358420.0, 7376124.0, 5437312.0], 'Accession': ['BU678343', 'XM_497527.2', 'NM_018433.3', 'AW629334', 'AI818233'], 'Symbol': [nan, 'LOC441782', 'JMJD1A', nan, nan], 'Protein_Product': [nan, 'XP_497527.2', 'NP_060903.2', nan, nan], 'Array_Address_Id': [1740241.0, 1850750.0, 1240504.0, 4050487.0, 2190598.0], 'Probe_Type': ['S', 'S', 'S', 'S', 'S'], 'Probe_Start': [349.0, 902.0, 4359.0, 117.0, 304.0], 'SEQUENCE': ['CTCTCTAAAGGGACAACAGAGTGGACAGTCAAGGAACTCCACATATTCAT', 'GGGGTCAAGCCCAGGTGAAATGTGGATTGGAAAAGTGCTTCCCTTGCCCC', 'CCAGGCTGTAAAAGCAAAACCTCGTATCAGCTCTGGAACAATACCTGCAG', 'CCAGACAGGAAGCATCAAGCCCTTCAGGAAAGAATATGCGAGAGTGCTGC', 'TGTGCAGAAAGCTGATGGAAGGGAGAAAGAATGGAAGTGGGTCACACAGC'], 'Chromosome': [nan, nan, '2', nan, nan], 'Probe_Chr_Orientation': [nan, nan, '+', nan, nan], 'Probe_Coordinates': [nan, nan, '86572991-86573040', nan, nan], 'Cytoband': [nan, nan, '2p11.2e', nan, nan], 'Definition': ['UI-CF-EC0-abi-c-12-0-UI.s1 UI-CF-EC0 Homo sapiens cDNA clone UI-CF-EC0-abi-c-12-0-UI 3, mRNA sequence', 'PREDICTED: Homo sapiens similar to spectrin domain with coiled-coils 1 (LOC441782), mRNA.', 'Homo sapiens jumonji domain containing 1A (JMJD1A), mRNA.', 'hi56g05.x1 Soares_NFL_T_GBC_S1 Homo sapiens cDNA clone IMAGE:2976344 3, mRNA sequence', 'wk77d04.x1 NCI_CGAP_Pan1 Homo sapiens cDNA clone IMAGE:2421415 3, mRNA sequence'], 'Ontology_Component': [nan, nan, 'nucleus [goid 5634] [evidence IEA]', nan, nan], 'Ontology_Process': [nan, nan, 'chromatin modification [goid 16568] [evidence IEA]; transcription [goid 6350] [evidence IEA]; regulation of transcription, DNA-dependent [goid 6355] [evidence IEA]', nan, nan], 'Ontology_Function': [nan, nan, 'oxidoreductase activity [goid 16491] [evidence IEA]; oxidoreductase activity, acting on single donors with incorporation of molecular oxygen, incorporation of two atoms of oxygen [goid 16702] [evidence IEA]; zinc ion binding [goid 8270] [evidence IEA]; metal ion binding [goid 46872] [evidence IEA]; iron ion binding [goid 5506] [evidence IEA]', nan, nan], 'Synonyms': [nan, nan, 'JHMD2A; JMJD1; TSGA; KIAA0742; DKFZp686A24246; DKFZp686P07111', nan, nan], 'GB_ACC': ['BU678343', 'XM_497527.2', 'NM_018433.3', 'AW629334', 'AI818233']}\n" ] } ], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n", "print(\"Gene annotation preview:\")\n", "print(preview_df(gene_annotation))\n" ] }, { "cell_type": "markdown", "id": "1fc79ff3", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "6b88fc77", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:14:15.043645Z", "iopub.status.busy": "2025-03-25T08:14:15.043532Z", "iopub.status.idle": "2025-03-25T08:14:15.451623Z", "shell.execute_reply": "2025-03-25T08:14:15.451244Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Mapped gene expression data shape: (18838, 58)\n", "First few gene symbols:\n", "Index(['A1BG', 'A2BP1', 'A2M', 'A2ML1', 'A3GALT2'], dtype='object', name='Gene')\n" ] } ], "source": [ "# 1. Determine which columns in gene_annotation store identifiers and gene symbols\n", "# After examining the preview, we can see that:\n", "# 'ID' column contains the Illumina probe IDs (ILMN_*) matching the gene_data index\n", "# 'Symbol' column contains the gene symbols we need to map to\n", "\n", "# 2. Get gene mapping dataframe using the two relevant columns\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n", "\n", "# 3. Apply gene mapping to convert probe measurements to gene expression data\n", "# This handles the many-to-many relationship between probes and genes\n", "# If a probe maps to multiple genes, its expression is divided equally among those genes\n", "# Then values for each gene are summed across all contributing probes\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "# Print the shape of the new gene expression dataframe\n", "print(f\"Mapped gene expression data shape: {gene_data.shape}\")\n", "# Print the first few gene symbols to confirm successful mapping\n", "print(\"First few gene symbols:\")\n", "print(gene_data.index[:5])\n" ] }, { "cell_type": "markdown", "id": "08d9fb72", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "c5d91eaf", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:14:15.452928Z", "iopub.status.busy": "2025-03-25T08:14:15.452823Z", "iopub.status.idle": "2025-03-25T08:14:24.440339Z", "shell.execute_reply": "2025-03-25T08:14:24.439588Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Cervical_Cancer/gene_data/GSE146114.csv\n", "Clinical data saved to ../../output/preprocess/Cervical_Cancer/clinical_data/GSE146114.csv\n", "Gene data samples: Index(['GSM1868975', 'GSM1868976', 'GSM1868977', 'GSM1868978', 'GSM1868979'], dtype='object') ...\n", "Clinical data samples: Index(['GSM1868975', 'GSM1868976', 'GSM1868977', 'GSM1868978', 'GSM1868979'], dtype='object') ...\n", "Number of common samples: 58\n", "Linked data shape: (58, 17552)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape after handling missing values: (58, 17552)\n", "For the feature 'Cervical_Cancer', the least common label is '1.0' with 13 occurrences. This represents 22.41% of the dataset.\n", "The distribution of the feature 'Cervical_Cancer' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Cervical_Cancer/GSE146114.csv\n" ] } ], "source": [ "# 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# Re-extract clinical data directly from the source file to get proper sample IDs\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", "\n", "# Define the conversion function for the trait (gene-based hypoxia)\n", "def convert_trait(value):\n", " \"\"\"Convert trait value to binary (0 or 1)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract the value after the colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert based on hypoxia status\n", " if 'less hypoxic' in value.lower():\n", " return 0 # Less hypoxic\n", " elif 'more hypoxic' in value.lower():\n", " return 1 # More hypoxic\n", " else:\n", " return None # Unknown or invalid value\n", "\n", "# Extract clinical features with proper sample IDs\n", "selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=1, # Row 1 contains gene-based hypoxia information\n", " convert_trait=convert_trait\n", ")\n", "\n", "# Save the correctly formatted clinical data\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "selected_clinical_df.to_csv(out_clinical_data_file)\n", "print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "\n", "# Print sample IDs from both datasets for diagnostic purposes\n", "print(\"Gene data samples:\", normalized_gene_data.columns[:5], \"...\")\n", "print(\"Clinical data samples:\", selected_clinical_df.columns[:5], \"...\")\n", "\n", "# Find common samples between the datasets\n", "common_samples = set(normalized_gene_data.columns).intersection(set(selected_clinical_df.columns))\n", "print(f\"Number of common samples: {len(common_samples)}\")\n", "\n", "if len(common_samples) > 0:\n", " # Filter both datasets to only include common samples\n", " normalized_gene_data = normalized_gene_data[list(common_samples)]\n", " selected_clinical_df = selected_clinical_df[list(common_samples)]\n", " \n", " # Now link the clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", " print(\"Linked data shape:\", linked_data.shape)\n", " \n", " # Handle missing values in the linked data\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(\"Linked data shape after handling missing values:\", linked_data.shape)\n", " \n", " if linked_data.shape[0] > 0:\n", " # 4. Determine whether the trait and some demographic features are severely biased\n", " is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " \n", " # 5. Conduct quality check and save the cohort information\n", " is_usable = validate_and_save_cohort_info(\n", " is_final=True, \n", " cohort=cohort, \n", " info_path=json_path, \n", " is_gene_available=True, \n", " is_trait_available=True, \n", " is_biased=is_trait_biased, \n", " df=unbiased_linked_data,\n", " note=\"Study on hypoxia biomarkers in cervical cancer patients. Trait is gene-based hypoxic status.\"\n", " )\n", " \n", " # 6. If the linked data is usable, save it as a CSV file\n", " if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", " else:\n", " print(\"Data was determined to be unusable and was not saved\")\n", " else:\n", " print(\"No samples remained after handling missing values. Dataset is unusable.\")\n", " validate_and_save_cohort_info(\n", " is_final=True, \n", " cohort=cohort, \n", " info_path=json_path, \n", " is_gene_available=True, \n", " is_trait_available=True, \n", " is_biased=True, # We consider empty datasets as biased\n", " df=pd.DataFrame(),\n", " note=\"All samples were filtered out due to missing trait values or excessive missing genes.\"\n", " )\n", "else:\n", " print(\"No common samples between clinical and gene expression data. Cannot create linked dataset.\")\n", " validate_and_save_cohort_info(\n", " is_final=True, \n", " cohort=cohort, \n", " info_path=json_path, \n", " is_gene_available=True, \n", " is_trait_available=True, \n", " is_biased=True, # We consider datasets with no overlap as biased\n", " df=pd.DataFrame(),\n", " note=\"No overlapping samples between clinical and gene expression data.\"\n", " )" ] } ], "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 }