{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "80f035bb", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:39:03.139415Z", "iopub.status.busy": "2025-03-25T07:39:03.139067Z", "iopub.status.idle": "2025-03-25T07:39:03.305418Z", "shell.execute_reply": "2025-03-25T07:39:03.304946Z" } }, "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 = \"Lower_Grade_Glioma\"\n", "cohort = \"GSE74567\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Lower_Grade_Glioma\"\n", "in_cohort_dir = \"../../input/GEO/Lower_Grade_Glioma/GSE74567\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Lower_Grade_Glioma/GSE74567.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Lower_Grade_Glioma/gene_data/GSE74567.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Lower_Grade_Glioma/clinical_data/GSE74567.csv\"\n", "json_path = \"../../output/preprocess/Lower_Grade_Glioma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "79b99be1", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "1e07b428", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:39:03.306896Z", "iopub.status.busy": "2025-03-25T07:39:03.306747Z", "iopub.status.idle": "2025-03-25T07:39:03.422067Z", "shell.execute_reply": "2025-03-25T07:39:03.421577Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Astrocytoma cell lines transduced to either express GFAP isoforms or to knockdown GFAP isoforms\"\n", "!Series_summary\t\"Modulation of the GFAP cytoskeleton in astrocytoma cells alters processes involved in extracellular matrix remodelling and cell-cell signalling – a transcriptome analysis\"\n", "!Series_summary\t\"Astrocytomas grade IV are malignant brain tumours with no effective treatment and a five year survival rate of only 5%. Expression of Glial Fibrillary Acidic Protein (GFAP) is lower in high astrocytoma grade, but the expression of the splice isoform GFAPδ is similar in low and high-grade astrocytomas. Thus the ratio of GFAPδ/α is increased in high-grade astrocytomas. We studied transcriptome changes in astrocytoma cell lines resulting from an induced alteration of GFAP isoform expression. GFAPα or GFAPδ were increased or decreased by recombinant expression or shRNA mediated knockdown of GFAPpan or GFAPα. We find that the most prominent effects are induced by the modulations where the GFAPδ/GFAPα ratio is increased. Gene ontology analysis revealed that the main effects of GFAP modulation take place in the extracellular matrix remodelling and cellular signalling clusters, with possible implications in astrocytoma invasive behaviour and angiogenesis.\"\n", "!Series_overall_design\t\"2 cell lines (U251 and U373) with respectively recombinant expression or knockdown of GFAP isoforms. Biological replicates: U251 control - N=8, U251 recombinant GFAPa - N=8, U251 Recombinant GFAPdelta - N=8, U373 shRNA Non Targeting Control - N=6, U373 shRNA GFAPalpha - N=5, U373 shRNA GFAPpan - N=5\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tumour line: U373', 'tumour line: U251'], 1: ['construct: shRNA GFAPpan', 'construct: shRNA NTC', 'construct: shRNA GFAPalpha', 'construct: recombinant mCherry', 'construct: recombinant GFAPalpha - IRES - GFP', 'construct: recombinant GFAPdelta - IRES - mCherry'], 2: ['substrate: PDMS coated with YIGSR peptide']}\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": "7e7fdc4f", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "67dd5351", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:39:03.423321Z", "iopub.status.busy": "2025-03-25T07:39:03.423202Z", "iopub.status.idle": "2025-03-25T07:39:03.427960Z", "shell.execute_reply": "2025-03-25T07:39:03.427499Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Completed initial validation for GSE74567. Trait: Lower_Grade_Glioma\n", "Gene data available: True, Trait data available: True\n" ] } ], "source": [ "import pandas as pd\n", "from typing import Optional, Callable, Dict, Any\n", "import os\n", "import json\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains gene expression data from astrocytoma cell lines\n", "# with modulated GFAP isoform expression, analyzing transcriptome changes.\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# The sample characteristics dictionary shows:\n", "# - No direct trait information (LGG status) because these are all cancer cell lines\n", "# - No age information as these are cell lines\n", "# - No gender information as these are cell lines\n", "# However, we can use the \"construct\" information as the trait since it indicates different GFAP expression conditions\n", "\n", "trait_row = 1 # The constructs in row 1 represent different experimental conditions\n", "age_row = None # No age data available for cell lines\n", "gender_row = None # No gender data available for cell lines\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert the construct information to binary values based on GFAP expression modulation.\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Binary classification: \n", " # 1 for increased GFAPδ/GFAPα ratio (either by recombinant GFAPδ or knockdown of GFAPα/GFAPpan)\n", " # 0 for controls or normal GFAPα expression\n", " if 'recombinant GFAPdelta' in value or 'shRNA GFAPalpha' in value or 'shRNA GFAPpan' in value:\n", " return 1 # Increased GFAPδ/GFAPα ratio\n", " elif 'recombinant GFAPalpha' in value or 'recombinant mCherry' in value or 'shRNA NTC' in value:\n", " return 0 # Control or normal GFAPα expression\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " # No age data to convert\n", " return None\n", "\n", "def convert_gender(value):\n", " # No gender data to convert\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Trait data is available (we're using the construct information as our trait)\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and save cohort info\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. Skipping the clinical feature extraction step\n", "# Since we couldn't locate the clinical data file and \n", "# the sample characteristics dictionary is not in a proper format to create a DataFrame,\n", "# we'll skip this step after validating the cohort info.\n", "print(f\"Completed initial validation for {cohort}. Trait: {trait}\")\n", "print(f\"Gene data available: {is_gene_available}, Trait data available: {is_trait_available}\")\n" ] }, { "cell_type": "markdown", "id": "376f2cf2", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "bd123dd2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:39:03.429150Z", "iopub.status.busy": "2025-03-25T07:39:03.429038Z", "iopub.status.idle": "2025-03-25T07:39:03.597023Z", "shell.execute_reply": "2025-03-25T07:39:03.596467Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining matrix file structure...\n", "Line 0: !Series_title\t\"Astrocytoma cell lines transduced to either express GFAP isoforms or to knockdown GFAP isoforms\"\n", "Line 1: !Series_geo_accession\t\"GSE74567\"\n", "Line 2: !Series_status\t\"Public on Jul 03 2017\"\n", "Line 3: !Series_submission_date\t\"Nov 02 2015\"\n", "Line 4: !Series_last_update_date\t\"Feb 23 2018\"\n", "Line 5: !Series_pubmed_id\t\"29152145\"\n", "Line 6: !Series_summary\t\"Modulation of the GFAP cytoskeleton in astrocytoma cells alters processes involved in extracellular matrix remodelling and cell-cell signalling – a transcriptome analysis\"\n", "Line 7: !Series_summary\t\"Astrocytomas grade IV are malignant brain tumours with no effective treatment and a five year survival rate of only 5%. Expression of Glial Fibrillary Acidic Protein (GFAP) is lower in high astrocytoma grade, but the expression of the splice isoform GFAPδ is similar in low and high-grade astrocytomas. Thus the ratio of GFAPδ/α is increased in high-grade astrocytomas. We studied transcriptome changes in astrocytoma cell lines resulting from an induced alteration of GFAP isoform expression. GFAPα or GFAPδ were increased or decreased by recombinant expression or shRNA mediated knockdown of GFAPpan or GFAPα. We find that the most prominent effects are induced by the modulations where the GFAPδ/GFAPα ratio is increased. Gene ontology analysis revealed that the main effects of GFAP modulation take place in the extracellular matrix remodelling and cellular signalling clusters, with possible implications in astrocytoma invasive behaviour and angiogenesis.\"\n", "Line 8: !Series_overall_design\t\"2 cell lines (U251 and U373) with respectively recombinant expression or knockdown of GFAP isoforms. Biological replicates: U251 control - N=8, U251 recombinant GFAPa - N=8, U251 Recombinant GFAPdelta - N=8, U373 shRNA Non Targeting Control - N=6, U373 shRNA GFAPalpha - N=5, U373 shRNA GFAPpan - N=5\"\n", "Line 9: !Series_type\t\"Expression profiling by array\"\n", "Found table marker at line 62\n", "First few lines after marker:\n", "\"ID_REF\"\t\"GSM1923085\"\t\"GSM1923086\"\t\"GSM1923087\"\t\"GSM1923088\"\t\"GSM1923089\"\t\"GSM1923090\"\t\"GSM1923091\"\t\"GSM1923092\"\t\"GSM1923093\"\t\"GSM1923094\"\t\"GSM1923095\"\t\"GSM1923096\"\t\"GSM1923097\"\t\"GSM1923098\"\t\"GSM1923099\"\t\"GSM1923100\"\t\"GSM1923101\"\t\"GSM1923102\"\t\"GSM1923103\"\t\"GSM1923104\"\t\"GSM1923105\"\t\"GSM1923106\"\t\"GSM1923107\"\t\"GSM1923108\"\t\"GSM1923109\"\t\"GSM1923110\"\t\"GSM1923111\"\t\"GSM1923112\"\t\"GSM1923113\"\t\"GSM1923114\"\t\"GSM1923115\"\t\"GSM1923116\"\t\"GSM1923117\"\t\"GSM1923118\"\t\"GSM1923119\"\t\"GSM1923120\"\t\"GSM1923121\"\t\"GSM1923122\"\t\"GSM1923123\"\t\"GSM1923124\"\n", "\"A_23_P100001\"\t7.523673858\t7.617331263\t7.719579414\t7.424315009\t7.181853388\t7.010250332\t7.826262472\t7.509768026\t8.18334099\t7.234614417\t7.942148753\t7.630297565\t7.362786926\t7.541585562\t7.652153204\t8.053501067\t7.656534484\t7.510359087\t7.04447922\t7.585072974\t7.777175054\t7.356946076\t7.623177676\t7.379428691\t7.484086603\t7.157357001\t7.168817519\t7.212228213\t7.887446911\t7.368677013\t7.210002173\t7.505426272\t7.823394905\t7.325823861\t7.194482336\t7.142198062\t7.282623261\t7.320740613\t7.360498496\t7.408891599\n", "\"A_23_P100022\"\t5.080111262\t4.837126976\t5.400014343\t5.094714262\t5.569440431\t5.464628468\t5.454392704\t5.428188429\t5.961694997\t5.377171219\t5.983278136\t5.733155417\t5.856536028\t5.41685335\t5.58961092\t5.646290471\t3.209780151\t3.574834892\t3.71271334\t3.254388251\t4.459653057\t3.538067169\t3.08774063\t2.58077503\t3.269009003\t3.835805047\t4.756417155\t4.651169156\t4.686004737\t4.55540615\t3.99219067\t5.07891881\t4.493007847\t4.739224213\t4.48264371\t4.042535111\t4.328491126\t4.851208224\t4.857878595\t4.443457236\n", "\"A_23_P100056\"\t3.937898279\t4.478489266\t4.649393821\t4.704021386\t4.753725366\t4.40191095\t5.489641347\t5.951333042\t4.863730297\t5.211929964\t5.055999634\t4.791525043\t5.500016966\t5.20049393\t5.248739097\t5.361916112\t3.954140334\t4.022602763\t4.409918615\t4.215080149\t3.935181027\t4.489243494\t4.584875314\t4.217237755\t3.627489283\t3.744628223\t4.097472617\t4.24833189\t4.458351891\t3.815028956\t4.432785024\t4.975569838\t4.473118923\t4.509364435\t4.33578323\t4.412384443\t3.44221532\t4.290451753\t4.144840549\t4.714486903\n", "\"A_23_P100074\"\t9.422043619\t9.730529346\t9.582364496\t9.566881226\t9.203744782\t9.004968309\t9.516058228\t9.500538732\t9.887370548\t9.589697937\t9.319794923\t9.576626698\t9.63961372\t8.980976802\t9.096050342\t9.52711923\t8.647917712\t8.653501937\t8.498510222\t8.86160482\t8.423719021\t9.249398222\t8.418371766\t8.614211411\t9.315560486\t9.208958164\t8.684435985\t8.65988559\t9.505680733\t8.840669536\t8.920917247\t8.344117388\t8.834885305\t8.694797775\t8.734359099\t8.5469929\t8.871911181\t8.778397173\t8.996166493\t9.044325948\n", "Total lines examined: 63\n", "\n", "Attempting to extract gene data from matrix file...\n", "Successfully extracted gene data with 34127 rows\n", "First 20 gene IDs:\n", "Index(['A_23_P100001', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074',\n", " 'A_23_P100127', 'A_23_P100141', 'A_23_P100189', 'A_23_P100196',\n", " 'A_23_P100203', 'A_23_P100220', 'A_23_P100240', 'A_23_P10025',\n", " 'A_23_P100292', 'A_23_P100315', 'A_23_P100326', 'A_23_P100344',\n", " 'A_23_P100355', 'A_23_P100386', 'A_23_P100392', 'A_23_P100420'],\n", " dtype='object', name='ID')\n", "\n", "Gene expression data available: True\n" ] } ], "source": [ "# 1. Get the file paths for the SOFT file and matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# Add diagnostic code to check file content and structure\n", "print(\"Examining matrix file structure...\")\n", "with gzip.open(matrix_file, 'rt') as file:\n", " table_marker_found = False\n", " lines_read = 0\n", " for i, line in enumerate(file):\n", " lines_read += 1\n", " if '!series_matrix_table_begin' in line:\n", " table_marker_found = True\n", " print(f\"Found table marker at line {i}\")\n", " # Read a few lines after the marker to check data structure\n", " next_lines = [next(file, \"\").strip() for _ in range(5)]\n", " print(\"First few lines after marker:\")\n", " for next_line in next_lines:\n", " print(next_line)\n", " break\n", " if i < 10: # Print first few lines to see file structure\n", " print(f\"Line {i}: {line.strip()}\")\n", " if i > 100: # Don't read the entire file\n", " break\n", " \n", " if not table_marker_found:\n", " print(\"Table marker '!series_matrix_table_begin' not found in first 100 lines\")\n", " print(f\"Total lines examined: {lines_read}\")\n", "\n", "# 2. Try extracting gene expression data from the matrix file again with better diagnostics\n", "try:\n", " print(\"\\nAttempting to extract gene data from matrix file...\")\n", " gene_data = get_genetic_data(matrix_file)\n", " if gene_data.empty:\n", " print(\"Extracted gene expression data is empty\")\n", " is_gene_available = False\n", " else:\n", " print(f\"Successfully extracted gene data with {len(gene_data.index)} rows\")\n", " print(\"First 20 gene IDs:\")\n", " print(gene_data.index[:20])\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {str(e)}\")\n", " print(\"This dataset appears to have an empty or malformed gene expression matrix\")\n", " is_gene_available = False\n", "\n", "print(f\"\\nGene expression data available: {is_gene_available}\")\n", "\n", "# If data extraction failed, try an alternative approach using pandas directly\n", "if not is_gene_available:\n", " print(\"\\nTrying alternative approach to read gene expression data...\")\n", " try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Skip lines until we find the marker\n", " for line in file:\n", " if '!series_matrix_table_begin' in line:\n", " break\n", " \n", " # Try to read the data directly with pandas\n", " gene_data = pd.read_csv(file, sep='\\t', index_col=0)\n", " \n", " if not gene_data.empty:\n", " print(f\"Successfully extracted gene data with alternative method: {gene_data.shape}\")\n", " print(\"First 20 gene IDs:\")\n", " print(gene_data.index[:20])\n", " is_gene_available = True\n", " else:\n", " print(\"Alternative extraction method also produced empty data\")\n", " except Exception as e:\n", " print(f\"Alternative extraction failed: {str(e)}\")\n" ] }, { "cell_type": "markdown", "id": "6d8bd8a0", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "185d2116", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:39:03.598403Z", "iopub.status.busy": "2025-03-25T07:39:03.598281Z", "iopub.status.idle": "2025-03-25T07:39:03.600447Z", "shell.execute_reply": "2025-03-25T07:39:03.600072Z" } }, "outputs": [], "source": [ "# Examining the gene IDs\n", "# Based on the observed gene IDs (like 'A_23_P100001'), these appear to be Agilent microarray probe IDs\n", "# rather than human gene symbols.\n", "# Agilent IDs typically follow this format: A_XX_PXXXXXX where XX is probe type and XXXXXX is the probe number\n", "# These would need to be mapped to standard gene symbols for proper analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "3ad262ba", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "3f300e7f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:39:03.601591Z", "iopub.status.busy": "2025-03-25T07:39:03.601483Z", "iopub.status.idle": "2025-03-25T07:39:05.964152Z", "shell.execute_reply": "2025-03-25T07:39:05.963452Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting gene annotation data from SOFT file...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully extracted gene annotation data with 1399304 rows\n", "\n", "Gene annotation preview (first few rows):\n", "{'ID': ['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107', '(+)E1A_r60_a135'], 'SPOT_ID': ['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107', '(+)E1A_r60_a135'], 'CONTROL_TYPE': ['pos', 'pos', 'pos', 'pos', 'pos'], 'REFSEQ': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan], 'GENE': [nan, nan, nan, nan, nan], 'GENE_SYMBOL': [nan, nan, nan, nan, nan], 'GENE_NAME': [nan, nan, nan, nan, nan], 'UNIGENE_ID': [nan, nan, nan, nan, nan], 'ENSEMBL_ID': [nan, nan, nan, nan, nan], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': [nan, nan, nan, nan, nan], 'CHROMOSOMAL_LOCATION': [nan, nan, nan, nan, nan], 'CYTOBAND': [nan, nan, nan, nan, nan], 'DESCRIPTION': [nan, nan, nan, nan, nan], 'GO_ID': [nan, nan, nan, nan, nan], 'SEQUENCE': [nan, nan, nan, nan, nan]}\n", "\n", "Column names in gene annotation data:\n", "['ID', 'SPOT_ID', 'CONTROL_TYPE', 'REFSEQ', 'GB_ACC', 'GENE', 'GENE_SYMBOL', 'GENE_NAME', 'UNIGENE_ID', 'ENSEMBL_ID', 'TIGR_ID', 'ACCESSION_STRING', 'CHROMOSOMAL_LOCATION', 'CYTOBAND', 'DESCRIPTION', 'GO_ID', 'SEQUENCE']\n", "\n", "The dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\n", "Number of rows with GenBank accessions: 30905 out of 1399304\n", "\n", "The dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\n", "Example SPOT_ID format: (+)E1A_r60_1\n" ] } ], "source": [ "# 1. Extract gene annotation data from the SOFT file\n", "print(\"Extracting gene annotation data from SOFT file...\")\n", "try:\n", " # Use the library function to extract gene annotation\n", " gene_annotation = get_gene_annotation(soft_file)\n", " print(f\"Successfully extracted gene annotation data with {len(gene_annotation.index)} rows\")\n", " \n", " # Preview the annotation DataFrame\n", " print(\"\\nGene annotation preview (first few rows):\")\n", " print(preview_df(gene_annotation))\n", " \n", " # Show column names to help identify which columns we need for mapping\n", " print(\"\\nColumn names in gene annotation data:\")\n", " print(gene_annotation.columns.tolist())\n", " \n", " # Check for relevant mapping columns\n", " if 'GB_ACC' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\")\n", " # Count non-null values in GB_ACC column\n", " non_null_count = gene_annotation['GB_ACC'].count()\n", " print(f\"Number of rows with GenBank accessions: {non_null_count} out of {len(gene_annotation)}\")\n", " \n", " if 'SPOT_ID' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\")\n", " print(\"Example SPOT_ID format:\", gene_annotation['SPOT_ID'].iloc[0])\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation data: {e}\")\n", " is_gene_available = False\n" ] }, { "cell_type": "markdown", "id": "226af4fc", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "60761eb4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:39:05.965789Z", "iopub.status.busy": "2025-03-25T07:39:05.965658Z", "iopub.status.idle": "2025-03-25T07:39:06.922015Z", "shell.execute_reply": "2025-03-25T07:39:06.921367Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Examining gene IDs in expression data vs. annotation data:\n", "First few gene IDs in expression data: ['A_23_P100001', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074', 'A_23_P100127']\n", "First few IDs in annotation data: ['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107', '(+)E1A_r60_a135']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Found 487121 annotation entries matching expression data ID pattern 'A_23_'\n", "First few matching annotation IDs:\n", "['A_23_P100001', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074', 'A_23_P100127']\n", "\n", "Creating gene mapping dataframe...\n", "Gene symbols available: 29833 entries\n", "Final mapping dataframe contains 29833 entries\n", "Sample of mapping data:\n", "{'ID': ['A_23_P100001', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074', 'A_23_P100127'], 'Gene': ['FAM174B', 'SV2B', 'RBPMS2', 'AVEN', 'CASC5']}\n", "\n", "Converting probe-level measurements to gene expression data...\n", "Successfully mapped to 19818 unique genes\n", "First few gene symbols in mapped data:\n", "['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data saved to ../../output/preprocess/Lower_Grade_Glioma/gene_data/GSE74567.csv\n" ] } ], "source": [ "# 1. Determine which columns to use for mapping\n", "# From the gene annotation data preview, we can see:\n", "# - 'ID' column contains the probe IDs\n", "# - 'GENE_SYMBOL' column contains the gene symbols we need\n", "\n", "print(\"\\nExamining gene IDs in expression data vs. annotation data:\")\n", "print(f\"First few gene IDs in expression data: {gene_data.index[:5].tolist()}\")\n", "print(f\"First few IDs in annotation data: {gene_annotation['ID'][:5].tolist()}\")\n", "\n", "# Let's check for format matching between expression data IDs and annotation IDs\n", "expression_id_pattern = gene_data.index[0][:5] # Get pattern of first few characters\n", "matching_ids = gene_annotation[gene_annotation['ID'].str.contains(expression_id_pattern, na=False)]\n", "\n", "print(f\"\\nFound {len(matching_ids)} annotation entries matching expression data ID pattern '{expression_id_pattern}'\")\n", "if not matching_ids.empty:\n", " print(\"First few matching annotation IDs:\")\n", " print(matching_ids['ID'][:5].tolist())\n", "\n", "# 2. Create the gene mapping dataframe\n", "# Since 'ID' in annotation may not exactly match the expression data IDs,\n", "# we'll perform a careful mapping based on available data\n", "print(\"\\nCreating gene mapping dataframe...\")\n", "\n", "# First check if we have GENE_SYMBOL column with data\n", "gene_symbol_available = 'GENE_SYMBOL' in gene_annotation.columns and gene_annotation['GENE_SYMBOL'].notna().sum() > 0\n", "if gene_symbol_available:\n", " print(f\"Gene symbols available: {gene_annotation['GENE_SYMBOL'].notna().sum()} entries\")\n", " mapping_df = get_gene_mapping(gene_annotation, 'ID', 'GENE_SYMBOL')\n", "else:\n", " # Fall back to GENE column if GENE_SYMBOL is not available\n", " print(\"GENE_SYMBOL column empty or missing, checking GENE column...\")\n", " if 'GENE' in gene_annotation.columns and gene_annotation['GENE'].notna().sum() > 0:\n", " print(f\"GENE column available with {gene_annotation['GENE'].notna().sum()} entries\")\n", " mapping_df = get_gene_mapping(gene_annotation, 'ID', 'GENE')\n", " else:\n", " print(\"Both GENE_SYMBOL and GENE columns unavailable or empty\")\n", " # Try to find any column that might contain gene identifiers\n", " potential_gene_cols = ['ENSEMBL_ID', 'REFSEQ', 'GB_ACC', 'UNIGENE_ID']\n", " for col in potential_gene_cols:\n", " if col in gene_annotation.columns and gene_annotation[col].notna().sum() > 0:\n", " print(f\"Using {col} as gene identifier, found {gene_annotation[col].notna().sum()} entries\")\n", " mapping_df = get_gene_mapping(gene_annotation, 'ID', col)\n", " break\n", " else:\n", " raise ValueError(\"No suitable gene identifier column found in annotation data\")\n", "\n", "# Filter mapping to only include IDs present in our expression data\n", "mapping_df = mapping_df[mapping_df['ID'].isin(gene_data.index)]\n", "print(f\"Final mapping dataframe contains {len(mapping_df)} entries\")\n", "print(\"Sample of mapping data:\")\n", "print(preview_df(mapping_df, n=5))\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "print(\"\\nConverting probe-level measurements to gene expression data...\")\n", "try:\n", " gene_data = apply_gene_mapping(gene_data, mapping_df)\n", " print(f\"Successfully mapped to {len(gene_data)} unique genes\")\n", " print(\"First few gene symbols in mapped data:\")\n", " print(gene_data.index[:10].tolist())\n", "except Exception as e:\n", " print(f\"Error applying gene mapping: {str(e)}\")\n", " print(\"Trying alternative approach...\")\n", " \n", " # Alternative approach if the standard function fails\n", " # Extract human gene symbols from the Gene column\n", " mapping_df['Gene'] = mapping_df['Gene'].apply(extract_human_gene_symbols)\n", " \n", " # Count genes per probe and expand to one gene per row\n", " mapping_df['num_genes'] = mapping_df['Gene'].apply(len)\n", " mapping_df = mapping_df.explode('Gene')\n", " \n", " # Empty list becomes NaN after explode, which should be dropped\n", " mapping_df = mapping_df.dropna(subset=['Gene'])\n", " mapping_df.set_index('ID', inplace=True)\n", " \n", " # Merge and distribute expression values\n", " expr_cols = gene_data.columns.tolist()\n", " merged_df = mapping_df.join(gene_data)\n", " merged_df[expr_cols] = merged_df[expr_cols].div(merged_df['num_genes'].replace(0, 1), axis=0)\n", " \n", " # Sum expression values for each gene\n", " gene_data = merged_df.groupby('Gene')[expr_cols].sum()\n", " \n", " print(f\"Alternative approach successful: mapped to {len(gene_data)} unique genes\")\n", " print(\"First few gene symbols in mapped data:\")\n", " print(gene_data.index[:10].tolist())\n", "\n", "# Save the gene expression data to file\n", "output_directory = os.path.dirname(out_gene_data_file)\n", "os.makedirs(output_directory, exist_ok=True)\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"\\nGene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "3aaa448c", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "e6adaf74", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:39:06.923485Z", "iopub.status.busy": "2025-03-25T07:39:06.923359Z", "iopub.status.idle": "2025-03-25T07:39:16.121397Z", "shell.execute_reply": "2025-03-25T07:39:16.121068Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Normalizing gene symbols using NCBI Gene database...\n", "After normalization: 19447 unique genes remain\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Lower_Grade_Glioma/gene_data/GSE74567.csv\n", "\n", "Extracting clinical data directly from the matrix file...\n", "\n", "Processing clinical data...\n", "Extracted clinical data with shape: (1, 40)\n", "Clinical data saved to: ../../output/preprocess/Lower_Grade_Glioma/clinical_data/GSE74567.csv\n", "\n", "Linking clinical and genetic data...\n", "Found 40 common samples between clinical and genetic data\n", "Linked data shape: (40, 19448)\n", "\n", "Handling missing values in linked data...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (40, 19448)\n", "\n", "Evaluating trait and demographic feature bias...\n", "For the feature 'Lower_Grade_Glioma', the least common label is '1.0' with 18 occurrences. This represents 45.00% of the dataset.\n", "The distribution of the feature 'Lower_Grade_Glioma' in this dataset is fine.\n", "\n", "\n", "Saving linked data to ../../output/preprocess/Lower_Grade_Glioma/GSE74567.csv\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved successfully!\n" ] } ], "source": [ "# 1. Normalize gene symbols using NCBI Gene database\n", "print(\"\\nNormalizing gene symbols using NCBI Gene database...\")\n", "try:\n", " gene_data_normalized = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"After normalization: {len(gene_data_normalized)} unique genes remain\")\n", " gene_data_cleaned = gene_data_normalized\n", " \n", " # Save the normalized gene expression data\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " gene_data_cleaned.to_csv(out_gene_data_file)\n", " print(f\"Normalized gene expression data saved to {out_gene_data_file}\")\n", "except Exception as e:\n", " print(f\"Error during gene symbol normalization: {str(e)}\")\n", " print(\"Falling back to original gene data\")\n", " gene_data_cleaned = gene_data.copy()\n", "\n", "# 2. We need to recreate the clinical data from the original matrix file\n", "print(\"\\nExtracting clinical data directly from the matrix file...\")\n", "# Extract clinical data from the matrix file again\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", "# Process clinical data\n", "print(\"\\nProcessing clinical data...\")\n", "# Create clinical features dataframe \n", "if trait_row is not None:\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 if age_row is not None else None,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender if gender_row is not None else None\n", " )\n", " \n", " print(f\"Extracted clinical data with shape: {selected_clinical_df.shape}\")\n", " # Save clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to: {out_clinical_data_file}\")\n", " \n", " is_trait_available = True\n", "else:\n", " selected_clinical_df = pd.DataFrame()\n", " is_trait_available = False\n", " print(\"No trait data available in clinical information.\")\n", "\n", "# 3. Link clinical and genetic data\n", "if is_trait_available and is_gene_available:\n", " print(\"\\nLinking clinical and genetic data...\")\n", " try:\n", " # Ensure the sample IDs match between clinical and genetic data\n", " common_samples = list(set(selected_clinical_df.columns).intersection(set(gene_data_cleaned.columns)))\n", " \n", " if len(common_samples) == 0:\n", " print(\"Warning: No common samples between clinical and genetic data\")\n", " linked_data = pd.DataFrame()\n", " is_biased = True\n", " else:\n", " print(f\"Found {len(common_samples)} common samples between clinical and genetic data\")\n", " \n", " # Filter data to include only common samples\n", " clinical_subset = selected_clinical_df[common_samples]\n", " genetic_subset = gene_data_cleaned[common_samples]\n", " \n", " # Link the data\n", " linked_data = pd.concat([clinical_subset, genetic_subset], axis=0).T\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " \n", " # 4. Handle missing values\n", " print(\"\\nHandling missing values in linked data...\")\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", " \n", " # 5. Determine if trait and demographic features are severely biased\n", " print(\"\\nEvaluating trait and demographic feature bias...\")\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " except Exception as e:\n", " print(f\"Error during data linking: {str(e)}\")\n", " linked_data = pd.DataFrame()\n", " is_biased = True\n", "else:\n", " print(\"\\nCannot create linked data: missing clinical or gene data\")\n", " linked_data = pd.DataFrame()\n", " is_biased = True\n", "\n", "# 6. Final validation and saving\n", "note = \"This dataset contains gene expression data from astrocytoma cell lines with modified GFAP isoform expression. The trait represents different experimental conditions related to the GFAPδ/GFAPα ratio.\"\n", "\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=is_biased if len(linked_data) > 0 else True,\n", " df=linked_data,\n", " note=note\n", ")\n", "\n", "# Save the linked data if it's usable\n", "if is_usable and len(linked_data) > 0:\n", " print(f\"\\nSaving linked data to {out_data_file}\")\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 successfully!\")\n", "else:\n", " print(f\"\\nDataset not usable for {trait} association studies due to bias or quality issues.\")" ] } ], "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 }