{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "6c9343c4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:02:32.698686Z", "iopub.status.busy": "2025-03-25T07:02:32.698539Z", "iopub.status.idle": "2025-03-25T07:02:32.859519Z", "shell.execute_reply": "2025-03-25T07:02:32.859169Z" } }, "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 = \"GSE270721\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Breast_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Breast_Cancer/GSE270721\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Breast_Cancer/GSE270721.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Breast_Cancer/gene_data/GSE270721.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Breast_Cancer/clinical_data/GSE270721.csv\"\n", "json_path = \"../../output/preprocess/Breast_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "2042a430", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "ce8df06b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:02:32.860953Z", "iopub.status.busy": "2025-03-25T07:02:32.860818Z", "iopub.status.idle": "2025-03-25T07:02:32.971798Z", "shell.execute_reply": "2025-03-25T07:02:32.971480Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"LncRNAs expressed in triple negative breast cancer of Mexican patients\"\n", "!Series_summary\t\"We provide a detailed analysis of the expression of lncRNAs in TNBC versus Luminal tumors of breast cancer patients\"\n", "!Series_overall_design\t\"We employed HTA 2.0 microarrays to analyze the transcriptome of TNBC and Luminal tumors.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: Formalin-fixed paraffin-embedded tissue sections'], 1: ['population: Mexican Patient'], 2: ['age: 78.00', 'age: 74.00', 'age: 48.00', 'age: not available', 'age: 49.00', 'age: 50.00', 'age: 40.00', 'age: 55.00', 'age: 70.00', 'age: 63.00', 'age: 42.00', 'age: 64.00', 'age: 38.00', 'age: 82.00', 'age: 45.00', 'age: 36.00', 'age: 44.00', 'age: 65.00', 'age: 66.00', 'age: 73.00']}\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": "f438e0f7", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "a707fc90", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:02:32.972895Z", "iopub.status.busy": "2025-03-25T07:02:32.972792Z", "iopub.status.idle": "2025-03-25T07:02:32.978267Z", "shell.execute_reply": "2025-03-25T07:02:32.977962Z" } }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 1. Gene Expression Data Availability\n", "# From the Series_title and Series_summary, this appears to be a microarray study of lncRNA expressions\n", "# in breast cancer. HTA 2.0 microarrays were used which should contain gene expression data.\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "# For trait: There's no direct mention of breast cancer subtypes in the sample characteristics\n", "# but the background info mentions TNBC vs Luminal tumors, suggesting trait data should be available somewhere else\n", "trait_row = None # Not available in the sample characteristics dictionary\n", "\n", "# For age: We can see age data in key 2\n", "age_row = 2\n", "\n", "# For gender: No gender information in sample characteristics, but likely all female as it's breast cancer\n", "gender_row = None # Not available\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " # Not used since trait_row is None\n", " return None\n", "\n", "def convert_age(value):\n", " try:\n", " # Extract value after colon and strip whitespace\n", " if ':' in value:\n", " age_str = value.split(':', 1)[1].strip()\n", " if age_str.lower() == 'not available':\n", " return None\n", " # Convert to float (continuous variable)\n", " return float(age_str)\n", " return None\n", " except:\n", " return None\n", "\n", "def convert_gender(value):\n", " # Not used since gender_row is None\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Trait data is not available in sample characteristics, so we set is_trait_available to False\n", "is_trait_available = False if trait_row is None else True\n", "\n", "# Initial validation of dataset 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", "# We skip this step since trait_row is None (clinical trait data not available in the sample characteristics)\n" ] }, { "cell_type": "markdown", "id": "b0d90d2f", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "8bf24a60", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:02:32.979325Z", "iopub.status.busy": "2025-03-25T07:02:32.979225Z", "iopub.status.idle": "2025-03-25T07:02:33.099562Z", "shell.execute_reply": "2025-03-25T07:02:33.099168Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SOFT file: ../../input/GEO/Breast_Cancer/GSE270721/GSE270721_family.soft.gz\n", "Matrix file: ../../input/GEO/Breast_Cancer/GSE270721/GSE270721_series_matrix.txt.gz\n", "Found the matrix table marker in the file.\n", "Gene data shape: (67528, 30)\n", "First 20 gene/probe identifiers:\n", "['TC01000001.hg.1', 'TC01000002.hg.1', 'TC01000003.hg.1', 'TC01000004.hg.1', 'TC01000005.hg.1', 'TC01000006.hg.1', 'TC01000007.hg.1', 'TC01000008.hg.1', 'TC01000009.hg.1', 'TC01000010.hg.1', 'TC01000011.hg.1', 'TC01000012.hg.1', 'TC01000013.hg.1', 'TC01000014.hg.1', 'TC01000015.hg.1', 'TC01000016.hg.1', 'TC01000017.hg.1', 'TC01000018.hg.1', 'TC01000019.hg.1', 'TC01000020.hg.1']\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", "try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " for line in file:\n", " if \"!series_matrix_table_begin\" in line:\n", " found_marker = True\n", " break\n", " \n", " if found_marker:\n", " print(\"Found the matrix table marker in the file.\")\n", " else:\n", " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n", " \n", " # Try to extract gene data from the matrix file\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", " \n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n", " is_gene_available = False\n", " \n", " # Try to diagnose the file format\n", " print(\"Examining file content to diagnose the issue:\")\n", " try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " for i, line in enumerate(file):\n", " if i < 10: # Print first 10 lines to diagnose\n", " print(f\"Line {i}: {line.strip()[:100]}...\") # Print first 100 chars of each line\n", " else:\n", " break\n", " except Exception as e2:\n", " print(f\"Error examining file: {e2}\")\n", "\n", "if not is_gene_available:\n", " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n" ] }, { "cell_type": "markdown", "id": "89361f17", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "661afcba", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:02:33.101070Z", "iopub.status.busy": "2025-03-25T07:02:33.100956Z", "iopub.status.idle": "2025-03-25T07:02:33.102919Z", "shell.execute_reply": "2025-03-25T07:02:33.102626Z" } }, "outputs": [], "source": [ "# The identifiers like 'TC01000001.hg.1' are not standard human gene symbols\n", "# These appear to be Affymetrix/Thermo Fisher probe IDs which need to be mapped to gene symbols\n", "# Standard human gene symbols would look like BRCA1, TP53, etc.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "752a2fc4", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "7b0a05bb", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:02:33.104048Z", "iopub.status.busy": "2025-03-25T07:02:33.103942Z", "iopub.status.idle": "2025-03-25T07:02:37.593990Z", "shell.execute_reply": "2025-03-25T07:02:37.593466Z" } }, "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', 'gene_assignment', 'mrna_assignment', 'swissprot', 'unigene', 'category', 'locus type', 'notes', 'SPOT_ID']\n", "{'ID': ['TC01000001.hg.1', 'TC01000002.hg.1', 'TC01000003.hg.1'], 'probeset_id': ['TC01000001.hg.1', 'TC01000002.hg.1', 'TC01000003.hg.1'], 'seqname': ['chr1', 'chr1', 'chr1'], 'strand': ['+', '+', '+'], 'start': ['11869', '29554', '69091'], 'stop': ['14409', '31109', '70008'], 'total_probes': [49.0, 60.0, 30.0], 'gene_assignment': ['NR_046018 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102 /// ENST00000456328 // DDX11L5 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 5 // 9p24.3 // 100287596 /// ENST00000456328 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102', 'ENST00000408384 // MIR1302-11 // microRNA 1302-11 // --- // 100422919 /// ENST00000408384 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000408384 // MIR1302-9 // microRNA 1302-9 // --- // 100422831 /// ENST00000408384 // MIR1302-2 // microRNA 1302-2 // --- // 100302278 /// ENST00000469289 // MIR1302-11 // microRNA 1302-11 // --- // 100422919 /// ENST00000469289 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000469289 // MIR1302-9 // microRNA 1302-9 // --- // 100422831 /// ENST00000469289 // MIR1302-2 // microRNA 1302-2 // --- // 100302278 /// ENST00000473358 // MIR1302-11 // microRNA 1302-11 // --- // 100422919 /// ENST00000473358 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000473358 // MIR1302-9 // microRNA 1302-9 // --- // 100422831 /// ENST00000473358 // MIR1302-2 // microRNA 1302-2 // --- // 100302278 /// OTTHUMT00000002841 // OTTHUMG00000000959 // NULL // --- // --- /// OTTHUMT00000002841 // RP11-34P13.3 // NULL // --- // --- /// OTTHUMT00000002840 // OTTHUMG00000000959 // NULL // --- // --- /// OTTHUMT00000002840 // RP11-34P13.3 // NULL // --- // ---', 'NM_001005484 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// ENST00000335137 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// OTTHUMT00000003223 // OR4F5 // NULL // --- // ---'], 'mrna_assignment': ['NR_046018 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 (DDX11L1), non-coding RNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000456328 // ENSEMBL // cdna:known chromosome:GRCh37:1:11869:14409:1 gene:ENSG00000223972 gene_biotype:pseudogene transcript_biotype:processed_transcript // chr1 // 100 // 100 // 0 // --- // 0 /// uc001aaa.3 // UCSC Genes // --- // chr1 // 100 // 100 // 0 // --- // 0 /// uc010nxq.1 // UCSC Genes // --- // chr1 // 100 // 100 // 0 // --- // 0 /// uc010nxr.1 // UCSC Genes // --- // chr1 // 100 // 100 // 0 // --- // 0', 'ENST00000408384 // ENSEMBL // ncrna:miRNA chromosome:GRCh37:1:30366:30503:1 gene:ENSG00000221311 gene_biotype:miRNA transcript_biotype:miRNA // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000469289 // ENSEMBL // havana:lincRNA chromosome:GRCh37:1:30267:31109:1 gene:ENSG00000243485 gene_biotype:lincRNA transcript_biotype:lincRNA // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000473358 // ENSEMBL // havana:lincRNA chromosome:GRCh37:1:29554:31097:1 gene:ENSG00000243485 gene_biotype:lincRNA transcript_biotype:lincRNA // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000002841 // Havana transcript // cdna:all chromosome:VEGA52:1:30267:31109:1 Gene:OTTHUMG00000000959 // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000002840 // Havana transcript // cdna:all chromosome:VEGA52:1:29554:31097:1 Gene:OTTHUMG00000000959 // chr1 // 100 // 100 // 0 // --- // 0', 'NM_001005484 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 5 (OR4F5), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000335137 // ENSEMBL // cdna:known chromosome:GRCh37:1:69091:70008:1 gene:ENSG00000186092 gene_biotype:protein_coding transcript_biotype:protein_coding // chr1 // 100 // 100 // 0 // --- // 0 /// uc001aal.1 // UCSC Genes // --- // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000003223 // Havana transcript // cdna:all chromosome:VEGA52:1:69091:70008:1 Gene:OTTHUMG00000001094 // chr1 // 100 // 100 // 0 // --- // 0'], 'swissprot': ['NR_046018 // B7ZGX0 /// NR_046018 // B7ZGX2 /// NR_046018 // B7ZGX7 /// NR_046018 // B7ZGX8 /// ENST00000456328 // B7ZGX0 /// ENST00000456328 // B7ZGX2 /// ENST00000456328 // B7ZGX3 /// ENST00000456328 // B7ZGX7 /// ENST00000456328 // B7ZGX8 /// ENST00000456328 // Q6ZU42', '---', 'NM_001005484 // Q8NH21 /// ENST00000335137 // Q8NH21'], 'unigene': ['NR_046018 // Hs.714157 // testis| normal| adult /// ENST00000456328 // Hs.719844 // brain| testis| normal /// ENST00000456328 // Hs.714157 // testis| normal| adult /// ENST00000456328 // Hs.618434 // testis| normal', 'ENST00000469289 // Hs.622486 // eye| normal| adult /// ENST00000469289 // Hs.729632 // testis| normal /// ENST00000469289 // Hs.742718 // testis /// ENST00000473358 // Hs.622486 // eye| normal| adult /// ENST00000473358 // Hs.729632 // testis| normal /// ENST00000473358 // Hs.742718 // testis', 'NM_001005484 // Hs.554500 // --- /// ENST00000335137 // Hs.554500 // ---'], 'category': ['main', 'main', 'main'], 'locus type': ['Coding', 'Coding', 'Coding'], 'notes': ['---', '---', '---'], 'SPOT_ID': ['chr1(+):11869-14409', 'chr1(+):29554-31109', 'chr1(+):69091-70008']}\n", "\n", "Examining gene_assignment column format (first 3 rows):\n", "Row 0: NR_046018 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102 /// ENST00000456328 // DDX11L5 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 5 // 9p24.3 // 100287596 /// ENST00000456328 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102\n", "Row 1: ENST00000408384 // MIR1302-11 // microRNA 1302-11 // --- // 100422919 /// ENST00000408384 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000408384 // MIR1302-9 // microRNA 1302-9 // --- // 100422831 /// ENST00000408384 // MIR1302-2 // microRNA 1302-2 // --- // 100302278 /// ENST00000469289 // MIR1302-11 // microRNA 1302-11 // --- // 100422919 /// ENST00000469289 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000469289 // MIR1302-9 // microRNA 1302-9 // --- // 100422831 /// ENST00000469289 // MIR1302-2 // microRNA 1302-2 // --- // 100302278 /// ENST00000473358 // MIR1302-11 // microRNA 1302-11 // --- // 100422919 /// ENST00000473358 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000473358 // MIR1302-9 // microRNA 1302-9 // --- // 100422831 /// ENST00000473358 // MIR1302-2 // microRNA 1302-2 // --- // 100302278 /// OTTHUMT00000002841 // OTTHUMG00000000959 // NULL // --- // --- /// OTTHUMT00000002841 // RP11-34P13.3 // NULL // --- // --- /// OTTHUMT00000002840 // OTTHUMG00000000959 // NULL // --- // --- /// OTTHUMT00000002840 // RP11-34P13.3 // NULL // --- // ---\n", "Row 2: NM_001005484 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// ENST00000335137 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// OTTHUMT00000003223 // OR4F5 // NULL // --- // ---\n", "\n", "Gene assignment column completeness: 70753/2096623 rows (3.37%)\n", "\n", "Attempting to extract gene symbols from first few entries:\n", "Row 0: Extracted gene symbol: DDX11L1\n", "Row 1: Extracted gene symbol: MIR1302-11\n", "Row 2: Extracted gene symbol: OR4F5\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, it appears the gene symbols are in the 'gene_assignment' column\n", "# Examine the gene_assignment column which appears to contain gene symbols\n", "print(\"\\nExamining gene_assignment column format (first 3 rows):\")\n", "if 'gene_assignment' in gene_annotation.columns:\n", " for i in range(min(3, len(gene_annotation))):\n", " print(f\"Row {i}: {gene_annotation['gene_assignment'].iloc[i]}\")\n", "\n", " # Check the quality and completeness of the mapping\n", " non_null_assignments = gene_annotation['gene_assignment'].notna().sum()\n", " total_rows = len(gene_annotation)\n", " print(f\"\\nGene assignment column completeness: {non_null_assignments}/{total_rows} rows ({non_null_assignments/total_rows:.2%})\")\n", " \n", " # Try to extract some gene symbols from the gene_assignment column\n", " print(\"\\nAttempting to extract gene symbols from first few entries:\")\n", " for i in range(min(3, len(gene_annotation))):\n", " assignment = gene_annotation['gene_assignment'].iloc[i]\n", " if isinstance(assignment, str):\n", " # The format appears to be: accession_id // gene_symbol // description // location // gene_id\n", " parts = assignment.split('//')\n", " if len(parts) > 1:\n", " gene_symbol = parts[1].strip()\n", " print(f\"Row {i}: Extracted gene symbol: {gene_symbol}\")\n" ] }, { "cell_type": "markdown", "id": "c773e467", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "2a5cba96", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:02:37.595538Z", "iopub.status.busy": "2025-03-25T07:02:37.595422Z", "iopub.status.idle": "2025-03-25T07:02:44.317228Z", "shell.execute_reply": "2025-03-25T07:02:44.316555Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Mapping dataframe shape before cleaning: (70753, 2)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape after mapping: (71527, 30)\n", "First 5 gene symbols:\n", "['A-', 'A-2', 'A-52', 'A-575C2', 'A-E']\n", "\n", "First 5 expression values for sample GSM8350629:\n", "Gene\n", "A- 20.84375\n", "A-2 1.31400\n", "A-52 4.69000\n", "A-575C2 2.84000\n", "A-E 1.73500\n", "Name: GSM8350629, dtype: float64\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Breast_Cancer/gene_data/GSE270721.csv\n" ] } ], "source": [ "# 1. Based on observation, the probe IDs are in the 'ID' column of the gene annotation data\n", "# and gene symbols are in the 'gene_assignment' column, but need to be extracted from a specific format\n", "\n", "# First, load the data files\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "gene_annotation = get_gene_annotation(soft_file)\n", "gene_data_probes = get_genetic_data(matrix_file)\n", "\n", "# 2. Create a mapping dataframe\n", "# We'll use 'ID' for probe identifiers, and rename 'gene_assignment' to 'Gene' for the mapping function\n", "mapping_df = gene_annotation[['ID', 'gene_assignment']].copy()\n", "mapping_df = mapping_df.dropna() # Remove rows with missing gene assignments\n", "mapping_df = mapping_df.rename(columns={'gene_assignment': 'Gene'}) # Rename column to match the function expectation\n", "\n", "# Print the mapping dataframe shape to track progress\n", "print(f\"Mapping dataframe shape before cleaning: {mapping_df.shape}\")\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n", "# The extract_human_gene_symbols function will parse the gene_assignment field to get gene symbols\n", "gene_data = apply_gene_mapping(gene_data_probes, mapping_df)\n", "\n", "# Print the shape of the gene expression data\n", "print(f\"Gene data shape after mapping: {gene_data.shape}\")\n", "\n", "# Preview first few rows of gene data\n", "print(\"First 5 gene symbols:\")\n", "print(gene_data.index[:5].tolist())\n", "\n", "# Preview the first few values for a sample (column)\n", "if gene_data.shape[1] > 0:\n", " first_col = gene_data.columns[0]\n", " print(f\"\\nFirst 5 expression values for sample {first_col}:\")\n", " print(gene_data[first_col].head())\n", "\n", "# Save the gene data to file\n", "# Create directory if it doesn't exist\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": "ae3f3dfd", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "a0291dcd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:02:44.319138Z", "iopub.status.busy": "2025-03-25T07:02:44.318987Z", "iopub.status.idle": "2025-03-25T07:02:44.834263Z", "shell.execute_reply": "2025-03-25T07:02:44.833613Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (71527, 30)\n", "Gene data shape after normalization: (24018, 30)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Breast_Cancer/gene_data/GSE270721.csv\n", "No trait data (Breast_Cancer) available in this dataset based on previous analysis.\n", "Cannot proceed with data linking due to missing trait or gene data.\n", "Abnormality detected in the cohort: GSE270721. Preprocessing failed.\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 }