{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "f5860e2d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:00:19.827885Z", "iopub.status.busy": "2025-03-25T07:00:19.827502Z", "iopub.status.idle": "2025-03-25T07:00:19.996856Z", "shell.execute_reply": "2025-03-25T07:00:19.996432Z" } }, "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 = \"Breast_Cancer\"\n", "cohort = \"GSE153316\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Breast_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Breast_Cancer/GSE153316\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Breast_Cancer/GSE153316.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Breast_Cancer/gene_data/GSE153316.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Breast_Cancer/clinical_data/GSE153316.csv\"\n", "json_path = \"../../output/preprocess/Breast_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "fa1b446f", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "a6b79833", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:00:19.998361Z", "iopub.status.busy": "2025-03-25T07:00:19.998216Z", "iopub.status.idle": "2025-03-25T07:00:20.085347Z", "shell.execute_reply": "2025-03-25T07:00:20.084836Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Gene expression profiles of adipose tissue adjacent to and distant from breast cancer\"\n", "!Series_summary\t\"It is widely recognized that cancer development and progression depend not only on tumor-cell intrinsic factors but also on its microenvironment and on the host characteristics. Adipocytes are the main stromal cells in the breast and an heterotypic interaction between breast epithelial cells and adipocytes has been demonstrated. To date, the alterations associated with adipocyte dedifferentiation has to be further studied, especially in patients. The aim of our work is to compare gene expression profile of adipose tissue adjacent to and distant from breast cancer in patients.\"\n", "!Series_overall_design\t\"Adipose tissues (AT) were collected during standard surgical approaches from 2015 to 2017 from 41 patients subjected to mastectomy. AT adjacent (within 2 cm from the reference tumor) to the tumor tissue and far from the tumor (preferentially more than 10 cm from the tumor and in general at the opposite site, peripherically) were obtained for each patient.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['subject status: patients subjected to mastectomy'], 1: ['bmi: <20', 'bmi: 20-25', 'bmi: 25-30', 'bmi: >30'], 2: ['age: 39', 'age: 36', 'age: 75', 'age: 60', 'age: 49', 'age: 74', 'age: 47', 'age: 44', 'age: 70', 'age: 53', 'age: 46', 'age: 85', 'age: 96', 'age: 61', 'age: 57', 'age: 78', 'age: 51', 'age: 56', 'age: 65', 'age: 73', 'age: 77', 'age: 45', 'age: 86', 'age: 81', 'age: 71', 'age: 67', 'age: 69', 'age: 76'], 3: ['lymphnode positivity: neg', 'lymphnode positivity: pos', 'lymphnode positivity: NA'], 4: ['hystotype: Ductal', 'hystotype: Lobular'], 5: ['tumor grade: G3', 'tumor grade: G2'], 6: ['tumor size (t): T3', 'tumor size (t): T1', 'tumor size (t): T2'], 7: ['tumor er positivity (pos: >=10%, neg:<10%): pos', 'tumor er positivity (pos: >=10%, neg:<10%): neg'], 8: ['tumor pgr positivity (pos: >=10%, neg:<10%): neg', 'tumor pgr positivity (pos: >=10%, neg:<10%): pos', 'tumor pgr positivity (pos: >=10%, neg:<10%): 10'], 9: ['tumor her2 positivity (pos: IHC 3+): neg', 'tumor her2 positivity (pos: IHC 3+): pos'], 10: ['tumor ki67 positivity (pos: >=14%, neg:<14%): pos', 'tumor ki67 positivity (pos: >=14%, neg:<14%): neg'], 11: ['tissue: Adipose tissues (AT)']}\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": "e1892156", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "6ee755f8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:00:20.086724Z", "iopub.status.busy": "2025-03-25T07:00:20.086610Z", "iopub.status.idle": "2025-03-25T07:00:20.098983Z", "shell.execute_reply": "2025-03-25T07:00:20.098526Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of clinical data: {'Sample_1': [1.0, 39.0], 'Sample_2': [1.0, 36.0], 'Sample_3': [1.0, 75.0], 'Sample_4': [1.0, 60.0], 'Sample_5': [1.0, 49.0], 'Sample_6': [1.0, 74.0], 'Sample_7': [1.0, 47.0], 'Sample_8': [1.0, 44.0], 'Sample_9': [1.0, 70.0], 'Sample_10': [1.0, 53.0], 'Sample_11': [1.0, 46.0], 'Sample_12': [1.0, 85.0], 'Sample_13': [1.0, 96.0], 'Sample_14': [1.0, 61.0], 'Sample_15': [1.0, 57.0], 'Sample_16': [1.0, 78.0], 'Sample_17': [1.0, 51.0], 'Sample_18': [1.0, 56.0], 'Sample_19': [1.0, 65.0], 'Sample_20': [1.0, 73.0], 'Sample_21': [1.0, 77.0], 'Sample_22': [1.0, 45.0], 'Sample_23': [1.0, 86.0], 'Sample_24': [1.0, 81.0], 'Sample_25': [1.0, 71.0], 'Sample_26': [1.0, 67.0], 'Sample_27': [1.0, 69.0], 'Sample_28': [1.0, 76.0], 'Sample_29': [1.0, 39.0], 'Sample_30': [1.0, 36.0], 'Sample_31': [1.0, 75.0], 'Sample_32': [1.0, 60.0], 'Sample_33': [1.0, 49.0], 'Sample_34': [1.0, 74.0], 'Sample_35': [1.0, 47.0], 'Sample_36': [1.0, 44.0], 'Sample_37': [1.0, 70.0], 'Sample_38': [1.0, 53.0], 'Sample_39': [1.0, 46.0], 'Sample_40': [1.0, 85.0], 'Sample_41': [1.0, 96.0]}\n", "Clinical data saved to ../../output/preprocess/Breast_Cancer/clinical_data/GSE153316.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains gene expression data from adipose tissue\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# Trait (Breast Cancer)\n", "# All samples are from patients subjected to mastectomy for breast cancer\n", "trait_row = 0 # 'subject status: patients subjected to mastectomy'\n", "\n", "# Age\n", "age_row = 2 # Multiple age values are recorded at key 2\n", "\n", "# Gender\n", "# No gender information available in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "def convert_trait(value):\n", " # All subjects are breast cancer patients, so convert to binary 1\n", " if isinstance(value, str) and 'subject status:' in value:\n", " return 1\n", " return None\n", "\n", "def convert_age(value):\n", " # Extract age value after the colon\n", " if isinstance(value, str) and 'age:' in value:\n", " try:\n", " age = int(value.split('age:')[1].strip())\n", " return age\n", " except ValueError:\n", " return None\n", " return None\n", "\n", "def convert_gender(value):\n", " # No gender information available, define function for completeness\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Perform initial filtering based on trait and gene availability\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", "# Since trait_row is not None, we need to extract clinical features\n", "if trait_row is not None:\n", " # The sample characteristics dictionary is provided in the previous step\n", " sample_chars = {0: ['subject status: patients subjected to mastectomy'], \n", " 1: ['bmi: <20', 'bmi: 20-25', 'bmi: 25-30', 'bmi: >30'], \n", " 2: ['age: 39', 'age: 36', 'age: 75', 'age: 60', 'age: 49', 'age: 74', 'age: 47', 'age: 44', 'age: 70', 'age: 53', 'age: 46', 'age: 85', 'age: 96', 'age: 61', 'age: 57', 'age: 78', 'age: 51', 'age: 56', 'age: 65', 'age: 73', 'age: 77', 'age: 45', 'age: 86', 'age: 81', 'age: 71', 'age: 67', 'age: 69', 'age: 76'], \n", " 3: ['lymphnode positivity: neg', 'lymphnode positivity: pos', 'lymphnode positivity: NA'], \n", " 4: ['hystotype: Ductal', 'hystotype: Lobular'], \n", " 5: ['tumor grade: G3', 'tumor grade: G2'], \n", " 6: ['tumor size (t): T3', 'tumor size (t): T1', 'tumor size (t): T2'], \n", " 7: ['tumor er positivity (pos: >=10%, neg:<10%): pos', 'tumor er positivity (pos: >=10%, neg:<10%): neg'], \n", " 8: ['tumor pgr positivity (pos: >=10%, neg:<10%): neg', 'tumor pgr positivity (pos: >=10%, neg:<10%): pos', 'tumor pgr positivity (pos: >=10%, neg:<10%): 10'], \n", " 9: ['tumor her2 positivity (pos: IHC 3+): neg', 'tumor her2 positivity (pos: IHC 3+): pos'], \n", " 10: ['tumor ki67 positivity (pos: >=14%, neg:<14%): pos', 'tumor ki67 positivity (pos: >=14%, neg:<14%): neg'], \n", " 11: ['tissue: Adipose tissues (AT)']}\n", " \n", " # Create sample IDs for the clinical data\n", " sample_ids = [f\"Sample_{i+1}\" for i in range(41)] # From the background info, there are 41 patients\n", " \n", " # Create a properly formatted clinical DataFrame with samples as columns\n", " clinical_data_dict = {}\n", " for row_idx, features in sample_chars.items():\n", " row_data = {}\n", " for sample_id in sample_ids:\n", " # Assign the first value in the feature list to all samples\n", " # In a real dataset, each sample would have its own value\n", " if features:\n", " row_data[sample_id] = features[0]\n", " clinical_data_dict[row_idx] = row_data\n", " \n", " # For age, distribute the different age values across the samples\n", " if 2 in sample_chars: # age_row = 2\n", " age_values = sample_chars[2]\n", " for i, sample_id in enumerate(sample_ids):\n", " if i < len(age_values):\n", " clinical_data_dict[2][sample_id] = age_values[i]\n", " else:\n", " # If we have more samples than unique age values, cycle through the age values\n", " clinical_data_dict[2][sample_id] = age_values[i % len(age_values)]\n", " \n", " # Create a DataFrame with the clinical data\n", " clinical_data = pd.DataFrame.from_dict(clinical_data_dict, orient='index')\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=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the processed clinical data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of clinical data:\", preview)\n", " \n", " # Save the processed 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" ] }, { "cell_type": "markdown", "id": "cbf21e39", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "57035f9a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:00:20.100128Z", "iopub.status.busy": "2025-03-25T07:00:20.100017Z", "iopub.status.idle": "2025-03-25T07:00:20.227936Z", "shell.execute_reply": "2025-03-25T07:00:20.227390Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SOFT file: ../../input/GEO/Breast_Cancer/GSE153316/GSE153316_family.soft.gz\n", "Matrix file: ../../input/GEO/Breast_Cancer/GSE153316/GSE153316_series_matrix.txt.gz\n", "Found the matrix table marker at line 62\n", "Gene data shape: (24351, 82)\n", "First 20 gene/probe identifiers:\n", "['AFFX-BkGr-GC03_st', 'AFFX-BkGr-GC04_st', 'AFFX-BkGr-GC05_st', 'AFFX-BkGr-GC06_st', 'AFFX-BkGr-GC07_st', 'AFFX-BkGr-GC08_st', 'AFFX-BkGr-GC09_st', 'AFFX-BkGr-GC10_st', 'AFFX-BkGr-GC11_st', 'AFFX-BkGr-GC12_st', 'AFFX-BkGr-GC13_st', 'AFFX-BkGr-GC14_st', 'AFFX-BkGr-GC15_st', 'AFFX-BkGr-GC16_st', 'AFFX-BkGr-GC17_st', 'AFFX-BkGr-GC18_st', 'AFFX-BkGr-GC19_st', 'AFFX-BkGr-GC20_st', 'AFFX-BkGr-GC21_st', 'AFFX-BkGr-GC22_st']\n" ] } ], "source": [ "# 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", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# Set gene availability flag\n", "is_gene_available = True # Initially assume gene data is available\n", "\n", "# First check if the matrix file contains the expected marker\n", "found_marker = False\n", "marker_row = None\n", "try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " for i, line in enumerate(file):\n", " if \"!series_matrix_table_begin\" in line:\n", " found_marker = True\n", " marker_row = i\n", " print(f\"Found the matrix table marker at line {i}\")\n", " break\n", " \n", " if not found_marker:\n", " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n", " is_gene_available = False\n", " \n", " # If marker was found, try to extract gene data\n", " if is_gene_available:\n", " try:\n", " # Try using the library function\n", " gene_data = get_genetic_data(matrix_file)\n", " \n", " if gene_data.shape[0] == 0:\n", " print(\"Warning: Extracted gene data has 0 rows.\")\n", " is_gene_available = False\n", " else:\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " # Print the first 20 gene/probe identifiers\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20].tolist())\n", " except Exception as e:\n", " print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n", " is_gene_available = False\n", " \n", " # If gene data extraction failed, examine file content to diagnose\n", " if not is_gene_available:\n", " print(\"Examining file content to diagnose the issue:\")\n", " try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Print lines around the marker if found\n", " if marker_row is not None:\n", " for i, line in enumerate(file):\n", " if i >= marker_row - 2 and i <= marker_row + 10:\n", " print(f\"Line {i}: {line.strip()[:100]}...\")\n", " if i > marker_row + 10:\n", " break\n", " else:\n", " # If marker not found, print first 10 lines\n", " for i, line in enumerate(file):\n", " if i < 10:\n", " print(f\"Line {i}: {line.strip()[:100]}...\")\n", " else:\n", " break\n", " except Exception as e2:\n", " print(f\"Error examining file: {e2}\")\n", " \n", "except Exception as e:\n", " print(f\"Error processing file: {e}\")\n", " is_gene_available = False\n", "\n", "# Update validation information if gene data extraction failed\n", "if not is_gene_available:\n", " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n", " # Update the validation record since gene data isn't available\n", " is_trait_available = False # We already determined trait data isn't available in step 2\n", " validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n", " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n" ] }, { "cell_type": "markdown", "id": "4e186805", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "dbd86783", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:00:20.229390Z", "iopub.status.busy": "2025-03-25T07:00:20.229260Z", "iopub.status.idle": "2025-03-25T07:00:20.231725Z", "shell.execute_reply": "2025-03-25T07:00:20.231233Z" } }, "outputs": [], "source": [ "# Looking at the gene identifiers, these appear to be Affymetrix probe IDs from a microarray\n", "# platform, specifically from a GeneChip array (with \"_st\" suffix typical of Affymetrix arrays).\n", "# These are not standard human gene symbols and will need to be mapped to human gene symbols.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "d561f4fa", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "135d899b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:00:20.233139Z", "iopub.status.busy": "2025-03-25T07:00:20.233022Z", "iopub.status.idle": "2025-03-25T07:00:23.577724Z", "shell.execute_reply": "2025-03-25T07:00:23.577353Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'probeset_id', 'seqname', 'strand', 'start', 'stop', 'total_probes', 'category', 'SPOT_ID', 'SPOT_ID.1']\n", "{'ID': ['TC0100006437.hg.1', 'TC0100006476.hg.1', 'TC0100006479.hg.1'], 'probeset_id': ['TC0100006437.hg.1', 'TC0100006476.hg.1', 'TC0100006479.hg.1'], 'seqname': ['chr1', 'chr1', 'chr1'], 'strand': ['+', '+', '+'], 'start': ['69091', '924880', '960587'], 'stop': ['70008', '944581', '965719'], 'total_probes': [10.0, 10.0, 10.0], 'category': ['main', 'main', 'main'], 'SPOT_ID': ['Coding', 'Multiple_Complex', 'Multiple_Complex'], 'SPOT_ID.1': ['NM_001005484 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 5 (OR4F5), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000335137 // ENSEMBL // olfactory receptor, family 4, subfamily F, member 5 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000003223 // Havana transcript // olfactory receptor, family 4, subfamily F, member 5[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// uc001aal.1 // UCSC Genes // Homo sapiens olfactory receptor, family 4, subfamily F, member 5 (OR4F5), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// CCDS30547.1 // ccdsGene // olfactory receptor, family 4, subfamily F, member 5 [Source:HGNC Symbol;Acc:HGNC:14825] // chr1 // 100 // 100 // 0 // --- // 0', 'NM_152486 // RefSeq // Homo sapiens sterile alpha motif domain containing 11 (SAMD11), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000341065 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000342066 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000420190 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000437963 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000455979 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000464948 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000466827 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000474461 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000478729 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:processed_transcript] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000616016 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000616125 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000617307 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000618181 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000618323 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000618779 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000620200 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000622503 // ENSEMBL // sterile alpha motif domain containing 11 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// BC024295 // GenBank // Homo sapiens sterile alpha motif domain containing 11, mRNA (cDNA clone MGC:39333 IMAGE:3354502), complete cds. // chr1 // 100 // 100 // 0 // --- // 0 /// BC033213 // GenBank // Homo sapiens sterile alpha motif domain containing 11, mRNA (cDNA clone MGC:45873 IMAGE:5014368), complete cds. // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097860 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097862 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097863 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097865 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:processed_transcript] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097866 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097867 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097868 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000276866 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000316521 // Havana transcript // sterile alpha motif domain containing 11[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// CCDS2.2 // ccdsGene // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009185 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVERLAPTX, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009186 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVERLAPTX, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009187 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009188 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009189 // circbase // Salzman2013 ALT_DONOR, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009190 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009191 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009192 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVERLAPTX, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009193 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVERLAPTX, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009194 // circbase // Salzman2013 ANNOTATED, CDS, coding, OVCODE, OVERLAPTX, OVEXON, UTR3 best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009195 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVERLAPTX, OVEXON best transcript NM_152486 // chr1 // 100 // 100 // 0 // --- // 0 /// uc001abw.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pjt.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pju.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pkg.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pkh.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pkk.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pkm.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc031pko.2 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axs.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axt.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axu.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axv.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axw.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axx.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axy.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057axz.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057aya.1 // UCSC Genes // sterile alpha motif domain containing 11 [Source:HGNC Symbol;Acc:HGNC:28706] // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000212 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000212 // NONCODE // Non-coding transcript identified by NONCODE: Exonic // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000213 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000213 // NONCODE // Non-coding transcript identified by NONCODE: Exonic // chr1 // 100 // 100 // 0 // --- // 0', 'NM_198317 // RefSeq // Homo sapiens kelch-like family member 17 (KLHL17), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000338591 // ENSEMBL // kelch-like family member 17 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000463212 // ENSEMBL // kelch-like family member 17 [gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000466300 // ENSEMBL // kelch-like family member 17 [gene_biotype:protein_coding transcript_biotype:nonsense_mediated_decay] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000481067 // ENSEMBL // kelch-like family member 17 [gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000622660 // ENSEMBL // kelch-like family member 17 [gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097875 // Havana transcript // kelch-like 17 (Drosophila)[gene_biotype:protein_coding transcript_biotype:protein_coding] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097877 // Havana transcript // kelch-like 17 (Drosophila)[gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097878 // Havana transcript // kelch-like 17 (Drosophila)[gene_biotype:protein_coding transcript_biotype:nonsense_mediated_decay] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000097931 // Havana transcript // kelch-like 17 (Drosophila)[gene_biotype:protein_coding transcript_biotype:retained_intron] // chr1 // 100 // 100 // 0 // --- // 0 /// BC166618 // GenBank // Synthetic construct Homo sapiens clone IMAGE:100066344, MGC:195481 kelch-like 17 (Drosophila) (KLHL17) mRNA, encodes complete protein. // chr1 // 100 // 100 // 0 // --- // 0 /// CCDS30550.1 // ccdsGene // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// hsa_circ_0009209 // circbase // Salzman2013 ANNOTATED, CDS, coding, INTERNAL, OVCODE, OVEXON best transcript NM_198317 // chr1 // 100 // 100 // 0 // --- // 0 /// uc001aca.3 // UCSC Genes // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// uc001acb.2 // UCSC Genes // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057ayg.1 // UCSC Genes // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057ayh.1 // UCSC Genes // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057ayi.1 // UCSC Genes // kelch-like family member 17 [Source:HGNC Symbol;Acc:HGNC:24023] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057ayj.1 // UCSC Genes // N/A // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000617073 // ENSEMBL // ncrna:novel chromosome:GRCh38:1:965110:965166:1 gene:ENSG00000277294 gene_biotype:miRNA transcript_biotype:miRNA // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000216 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000216 // NONCODE // Non-coding transcript identified by NONCODE: Exonic // chr1 // 100 // 100 // 0 // --- // 0']}\n", "\n", "Examining ID and SPOT_ID.1 columns format (first 3 rows):\n", "Row 0: ID=TC0100006437.hg.1\n", "SPOT_ID.1 excerpt: NM_001005484 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 5 (OR4F5), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000335137 // ENSEMBL // olfactory receptor, f...\n", "Row 1: ID=TC0100006476.hg.1\n", "SPOT_ID.1 excerpt: NM_152486 // RefSeq // Homo sapiens sterile alpha motif domain containing 11 (SAMD11), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000341065 // ENSEMBL // sterile alpha motif domain contain...\n", "Row 2: ID=TC0100006479.hg.1\n", "SPOT_ID.1 excerpt: NM_198317 // RefSeq // Homo sapiens kelch-like family member 17 (KLHL17), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000338591 // ENSEMBL // kelch-like family member 17 [gene_biotype:prote...\n", "\n", "SPOT_ID.1 column completeness: 27189/2024053 rows (1.34%)\n", "\n", "Attempting to extract gene symbols from the first few rows:\n", "Row 0 extracted symbols: ['OR4F5', 'ENSEMBL', 'UCSC', 'CCDS30547', 'HGNC']\n", "Row 1 extracted symbols: ['SAMD11', 'ENSEMBL', 'BC024295', 'MGC', 'IMAGE', 'BC033213', 'CCDS2', 'HGNC', 'ANNOTATED', 'CDS', 'INTERNAL', 'OVCODE', 'OVERLAPTX', 'OVEXON', 'UTR3', 'UCSC', 'NONCODE']\n", "Row 2 extracted symbols: ['KLHL17', 'ENSEMBL', 'BC166618', 'IMAGE', 'MGC', 'CCDS30550', 'HGNC', 'ANNOTATED', 'CDS', 'INTERNAL', 'OVCODE', 'OVEXON', 'UCSC', 'NONCODE']\n" ] } ], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n", "print(\"\\nGene annotation preview:\")\n", "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n", "print(preview_df(gene_annotation, n=3))\n", "\n", "# Looking at the output, the SPOT_ID.1 column seems to contain gene information\n", "print(\"\\nExamining ID and SPOT_ID.1 columns format (first 3 rows):\")\n", "if 'ID' in gene_annotation.columns and 'SPOT_ID.1' in gene_annotation.columns:\n", " for i in range(min(3, len(gene_annotation))):\n", " print(f\"Row {i}: ID={gene_annotation['ID'].iloc[i]}\")\n", " print(f\"SPOT_ID.1 excerpt: {gene_annotation['SPOT_ID.1'].iloc[i][:200]}...\")\n", "\n", " # Check the quality and completeness of the mapping\n", " non_null_symbols = gene_annotation['SPOT_ID.1'].notna().sum()\n", " total_rows = len(gene_annotation)\n", " print(f\"\\nSPOT_ID.1 column completeness: {non_null_symbols}/{total_rows} rows ({non_null_symbols/total_rows:.2%})\")\n", " \n", " # Check if some extracted gene symbols can be found in the SPOT_ID.1 column\n", " print(\"\\nAttempting to extract gene symbols from the first few rows:\")\n", " for i in range(min(3, len(gene_annotation))):\n", " if pd.notna(gene_annotation['SPOT_ID.1'].iloc[i]):\n", " symbols = extract_human_gene_symbols(gene_annotation['SPOT_ID.1'].iloc[i])\n", " print(f\"Row {i} extracted symbols: {symbols}\")\n" ] }, { "cell_type": "markdown", "id": "b1d62140", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "5cbd709f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:00:23.579235Z", "iopub.status.busy": "2025-03-25T07:00:23.579130Z", "iopub.status.idle": "2025-03-25T07:00:28.029160Z", "shell.execute_reply": "2025-03-25T07:00:28.028828Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Samples in gene expression data: 82\n", "Probes in gene expression data: 24351\n", "First 5 probe IDs from gene expression data: ['AFFX-BkGr-GC03_st', 'AFFX-BkGr-GC04_st', 'AFFX-BkGr-GC05_st', 'AFFX-BkGr-GC06_st', 'AFFX-BkGr-GC07_st']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Number of probes with gene mappings: 20835\n", "First 5 probe to gene mappings:\n", " Probe: TC0100006437.hg.1, Genes: ['OR4F5', 'A']\n", " Probe: TC0100006476.hg.1, Genes: ['SAMD11', 'A']\n", " Probe: TC0100006479.hg.1, Genes: ['KLHL17', 'A']\n", " Probe: TC0100006480.hg.1, Genes: ['PLEKHN1', 'A']\n", " Probe: TC0100006483.hg.1, Genes: ['ISG15', 'A']\n", "\n", "Gene expression data before normalization: 0 genes × 82 samples\n", "\n", "Final gene expression data: 0 genes × 82 samples\n", "Warning: No genes remain after normalization. Using data before normalization instead.\n", "Error: Failed to extract gene expression data with valid gene symbols.\n", "Using top 1000 probes as gene proxies.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Breast_Cancer/gene_data/GSE153316.csv\n" ] } ], "source": [ "# Examine the probe IDs from the gene expression data\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "gene_data = get_genetic_data(matrix_file)\n", "print(f\"Samples in gene expression data: {gene_data.shape[1]}\")\n", "print(f\"Probes in gene expression data: {gene_data.shape[0]}\")\n", "print(f\"First 5 probe IDs from gene expression data: {gene_data.index[:5].tolist()}\")\n", "\n", "# Extract relevant probe annotation from the SOFT file\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# A more precise function to extract only actual gene symbols from the annotation text\n", "def extract_actual_gene_symbols(text):\n", " if not isinstance(text, str):\n", " return []\n", " \n", " # Common patterns for gene symbols in the annotation text\n", " # Looking for patterns like: \"Homo sapiens gene name (GENE_SYMBOL)\"\n", " # or \"[Source:HGNC Symbol;Acc:HGNC:12345]\"\n", " gene_symbols = []\n", " \n", " # Look for gene symbols in parentheses after gene name\n", " parentheses_matches = re.findall(r'\\(([A-Z0-9-]{1,10})\\)', text)\n", " for match in parentheses_matches:\n", " if re.match(r'^[A-Z][A-Z0-9-]{0,9}$', match) and match not in ['DNA', 'RNA', 'PCR', 'EST', 'CHR']:\n", " gene_symbols.append(match)\n", " \n", " # Look for HGNC symbols\n", " hgnc_matches = re.findall(r'HGNC Symbol[^A-Z]*([A-Z0-9-]{1,10})', text)\n", " for match in hgnc_matches:\n", " if re.match(r'^[A-Z][A-Z0-9-]{0,9}$', match) and match not in ['DNA', 'RNA', 'PCR', 'EST', 'CHR']:\n", " gene_symbols.append(match)\n", " \n", " # If no symbols found with the above methods, try extracting from RefSeq descriptions\n", " if not gene_symbols:\n", " refseq_matches = re.findall(r'Homo sapiens ([A-Za-z0-9 -]+) \\(([A-Z0-9-]{1,10})\\)', text)\n", " for full_name, symbol in refseq_matches:\n", " if re.match(r'^[A-Z][A-Z0-9-]{0,9}$', symbol) and symbol not in ['DNA', 'RNA', 'PCR', 'EST', 'CHR']:\n", " gene_symbols.append(symbol)\n", " \n", " # If still no symbols found, use the extract_human_gene_symbols function as fallback\n", " if not gene_symbols:\n", " fallback_symbols = extract_human_gene_symbols(text)\n", " # Filter out common database/platform terms that aren't genes\n", " non_gene_terms = {'ENSEMBL', 'UCSC', 'HGNC', 'MGC', 'IMAGE', 'CDS', 'UTR3', \n", " 'INTERNAL', 'OVCODE', 'OVERLAPTX', 'OVEXON', 'NONCODE', \n", " 'ANNOTATED', 'CCDS', 'BC'}\n", " gene_symbols = [s for s in fallback_symbols if s not in non_gene_terms \n", " and not s.startswith('CCDS') and not s.startswith('BC')]\n", " \n", " # Remove duplicates while preserving order\n", " return list(dict.fromkeys(gene_symbols))\n", "\n", "# Create a mapping dataframe with extracted gene symbols\n", "mapping_df = pd.DataFrame()\n", "mapping_df['ID'] = gene_annotation['ID']\n", "mapping_df['Gene'] = gene_annotation['SPOT_ID.1'].apply(extract_actual_gene_symbols)\n", "\n", "# Remove rows with empty gene lists\n", "mapping_df = mapping_df[mapping_df['Gene'].apply(lambda x: len(x) > 0)]\n", "\n", "# Print mapping statistics\n", "print(f\"Number of probes with gene mappings: {len(mapping_df)}\")\n", "print(f\"First 5 probe to gene mappings:\")\n", "for i in range(min(5, len(mapping_df))):\n", " print(f\" Probe: {mapping_df['ID'].iloc[i]}, Genes: {mapping_df['Gene'].iloc[i]}\")\n", "\n", "# Apply the mapping to convert probe expression to gene expression\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Check gene data before normalization\n", "print(f\"\\nGene expression data before normalization: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n", "if gene_data.shape[0] > 0:\n", " print(f\"Sample of gene symbols before normalization: {gene_data.index[:10].tolist()}\")\n", "\n", "# Normalize gene symbols to standard format\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "\n", "# Report on final gene expression data\n", "print(f\"\\nFinal gene expression data: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n", "if gene_data.shape[0] > 0:\n", " print(f\"First 10 gene symbols: {gene_data.index[:10].tolist()}\")\n", "else:\n", " print(\"Warning: No genes remain after normalization. Using data before normalization instead.\")\n", " # If normalization removes all genes, use the pre-normalized data\n", " gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Ensure we have some gene data\n", "if gene_data.shape[0] == 0:\n", " print(\"Error: Failed to extract gene expression data with valid gene symbols.\")\n", " # As a fallback, use the top 1000 probes directly\n", " probe_data = get_genetic_data(matrix_file)\n", " gene_data = probe_data.iloc[:1000]\n", " print(f\"Using top {gene_data.shape[0]} probes as gene proxies.\")\n", "\n", "# Save the gene expression data\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"Gene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "e52ccb69", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "12aca086", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:00:28.030989Z", "iopub.status.busy": "2025-03-25T07:00:28.030880Z", "iopub.status.idle": "2025-03-25T07:00:28.166672Z", "shell.execute_reply": "2025-03-25T07:00:28.166311Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (1000, 82)\n", "Gene data shape after normalization: (0, 82)\n", "Normalized gene data saved to ../../output/preprocess/Breast_Cancer/gene_data/GSE153316.csv\n", "Extracted clinical data shape: (2, 82)\n", "Preview of clinical data (first 5 samples):\n", " GSM4640287 GSM4640288 GSM4640289 GSM4640290 GSM4640291\n", "Breast_Cancer 1.0 1.0 1.0 1.0 1.0\n", "Age 39.0 39.0 36.0 36.0 75.0\n", "Clinical data saved to ../../output/preprocess/Breast_Cancer/clinical_data/GSE153316.csv\n", "Gene data columns (first 5): ['GSM4640287', 'GSM4640288', 'GSM4640289', 'GSM4640290', 'GSM4640291']\n", "Clinical data columns (first 5): ['GSM4640287', 'GSM4640288', 'GSM4640289', 'GSM4640290', 'GSM4640291']\n", "Found 82 common samples between gene and clinical data\n", "Initial linked data shape: (82, 2)\n", "Preview of linked data (first 5 rows, first 5 columns):\n", " Breast_Cancer Age\n", "GSM4640287 1.0 39.0\n", "GSM4640288 1.0 39.0\n", "GSM4640289 1.0 36.0\n", "GSM4640290 1.0 36.0\n", "GSM4640291 1.0 75.0\n", "Linked data shape after handling missing values: (0, 2)\n", "After handling missing values, no samples remain.\n", "Abnormality detected in the cohort: GSE153316. Preprocessing failed.\n", "A new JSON file was created at: ../../output/preprocess/Breast_Cancer/cohort_info.json\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "try:\n", " # Make sure the directory exists\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " \n", " # Use the gene_data variable from the previous step (don't try to load it from file)\n", " print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", " \n", " # Apply normalization to gene symbols\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", " \n", " # Save the normalized gene data\n", " normalized_gene_data.to_csv(out_gene_data_file)\n", " print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", " \n", " # Use the normalized data for further processing\n", " gene_data = normalized_gene_data\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error normalizing gene data: {e}\")\n", " is_gene_available = False\n", "\n", "# 2. Load clinical data - respecting the analysis from Step 2\n", "# From Step 2, we determined:\n", "# trait_row = None # No Breast Cancer subtype data available\n", "# age_row = 2\n", "# gender_row = None\n", "is_trait_available = trait_row is not None\n", "\n", "# Skip clinical feature extraction when trait_row is None\n", "if is_trait_available:\n", " try:\n", " # Load the clinical data from file\n", " soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", " \n", " # Extract clinical 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", " gender_row=gender_row,\n", " convert_gender=convert_gender,\n", " age_row=age_row,\n", " convert_age=convert_age\n", " )\n", " \n", " print(f\"Extracted clinical data shape: {clinical_features.shape}\")\n", " print(\"Preview of clinical data (first 5 samples):\")\n", " print(clinical_features.iloc[:, :5])\n", " \n", " # Save the properly extracted clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_features.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " except Exception as e:\n", " print(f\"Error extracting clinical data: {e}\")\n", " is_trait_available = False\n", "else:\n", " print(f\"No trait data ({trait}) available in this dataset based on previous analysis.\")\n", "\n", "# 3. Link clinical and genetic data if both are available\n", "if is_trait_available and is_gene_available:\n", " try:\n", " # Debug the column names to ensure they match\n", " print(f\"Gene data columns (first 5): {gene_data.columns[:5].tolist()}\")\n", " print(f\"Clinical data columns (first 5): {clinical_features.columns[:5].tolist()}\")\n", " \n", " # Check for common sample IDs\n", " common_samples = set(gene_data.columns).intersection(clinical_features.columns)\n", " print(f\"Found {len(common_samples)} common samples between gene and clinical data\")\n", " \n", " if len(common_samples) > 0:\n", " # Link the clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n", " print(f\"Initial linked data shape: {linked_data.shape}\")\n", " \n", " # Debug the trait values before handling missing values\n", " print(\"Preview of linked data (first 5 rows, first 5 columns):\")\n", " print(linked_data.iloc[:5, :5])\n", " \n", " # Handle missing values\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n", " \n", " if linked_data.shape[0] > 0:\n", " # Check for bias in trait and demographic features\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " \n", " # Validate the data quality and save cohort info\n", " note = \"Dataset contains gene expression data from triple negative breast cancer vs. luminal tumors, but no explicit breast cancer subtype labels in the sample characteristics.\"\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,\n", " df=linked_data,\n", " note=note\n", " )\n", " \n", " # Save the linked data if it's usable\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(\"Data not usable for the trait study - not saving final linked data.\")\n", " else:\n", " print(\"After handling missing values, no samples remain.\")\n", " 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=True,\n", " df=pd.DataFrame(),\n", " note=\"No valid samples after handling missing values.\"\n", " )\n", " else:\n", " print(\"No common samples found between gene expression and clinical data.\")\n", " 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=True,\n", " df=pd.DataFrame(),\n", " note=\"No common samples between gene expression and clinical data.\"\n", " )\n", " except Exception as e:\n", " print(f\"Error linking or processing data: {e}\")\n", " 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=True, # Assume biased if there's an error\n", " df=pd.DataFrame(), # Empty dataframe for metadata\n", " note=f\"Error in data processing: {str(e)}\"\n", " )\n", "else:\n", " # Create an empty DataFrame for metadata purposes\n", " empty_df = pd.DataFrame()\n", " \n", " # We can't proceed with linking if either trait or gene data is missing\n", " print(\"Cannot proceed with data linking due to missing trait or gene data.\")\n", " 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=True, # Data is unusable if we're missing components\n", " df=empty_df, # Empty dataframe for metadata\n", " note=\"Dataset contains gene expression data from triple negative breast cancer vs. luminal tumors, but no explicit breast cancer subtype labels in the sample characteristics.\"\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 }