{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "2db3d5cc", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:57:28.978042Z", "iopub.status.busy": "2025-03-25T06:57:28.977867Z", "iopub.status.idle": "2025-03-25T06:57:29.145250Z", "shell.execute_reply": "2025-03-25T06:57:29.144893Z" } }, "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 = \"Bladder_Cancer\"\n", "cohort = \"GSE222073\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Bladder_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Bladder_Cancer/GSE222073\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Bladder_Cancer/GSE222073.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Bladder_Cancer/gene_data/GSE222073.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Bladder_Cancer/clinical_data/GSE222073.csv\"\n", "json_path = \"../../output/preprocess/Bladder_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "408fde1c", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "bf1b0f8b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:57:29.146536Z", "iopub.status.busy": "2025-03-25T06:57:29.146394Z", "iopub.status.idle": "2025-03-25T06:57:29.284560Z", "shell.execute_reply": "2025-03-25T06:57:29.284207Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Patterns of metastasis and recurrence in urothelial cancer molecular subtypes\"\n", "!Series_summary\t\"This series contains the gene expression data from urothelial bladder cancer samples from Swedish patients that were used to analyze metastatic sites. Included patients have a recurrence or distant metastasis before or after treatment with chemotherapy. Patients with only lymph-node metastases are not included. A previous series (GSE169455) contains data from all patients that recieved two or more cycles of neoadjuvant chemotherapy with curative intent. Patients in that series that developed distant recurrence are re-analyzed here. A few samples from a previous cystectomy series (GSE83586) are also included as re-analysis. In addition, the current series contains data from patients treated with palliative first-line chemotherapy, curative adjuvant chemotherapy, or < 2 cycles of neoadjuvant chemotherapy.\"\n", "!Series_summary\t\"Raw data should be adjusted in data processing for batch variables: Labeling batch and Labeling kit.\"\n", "!Series_overall_design\t\"Retrospective cohort study aiming to study metastatic sites and chemotherapy response in muscle-invasive bladder cancer.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['labeling kit: SensationPlus FFPE Amplification and WT labeling kit', 'labeling kit: GeneChip WT Pico kit'], 1: ['labeling batch: 3', 'labeling batch: 4', 'labeling batch: 5', 'labeling batch: 6', 'labeling batch: 7', 'labeling batch: 8', 'labeling batch: 9', 'labeling batch: 10', 'labeling batch: 11', 'labeling batch: 13', 'labeling batch: 14', 'labeling batch: 15', 'labeling batch: 16', 'labeling batch: 17', 'labeling batch: 18', 'labeling batch: 19', 'labeling batch: 20', 'labeling batch: 21', 'labeling batch: 22', 'labeling batch: 23', 'labeling batch: 24', 'labeling batch: 25', 'labeling batch: 26', 'labeling batch: 27'], 2: ['clinical tnm staging: cTxN0M1', 'clinical tnm staging: cT3N0M0', 'clinical tnm staging: pT4aN1M0', 'clinical tnm staging: cT2N0M0', 'clinical tnm staging: cT4bN0M0', 'clinical tnm staging: cTxN2M1', 'clinical tnm staging: cTxN3M1', 'clinical tnm staging: cT3bN0M0', 'clinical tnm staging: cTxNxM1', 'clinical tnm staging: cT2N2M0', 'clinical tnm staging: CT3bN0M0', 'clinical tnm staging: cT4bN1M0', 'clinical tnm staging: pT3bN2M0', 'clinical tnm staging: cT1N3M1', 'clinical tnm staging: cT3N1M0', 'clinical tnm staging: cT4aN0M0', 'clinical tnm staging: cT4bN2M0', 'clinical tnm staging: cT4N0M0', 'clinical tnm staging: cT1N0M1', 'clinical tnm staging: cT2N0M1', 'clinical tnm staging: cT2N1M0', 'clinical tnm staging: cT3bN0M1', 'clinical tnm staging: cT3N1M1', 'clinical tnm staging: pT1N2M0', 'clinical tnm staging: pT4aN2M0', 'clinical tnm staging: cT3N2M1', 'clinical tnm staging: cT3aN2M0', 'clinical tnm staging: cT2N3M1', 'clinical tnm staging: pT2N2M0', 'clinical tnm staging: cT2N2M1'], 3: ['chemotherapy type: palliative', 'chemotherapy type: neoadjuvant', 'chemotherapy type: adjuvant', 'chemotherapy type: induction', 'chemotherapy type: curative radiochemotherapy', 'chemotherapy type: induction + radiotherapy'], 4: ['lundtax rna-subtype: UroC', 'lundtax rna-subtype: GU', 'lundtax rna-subtype: UroB', 'lundtax rna-subtype: UroA', 'lundtax rna-subtype: ScNE', 'lundtax rna-subtype: BASQ', 'lundtax rna-subtype: Mes'], 5: ['lundtax ihc-subtype: Uro', 'lundtax ihc-subtype: GU', 'lundtax ihc-subtype: BASQ', 'lundtax ihc-subtype: ScNE', 'lundtax ihc-subtype: Mes'], 6: ['consensus classifier subtype: LumNS', 'consensus classifier subtype: LumU', 'consensus classifier subtype: BASQ', 'consensus classifier subtype: StromaRich', 'consensus classifier subtype: LumP', 'consensus classifier subtype: NE_like'], 7: ['rm-lymphnode: no', 'rm-lymphnode: yes'], 8: ['rm-local: no', 'rm-local: yes'], 9: ['rm-lung: no', 'rm-lung: yes'], 10: ['rm-liver: no', 'rm-liver: yes'], 11: ['rm-bone: yes', 'rm-bone: no'], 12: ['rm-other: no', 'rm-other: yes']}\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": "caacbf57", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "61f0d6f2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:57:29.286163Z", "iopub.status.busy": "2025-03-25T06:57:29.286048Z", "iopub.status.idle": "2025-03-25T06:57:29.290774Z", "shell.execute_reply": "2025-03-25T06:57:29.290465Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data file not found at ../../input/GEO/Bladder_Cancer/GSE222073/clinical_data.csv\n", "Skipping clinical feature extraction.\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# From the background information, it appears this dataset contains gene expression data for urothelial bladder cancer\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For trait (Bladder Cancer)\n", "# From the provided sample characteristics, we can use bone metastasis information as our trait\n", "trait_row = 11 # Key 11 contains 'rm-bone: yes/no' data\n", "\n", "# Age is not explicitly mentioned in the sample characteristics\n", "age_row = None \n", "\n", "# Gender is not explicitly mentioned in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "# For trait (bone metastasis in bladder cancer)\n", "def convert_trait(value):\n", " if value is None:\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 to binary (1 for yes, 0 for no)\n", " if value.lower() == 'yes':\n", " return 1\n", " elif value.lower() == 'no':\n", " return 0\n", " else:\n", " return None\n", "\n", "# Age conversion function (not used as age is not available)\n", "def convert_age(value):\n", " return None\n", "\n", "# Gender conversion function (not used as gender is not available)\n", "def convert_gender(value):\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine if trait data is available\n", "is_trait_available = trait_row is not None\n", "# Initial filtering on usability\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", " try:\n", " # Check if the clinical data file exists\n", " if os.path.exists(f\"{in_cohort_dir}/clinical_data.csv\"):\n", " # Load the clinical data and extract features\n", " clinical_data = pd.read_csv(f\"{in_cohort_dir}/clinical_data.csv\")\n", " \n", " # Use the library function to extract features\n", " selected_clinical = 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_df(selected_clinical))\n", " \n", " # Save the clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " else:\n", " print(f\"Clinical data file not found at {in_cohort_dir}/clinical_data.csv\")\n", " print(\"Skipping clinical feature extraction.\")\n", " except Exception as e:\n", " print(f\"Error processing clinical data: {e}\")\n", " is_trait_available = False\n" ] }, { "cell_type": "markdown", "id": "4f106830", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "766f954b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:57:29.292252Z", "iopub.status.busy": "2025-03-25T06:57:29.292140Z", "iopub.status.idle": "2025-03-25T06:57:29.520354Z", "shell.execute_reply": "2025-03-25T06:57:29.520015Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Index(['1-Mar', '2-Mar', '3-Mar', '4-Mar', '5-Mar', '6-Mar', '7-Mar', 'A2M',\n", " 'A2ML1', 'A4GALT', 'A4GNT', 'AAAS', 'AACS', 'AADAT', 'AAGAB', 'AAK1',\n", " 'AAMDC', 'AAMP', 'AANAT', 'AAR2'],\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": "b9310392", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "ff9e60c8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:57:29.522077Z", "iopub.status.busy": "2025-03-25T06:57:29.521946Z", "iopub.status.idle": "2025-03-25T06:57:29.524189Z", "shell.execute_reply": "2025-03-25T06:57:29.523869Z" } }, "outputs": [], "source": [ "# Examining the gene identifiers in the expression data\n", "\n", "# Based on the sample of gene identifiers shown, I observe:\n", "# - Many entries like \"A2M\", \"AAAS\", \"AAMP\" which appear to be standard HGNC gene symbols\n", "# - Some unusual entries like \"1-Mar\", \"2-Mar\" etc. which are not standard gene symbols \n", "# (these are likely MARCH family genes that have been incorrectly formatted)\n", "\n", "# Since most identifiers appear to be gene symbols already but with some formatting issues,\n", "# I'll recommend mapping to ensure consistency\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "c966be05", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "98aace6e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:57:29.525732Z", "iopub.status.busy": "2025-03-25T06:57:29.525626Z", "iopub.status.idle": "2025-03-25T06:57:31.658348Z", "shell.execute_reply": "2025-03-25T06:57:31.657934Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['LOC100287497', 'SAMD11', 'KLHL17', 'PLEKHN1', 'ISG15'], 'ORF': ['LOC100287497', 'SAMD11', 'KLHL17', 'PLEKHN1', 'ISG15']}\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": "1ba0d055", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "ca948e83", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:57:31.660042Z", "iopub.status.busy": "2025-03-25T06:57:31.659909Z", "iopub.status.idle": "2025-03-25T06:57:35.348166Z", "shell.execute_reply": "2025-03-25T06:57:35.347772Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Mapped gene data preview (first 5 genes):\n", "Index(['A2M', 'A2ML1', 'A4GALT', 'A4GNT', 'AAAS'], dtype='object', name='Gene')\n", "Total number of genes after mapping: 13409\n" ] } ], "source": [ "# 1. After observing the data, it seems that:\n", "# - The gene expression data uses gene symbols directly as identifiers (e.g., A2M, AAAS)\n", "# - The gene annotation data has 'ID' and 'ORF' columns which both contain gene identifiers\n", "\n", "# Since the gene annotation preview data shows symbols like 'SAMD11', 'KLHL17', etc.\n", "# which are standard gene symbols, I'll use 'ID' as both the probe column and the gene column\n", "# for consistent mapping\n", "\n", "# 2. Get a gene mapping dataframe\n", "mapping_data = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='ORF')\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene-level expression\n", "gene_data = apply_gene_mapping(gene_data, mapping_data)\n", "\n", "# Preview the mapped gene data\n", "print(\"Mapped gene data preview (first 5 genes):\")\n", "print(gene_data.index[:5])\n", "print(f\"Total number of genes after mapping: {len(gene_data)}\")\n" ] }, { "cell_type": "markdown", "id": "8ff31fc0", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "8fbe72eb", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:57:35.349862Z", "iopub.status.busy": "2025-03-25T06:57:35.349750Z", "iopub.status.idle": "2025-03-25T06:57:44.799217Z", "shell.execute_reply": "2025-03-25T06:57:44.798822Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original gene count: 13409\n", "Normalized gene count: 13362\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Bladder_Cancer/gene_data/GSE222073.csv\n", "Clinical data structure:\n", "(13, 147)\n", "First few rows of clinical data:\n", " !Sample_geo_accession \\\n", "0 !Sample_characteristics_ch1 \n", "1 !Sample_characteristics_ch1 \n", "2 !Sample_characteristics_ch1 \n", "3 !Sample_characteristics_ch1 \n", "4 !Sample_characteristics_ch1 \n", "\n", " GSM6914278 \\\n", "0 labeling kit: SensationPlus FFPE Amplification... \n", "1 labeling batch: 3 \n", "2 clinical tnm staging: cTxN0M1 \n", "3 chemotherapy type: palliative \n", "4 lundtax rna-subtype: UroC \n", "\n", " GSM6914279 \\\n", "0 labeling kit: SensationPlus FFPE Amplification... \n", "1 labeling batch: 4 \n", "2 clinical tnm staging: cT3N0M0 \n", "3 chemotherapy type: neoadjuvant \n", "4 lundtax rna-subtype: GU \n", "\n", " GSM6914280 \\\n", "0 labeling kit: SensationPlus FFPE Amplification... \n", "1 labeling batch: 4 \n", "2 clinical tnm staging: pT4aN1M0 \n", "3 chemotherapy type: adjuvant \n", "4 lundtax rna-subtype: GU \n", "\n", " GSM6914281 \\\n", "0 labeling kit: SensationPlus FFPE Amplification... \n", "1 labeling batch: 5 \n", "2 clinical tnm staging: cT3N0M0 \n", "3 chemotherapy type: neoadjuvant \n", "4 lundtax rna-subtype: UroB \n", "\n", " GSM6914282 \\\n", "0 labeling kit: SensationPlus FFPE Amplification... \n", "1 labeling batch: 6 \n", "2 clinical tnm staging: cT2N0M0 \n", "3 chemotherapy type: neoadjuvant \n", "4 lundtax rna-subtype: GU \n", "\n", " GSM6914283 \\\n", "0 labeling kit: SensationPlus FFPE Amplification... \n", "1 labeling batch: 6 \n", "2 clinical tnm staging: cT4bN0M0 \n", "3 chemotherapy type: induction \n", "4 lundtax rna-subtype: GU \n", "\n", " GSM6914284 \\\n", "0 labeling kit: SensationPlus FFPE Amplification... \n", "1 labeling batch: 7 \n", "2 clinical tnm staging: cTxN2M1 \n", "3 chemotherapy type: palliative \n", "4 lundtax rna-subtype: UroA \n", "\n", " GSM6914285 \\\n", "0 labeling kit: SensationPlus FFPE Amplification... \n", "1 labeling batch: 8 \n", "2 clinical tnm staging: cT2N0M0 \n", "3 chemotherapy type: neoadjuvant \n", "4 lundtax rna-subtype: UroA \n", "\n", " GSM6914286 ... \\\n", "0 labeling kit: SensationPlus FFPE Amplification... ... \n", "1 labeling batch: 8 ... \n", "2 clinical tnm staging: cTxN0M1 ... \n", "3 chemotherapy type: palliative ... \n", "4 lundtax rna-subtype: GU ... \n", "\n", " GSM6914414 GSM6914415 \\\n", "0 labeling kit: GeneChip WT Pico kit labeling kit: GeneChip WT Pico kit \n", "1 labeling batch: 25 labeling batch: 25 \n", "2 clinical tnm staging: cT3bN0M1 clinical tnm staging: cT4N2M1 \n", "3 chemotherapy type: palliative chemotherapy type: palliative \n", "4 lundtax rna-subtype: Mes lundtax rna-subtype: BASQ \n", "\n", " GSM6914416 GSM6914417 \\\n", "0 labeling kit: GeneChip WT Pico kit labeling kit: GeneChip WT Pico kit \n", "1 labeling batch: 25 labeling batch: 26 \n", "2 clinical tnm staging: cT4aN0M1 clinical tnm staging: cTxN0M1 \n", "3 chemotherapy type: palliative chemotherapy type: palliative \n", "4 lundtax rna-subtype: UroA lundtax rna-subtype: UroA \n", "\n", " GSM6914418 GSM6914419 \\\n", "0 labeling kit: GeneChip WT Pico kit labeling kit: GeneChip WT Pico kit \n", "1 labeling batch: 26 labeling batch: 27 \n", "2 clinical tnm staging: cT3bN0M0 clinical tnm staging: pT3bN1M0 \n", "3 chemotherapy type: neoadjuvant chemotherapy type: adjuvant \n", "4 lundtax rna-subtype: UroB lundtax rna-subtype: GU \n", "\n", " GSM6914420 GSM6914421 \\\n", "0 labeling kit: GeneChip WT Pico kit labeling kit: GeneChip WT Pico kit \n", "1 labeling batch: 27 labeling batch: 27 \n", "2 clinical tnm staging: cTxN0M1 clinical tnm staging: cTxN3M1 \n", "3 chemotherapy type: palliative chemotherapy type: palliative \n", "4 lundtax rna-subtype: BASQ lundtax rna-subtype: UroB \n", "\n", " GSM6914422 GSM6914423 \n", "0 labeling kit: GeneChip WT Pico kit labeling kit: GeneChip WT Pico kit \n", "1 labeling batch: 27 labeling batch: 27 \n", "2 clinical tnm staging: pT2aN1M0 clinical tnm staging: cT3N1M1 \n", "3 chemotherapy type: adjuvant chemotherapy type: palliative \n", "4 lundtax rna-subtype: UroC lundtax rna-subtype: BASQ \n", "\n", "[5 rows x 147 columns]\n", "Clinical data shape after extraction: (1, 146)\n", "First few sample IDs in clinical data:\n", "['GSM6914278', 'GSM6914279', 'GSM6914280', 'GSM6914281', 'GSM6914282']\n", "First few sample IDs in gene data:\n", "['GSM6914278', 'GSM6914279', 'GSM6914280', 'GSM6914281', 'GSM6914282']\n", "Number of common samples between clinical and gene data: 146\n", "Clinical data saved to ../../output/preprocess/Bladder_Cancer/clinical_data/GSE222073.csv\n", "Linked data shape: (146, 13363)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape after handling missing values: (146, 13363)\n", "For the feature 'Bladder_Cancer', the least common label is '1.0' with 53 occurrences. This represents 36.30% of the dataset.\n", "The distribution of the feature 'Bladder_Cancer' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Bladder_Cancer/GSE222073.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "# First, normalize gene symbols using the function from the library\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Original gene count: {len(gene_data)}\")\n", "print(f\"Normalized gene count: {len(normalized_gene_data)}\")\n", "\n", "# Create directory for the gene data file if it doesn't exist\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "\n", "# Save the normalized gene data to a CSV file\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# 2. Load clinical data from the matrix file again to ensure we have the correct sample IDs\n", "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n", "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n", "_, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", "\n", "print(\"Clinical data structure:\")\n", "print(clinical_data.shape)\n", "print(\"First few rows of clinical data:\")\n", "print(clinical_data.head())\n", "\n", "# Extract clinical features with the correct sample IDs\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", "print(f\"Clinical data shape after extraction: {selected_clinical_df.shape}\")\n", "print(\"First few sample IDs in clinical data:\")\n", "print(list(selected_clinical_df.columns)[:5])\n", "print(\"First few sample IDs in gene data:\")\n", "print(list(normalized_gene_data.columns)[:5])\n", "\n", "# Check for column overlap\n", "common_samples = set(selected_clinical_df.columns).intersection(set(normalized_gene_data.columns))\n", "print(f\"Number of common samples between clinical and gene data: {len(common_samples)}\")\n", "\n", "# Save the clinical data for inspection\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", "# Link the clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "\n", "# Check if linking was successful\n", "if len(linked_data) == 0 or trait not in linked_data.columns:\n", " print(\"Linking clinical and genetic data failed - no valid rows or trait column missing\")\n", " \n", " # Check what columns are in the linked data\n", " if len(linked_data.columns) > 0:\n", " print(\"Columns in linked data:\")\n", " print(list(linked_data.columns)[:10]) # Print first 10 columns\n", " \n", " # Set is_usable to False and save cohort info\n", " is_usable = validate_and_save_cohort_info(\n", " is_final=True, \n", " cohort=cohort, \n", " info_path=json_path, \n", " is_gene_available=True, \n", " is_trait_available=True, \n", " is_biased=True, # Consider it biased if linking fails\n", " df=pd.DataFrame({trait: [], 'Gender': []}), \n", " note=\"Data linking failed - unable to match sample IDs between clinical and gene expression data.\"\n", " )\n", " print(\"The dataset was determined to be not usable for analysis.\")\n", "else:\n", " # 3. Handle missing values in the linked data\n", " linked_data = handle_missing_values(linked_data, trait)\n", " \n", " print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n", " \n", " # 4. Determine whether the trait and demographic features are severely biased\n", " is_trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " \n", " # 5. Conduct quality check and save the cohort information.\n", " note = \"Dataset contains gene expression data from bladder cancer samples with molecular subtyping 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=linked_data, \n", " note=note\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", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", " else:\n", " print(\"The dataset was determined to be not usable for analysis due to bias in the trait distribution.\")" ] } ], "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 }