{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "be5358da", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:39:41.183572Z", "iopub.status.busy": "2025-03-25T07:39:41.183454Z", "iopub.status.idle": "2025-03-25T07:39:41.344695Z", "shell.execute_reply": "2025-03-25T07:39:41.344334Z" } }, "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_and_glioblastoma\"\n", "cohort = \"GSE35158\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/lower_grade_glioma_and_glioblastoma\"\n", "in_cohort_dir = \"../../input/GEO/lower_grade_glioma_and_glioblastoma/GSE35158\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/lower_grade_glioma_and_glioblastoma/GSE35158.csv\"\n", "out_gene_data_file = \"../../output/preprocess/lower_grade_glioma_and_glioblastoma/gene_data/GSE35158.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/lower_grade_glioma_and_glioblastoma/clinical_data/GSE35158.csv\"\n", "json_path = \"../../output/preprocess/lower_grade_glioma_and_glioblastoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "a798e832", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "f05a2a25", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:39:41.346154Z", "iopub.status.busy": "2025-03-25T07:39:41.346014Z", "iopub.status.idle": "2025-03-25T07:39:41.440706Z", "shell.execute_reply": "2025-03-25T07:39:41.440415Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the cohort directory:\n", "['GSE35158_family.soft.gz', 'GSE35158_series_matrix.txt.gz']\n", "Identified SOFT files: ['GSE35158_family.soft.gz']\n", "Identified matrix files: ['GSE35158_series_matrix.txt.gz']\n", "\n", "Background Information:\n", "!Series_title\t\"Expression profiling of lower-grade diffuse astrocytic glioma\"\n", "!Series_summary\t\"Diffuse gliomas represent the most prevalent class of primary brain tumor. Despite significant recent advances in the understanding of glioblastoma (WHO IV), its most malignant subtype, lower-grade (WHO II and III) glioma variants remain comparatively understudied, especially in light of their notably variable clinical behavior. To examine the foundations of this heterogeneity, we performed multidimensional molecular profiling, including global transcriptional analysis, on 101 lower-grade diffuse astrocytic gliomas collected at our own institution, and validated our findings using publically available gene expression and copy number data from large independent patient cohorts. We found that IDH mutational status delineated molecularly and clinically distinct glioma subsets, with IDH mutant (IDH mt) tumors exhibiting TP53 mutations, PDGFRA overexpression, and prolonged survival, and IDH wild-type (IDH wt) tumors exhibiting EGFR amplification, PTEN loss, and unfavorable disease outcome. Furthermore, global expression profiling revealed three robust molecular subclasses within lower-grade diffuse astrocytic gliomas, two of which were predominantly IDH mt and one almost entirely IDH wt. IDH mt subclasses were distinguished from each other on the basis of TP53 mutations, DNA copy number abnormalities, and links to distinct stages of neurogenesis in the subventricular zone (SVZ). This latter finding implicates discrete pools of neuroglial progenitors as cells of origin for the different subclasses of IDH mt tumors. In summary, we have elucidated molecularly distinct subclasses of lower-grade diffuse astrocytic glioma that dictate clinical behavior and demonstrate fundamental associations with both IDH mutational status and neuroglial developmental stage.\"\n", "!Series_overall_design\t\"80 tumor samples, one normal tissue sample (brain)\"\n", "\n", "Sample Characteristics Dictionary:\n", "{0: ['tumor type: normal brain', 'tumor type: diffuse astrocytic glioma'], 1: [nan, 'who grade: III', 'who grade: II'], 2: [nan, 'subclass: PG', 'subclass: NB', 'subclass: EPL'], 3: [nan, 'idh mut status: wt', 'idh mut status: mut'], 4: [nan, 'pten methylation: U', 'pten methylation: M', 'pten methylation: NA'], 5: [nan, 'cdkn2a methylation: U', 'cdkn2a methylation: NA', 'cdkn2a methylation: M'], 6: [nan, 'tp53 seq: mut', 'tp53 seq: wt', 'tp53 seq: NA'], 7: [nan, 'pten del: No', 'pten del: NA', 'pten del: Yes'], 8: [nan, 'pdgfra ihc: -', 'pdgfra ihc: +'], 9: [nan, 'p53 ihc: +', 'p53 ihc: -'], 10: [nan, 'p-pras40 ihc: +', 'p-pras40 ihc: -', 'p-pras40 ihc: NA'], 11: [nan, 'egfr amp: No', 'egfr amp: Yes', 'egfr amp: NA']}\n" ] } ], "source": [ "# 1. Let's first list the directory contents to understand what files are available\n", "import os\n", "\n", "print(\"Files in the cohort directory:\")\n", "files = os.listdir(in_cohort_dir)\n", "print(files)\n", "\n", "# Adapt file identification to handle different naming patterns\n", "soft_files = [f for f in files if 'soft' in f.lower() or '.soft' in f.lower() or '_soft' in f.lower()]\n", "matrix_files = [f for f in files if 'matrix' in f.lower() or '.matrix' in f.lower() or '_matrix' in f.lower()]\n", "\n", "# If no files with these patterns are found, look for alternative file types\n", "if not soft_files:\n", " soft_files = [f for f in files if f.endswith('.txt') or f.endswith('.gz')]\n", "if not matrix_files:\n", " matrix_files = [f for f in files if f.endswith('.txt') or f.endswith('.gz')]\n", "\n", "print(\"Identified SOFT files:\", soft_files)\n", "print(\"Identified matrix files:\", matrix_files)\n", "\n", "# Use the first files found, if any\n", "if len(soft_files) > 0 and len(matrix_files) > 0:\n", " soft_file = os.path.join(in_cohort_dir, soft_files[0])\n", " matrix_file = os.path.join(in_cohort_dir, matrix_files[0])\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(\"\\nBackground Information:\")\n", " print(background_info)\n", " print(\"\\nSample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", "else:\n", " print(\"No appropriate files found in the directory.\")\n" ] }, { "cell_type": "markdown", "id": "e06ee23a", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "a3df57fe", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:39:41.441662Z", "iopub.status.busy": "2025-03-25T07:39:41.441555Z", "iopub.status.idle": "2025-03-25T07:39:41.505675Z", "shell.execute_reply": "2025-03-25T07:39:41.505374Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of processed clinical data:\n", "{1: [nan]}\n", "Saved clinical data to ../../output/preprocess/lower_grade_glioma_and_glioblastoma/clinical_data/GSE35158.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Looking at the background information, this dataset mentions \"global transcriptional analysis\"\n", "# which indicates gene expression data is available\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "\n", "# 2.1 Trait Data Availability\n", "# Based on the sample characteristics, we can use 'who grade' at index 1 to distinguish between\n", "# lower-grade glioma (grade II) and glioblastoma (grade III)\n", "trait_row = 1 # 'who grade: III', 'who grade: II'\n", "\n", "# Age data is not available in the sample characteristics\n", "age_row = None\n", "\n", "# Gender data is not available in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert WHO grade to binary trait: 1 for glioblastoma (Grade III), 0 for lower-grade glioma (Grade II)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract the value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert WHO grade to binary\n", " if value == 'III':\n", " return 1 # glioblastoma\n", " elif value == 'II':\n", " return 0 # lower-grade glioma\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Placeholder function for age conversion, not used in this dataset\"\"\"\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Placeholder function for gender conversion, not used in this dataset\"\"\"\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine if trait data is available\n", "is_trait_available = trait_row is not None\n", "\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. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # Create DataFrame from the sample characteristics dictionary provided in previous step output\n", " # The sample characteristics dictionary format is:\n", " # {0: ['tumor type: normal brain', 'tumor type: diffuse astrocytic glioma'], \n", " # 1: [nan, 'who grade: III', 'who grade: II'], ...}\n", " \n", " # First, let's load the GEO series matrix file to get the sample IDs and characteristics\n", " sample_ids = []\n", " sample_chars = []\n", " \n", " with gzip.open(f\"{in_cohort_dir}/GSE35158_series_matrix.txt.gz\", 'rt') as file:\n", " for line in file:\n", " if line.startswith(\"!Sample_geo_accession\"):\n", " sample_ids = line.strip().split('\\t')[1:]\n", " elif line.startswith(\"!Sample_characteristics_ch1\"):\n", " chars = line.strip().split('\\t')[1:]\n", " sample_chars.append(chars)\n", " \n", " # Create a DataFrame with samples as rows and characteristic types as columns\n", " # Transpose the data so samples are rows and characteristic types are columns\n", " clinical_df = pd.DataFrame(index=sample_ids)\n", " \n", " # From the previous output, we know the trait info is at row 1 in sample_characteristics dictionary\n", " if len(sample_chars) > trait_row:\n", " clinical_df[trait_row] = sample_chars[trait_row]\n", " \n", " # Extract clinical features using geo_select_clinical_features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_df,\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 processed clinical data:\")\n", " print(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\"Saved clinical data to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "eabe1c22", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "8c9dd91e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:39:41.506726Z", "iopub.status.busy": "2025-03-25T07:39:41.506619Z", "iopub.status.idle": "2025-03-25T07:39:41.654244Z", "shell.execute_reply": "2025-03-25T07:39:41.653850Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First 20 gene/probe identifiers:\n", "Index(['ILMN_1651209', 'ILMN_1651228', 'ILMN_1651229', 'ILMN_1651235',\n", " 'ILMN_1651236', 'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651254',\n", " 'ILMN_1651262', 'ILMN_1651268', 'ILMN_1651278', 'ILMN_1651285',\n", " 'ILMN_1651292', 'ILMN_1651303', 'ILMN_1651315', 'ILMN_1651316',\n", " 'ILMN_1651336', 'ILMN_1651343', 'ILMN_1651346', 'ILMN_1651347'],\n", " dtype='object', name='ID')\n", "\n", "Gene expression data shape: (20792, 81)\n" ] } ], "source": [ "# Use the helper function to get the proper file paths\n", "soft_file_path, matrix_file_path = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# Extract gene expression data\n", "try:\n", " gene_data = get_genetic_data(matrix_file_path)\n", " \n", " # Print the first 20 row IDs (gene or probe identifiers)\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20])\n", " \n", " # Print shape to understand the dataset dimensions\n", " print(f\"\\nGene expression data shape: {gene_data.shape}\")\n", " \n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n" ] }, { "cell_type": "markdown", "id": "882147a0", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "c8369eef", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:39:41.655542Z", "iopub.status.busy": "2025-03-25T07:39:41.655416Z", "iopub.status.idle": "2025-03-25T07:39:41.657370Z", "shell.execute_reply": "2025-03-25T07:39:41.657039Z" } }, "outputs": [], "source": [ "# Looking at the identifiers, these are ILMN_ prefixed IDs which are Illumina microarray probe IDs\n", "# These are not human gene symbols and will need to be mapped to gene symbols\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "b1d3c8bd", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "c0d2ebbe", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:39:41.658842Z", "iopub.status.busy": "2025-03-25T07:39:41.658737Z", "iopub.status.idle": "2025-03-25T07:39:45.947269Z", "shell.execute_reply": "2025-03-25T07:39:45.946875Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Sample of gene expression data (first 5 rows, first 5 columns):\n", " GSM864095 GSM864096 GSM864097 GSM864098 GSM864099\n", "ID \n", "ILMN_1651209 7.08126 7.02804 7.04731 6.89578 7.54783\n", "ILMN_1651228 12.26640 11.81630 12.25260 12.76770 12.55510\n", "ILMN_1651229 11.51870 11.18470 10.52200 10.83890 10.72500\n", "ILMN_1651235 11.06620 11.11270 12.09500 12.04060 11.62470\n", "ILMN_1651236 6.71231 6.80484 7.71360 6.76902 6.83577\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Platform information:\n", "!Series_title = Expression profiling of lower-grade diffuse astrocytic glioma\n", "!Platform_title = Illumina HumanHT-12 WG-DASL V4.0 R2 expression beadchip\n", "#Definition = Gene description from the source\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n", "!Sample_description = FFPE material/DASL processed\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation columns:\n", "['ID', 'Transcript', 'Species', 'Source', 'Search_Key', 'ILMN_Gene', 'Source_Reference_ID', 'RefSeq_ID', 'Entrez_Gene_ID', 'GI', 'Accession', 'Symbol', 'Protein_Product', 'Array_Address_Id', 'Probe_Type', 'Probe_Start', 'SEQUENCE', 'Chromosome', 'Probe_Chr_Orientation', 'Probe_Coordinates', 'Cytoband', 'Definition', 'Ontology_Component', 'Ontology_Process', 'Ontology_Function', 'Synonyms', 'Obsolete_Probe_Id', 'GB_ACC']\n", "\n", "Gene annotation preview:\n", "{'ID': ['ILMN_3166687', 'ILMN_3165566', 'ILMN_3164811', 'ILMN_3165363', 'ILMN_3166511'], 'Transcript': ['ILMN_333737', 'ILMN_333646', 'ILMN_333584', 'ILMN_333628', 'ILMN_333719'], 'Species': ['ILMN Controls', 'ILMN Controls', 'ILMN Controls', 'ILMN Controls', 'ILMN Controls'], 'Source': ['ILMN_Controls', 'ILMN_Controls', 'ILMN_Controls', 'ILMN_Controls', 'ILMN_Controls'], 'Search_Key': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'ILMN_Gene': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'Source_Reference_ID': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': ['DQ516750', 'DQ883654', 'DQ668364', 'DQ516785', 'DQ854995'], 'Symbol': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'Protein_Product': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5270161.0, 4260594.0, 7610424.0, 5260356.0, 2030196.0], 'Probe_Type': ['S', 'S', 'S', 'S', 'S'], 'Probe_Start': [12.0, 224.0, 868.0, 873.0, 130.0], 'SEQUENCE': ['CCCATGTGTCCAATTCTGAATATCTTTCCAGCTAAGTGCTTCTGCCCACC', 'GGATTAACTGCTGTGGTGTGTCATACTCGGCTACCTCCTGGTTTGGCGTC', 'GACCACGCCTTGTAATCGTATGACACGCGCTTGACACGACTGAATCCAGC', 'CTGCAATGCCATTAACAACCTTAGCACGGTATTTCCAGTAGCTGGTGAGC', 'CGTGCAGACAGGGATCGTAAGGCGATCCAGCCGGTATACCTTAGTCACAT'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': ['Methanocaldococcus jannaschii spike-in control MJ-500-33 genomic sequence', 'Synthetic construct clone NISTag13 external RNA control sequence', 'Synthetic construct clone TagJ microarray control', 'Methanocaldococcus jannaschii spike-in control MJ-1000-68 genomic sequence', 'Synthetic construct clone AG006.1100 external RNA control sequence'], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': ['DQ516750', 'DQ883654', 'DQ668364', 'DQ516785', 'DQ854995']}\n", "\n", "Matching rows in annotation for sample IDs: 820\n", "\n", "Potential gene symbol columns: ['ILMN_Gene', 'Entrez_Gene_ID', 'Symbol']\n", "\n", "Is this dataset likely to contain gene expression data? True\n" ] } ], "source": [ "# 1. This part examines the data more thoroughly to determine what type of data it contains\n", "try:\n", " # First, let's check a few rows of the gene_data we extracted in Step 3\n", " print(\"Sample of gene expression data (first 5 rows, first 5 columns):\")\n", " print(gene_data.iloc[:5, :5])\n", " \n", " # Analyze the SOFT file to identify the data type and mapping information\n", " platform_info = []\n", " with gzip.open(soft_file_path, 'rt', encoding='latin-1') as f:\n", " for line in f:\n", " if line.startswith(\"!Platform_title\") or line.startswith(\"!Series_title\") or \"description\" in line.lower():\n", " platform_info.append(line.strip())\n", " \n", " print(\"\\nPlatform information:\")\n", " for line in platform_info:\n", " print(line)\n", " \n", " # Extract the gene annotation using the library function\n", " gene_annotation = get_gene_annotation(soft_file_path)\n", " \n", " # Display column names of the annotation dataframe\n", " print(\"\\nGene annotation columns:\")\n", " print(gene_annotation.columns.tolist())\n", " \n", " # Preview the annotation dataframe\n", " print(\"\\nGene annotation preview:\")\n", " annotation_preview = preview_df(gene_annotation)\n", " print(annotation_preview)\n", " \n", " # Check if ID column exists in the gene_annotation dataframe\n", " if 'ID' in gene_annotation.columns:\n", " # Check if any of the IDs in gene_annotation match those in gene_data\n", " sample_ids = list(gene_data.index[:10])\n", " matching_rows = gene_annotation[gene_annotation['ID'].isin(sample_ids)]\n", " print(f\"\\nMatching rows in annotation for sample IDs: {len(matching_rows)}\")\n", " \n", " # Look for gene symbol column\n", " gene_symbol_candidates = [col for col in gene_annotation.columns if 'gene' in col.lower() or 'symbol' in col.lower() or 'name' in col.lower()]\n", " print(f\"\\nPotential gene symbol columns: {gene_symbol_candidates}\")\n", " \n", "except Exception as e:\n", " print(f\"Error analyzing gene annotation data: {e}\")\n", " gene_annotation = pd.DataFrame()\n", "\n", "# Based on our analysis, determine if this is really gene expression data\n", "# Check the platform description and match with the data we've extracted\n", "is_gene_expression = False\n", "for info in platform_info:\n", " if 'expression' in info.lower() or 'transcript' in info.lower() or 'mrna' in info.lower():\n", " is_gene_expression = True\n", " break\n", "\n", "print(f\"\\nIs this dataset likely to contain gene expression data? {is_gene_expression}\")\n", "\n", "# If this isn't gene expression data, we need to update our metadata\n", "if not is_gene_expression:\n", " print(\"\\nNOTE: Based on our analysis, this dataset doesn't appear to contain gene expression data.\")\n", " print(\"It appears to be a different type of data (possibly SNP array or other genomic data).\")\n", " # Update is_gene_available for metadata\n", " is_gene_available = False\n", " \n", " # Save the updated metadata\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" ] }, { "cell_type": "markdown", "id": "b6acc2b2", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "478b48f6", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:39:45.949101Z", "iopub.status.busy": "2025-03-25T07:39:45.948980Z", "iopub.status.idle": "2025-03-25T07:39:46.937887Z", "shell.execute_reply": "2025-03-25T07:39:46.937496Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of gene mapping:\n", " ID Gene\n", "0 ILMN_3166687 ERCC-00162\n", "1 ILMN_3165566 ERCC-00071\n", "2 ILMN_3164811 ERCC-00009\n", "3 ILMN_3165363 ERCC-00053\n", "4 ILMN_3166511 ERCC-00144\n", "Total mappings: 29377\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "After mapping and normalization:\n", "Number of genes: 19449\n", "Number of samples: 81\n", "First 5 gene symbols:\n", "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1'], dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved gene expression data to ../../output/preprocess/lower_grade_glioma_and_glioblastoma/gene_data/GSE35158.csv\n" ] } ], "source": [ "# 1. Decide which columns to use for mapping\n", "# From previous steps, we observed that:\n", "# - The gene expression data uses 'ILMN_*' identifiers which are Illumina probe IDs\n", "# - The gene annotation data has an 'ID' column with these same identifiers\n", "# - The 'Symbol' column appears to contain gene symbols\n", "\n", "prob_col = 'ID' # Probe identifier column\n", "gene_col = 'Symbol' # Gene symbol column\n", "\n", "# 2. Create gene mapping dataframe\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "\n", "# Display the first few rows of the mapping\n", "print(\"Preview of gene mapping:\")\n", "print(gene_mapping.head())\n", "print(f\"Total mappings: {len(gene_mapping)}\")\n", "\n", "# 3. Apply the gene mapping to convert probe-level data to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "# Normalize gene symbols (standardize capitalization, handle synonyms)\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "\n", "# Display the results\n", "print(\"\\nAfter mapping and normalization:\")\n", "print(f\"Number of genes: {gene_data.shape[0]}\")\n", "print(f\"Number of samples: {gene_data.shape[1]}\")\n", "print(\"First 5 gene symbols:\")\n", "print(gene_data.index[:5])\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\"Saved gene expression data to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "13d2267e", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "4d9341db", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:39:46.940268Z", "iopub.status.busy": "2025-03-25T07:39:46.940108Z", "iopub.status.idle": "2025-03-25T07:39:58.659738Z", "shell.execute_reply": "2025-03-25T07:39:58.659350Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape after normalization: (19449, 81)\n", "First few gene symbols after normalization: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/lower_grade_glioma_and_glioblastoma/gene_data/GSE35158.csv\n", "Loaded clinical data:\n", " 1\n", "lower_grade_glioma_and_glioblastoma NaN\n", "Transposed clinical data to correct format:\n", " lower_grade_glioma_and_glioblastoma\n", "1 NaN\n", "Number of common samples between clinical and genetic data: 0\n", "WARNING: No matching sample IDs between clinical and genetic data.\n", "Clinical data index: ['1']\n", "Gene data columns: ['GSM864095', 'GSM864096', 'GSM864097', 'GSM864098', 'GSM864099', '...']\n", "Extracted 81 GSM IDs from gene data.\n", "Created new clinical data with matching sample IDs:\n", " lower_grade_glioma_and_glioblastoma\n", "GSM864095 1\n", "GSM864096 1\n", "GSM864097 1\n", "GSM864098 1\n", "GSM864099 1\n", "Gene data shape for linking (samples as rows): (81, 19449)\n", "Linked data shape: (81, 19450)\n", "Linked data preview (first 5 columns):\n", " lower_grade_glioma_and_glioblastoma A1BG A1BG-AS1 A1CF \\\n", "GSM864095 1 7.26299 7.87862 7.00445 \n", "GSM864096 1 7.33984 9.12976 7.25328 \n", "GSM864097 1 7.05604 9.42258 6.81456 \n", "GSM864098 1 7.35527 10.50850 7.24100 \n", "GSM864099 1 7.29422 6.65241 6.83460 \n", "\n", " A2M \n", "GSM864095 12.6632 \n", "GSM864096 12.1218 \n", "GSM864097 12.2176 \n", "GSM864098 12.6828 \n", "GSM864099 12.4022 \n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape after handling missing values: (81, 19450)\n", "For the feature 'lower_grade_glioma_and_glioblastoma', the least common label is '1' with 14 occurrences. This represents 17.28% of the dataset.\n", "The distribution of the feature 'lower_grade_glioma_and_glioblastoma' in this dataset is fine.\n", "\n", "Is trait biased: False\n", "Data quality check result: Usable\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/lower_grade_glioma_and_glioblastoma/GSE35158.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the obtained gene expression data\n", "try:\n", " # Now let's normalize the gene data using the provided function\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", " print(f\"First few gene symbols after normalization: {list(normalized_gene_data.index[:10])}\")\n", " \n", " # Save the normalized gene data\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " normalized_gene_data.to_csv(out_gene_data_file)\n", " print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "except Exception as e:\n", " print(f\"Error in gene normalization: {e}\")\n", " # If normalization fails, use the original gene data\n", " normalized_gene_data = gene_data\n", " print(\"Using original gene data without normalization\")\n", "\n", "# 2. Load the clinical data - make sure we have the correct format\n", "try:\n", " # Load the clinical data we saved earlier to ensure correct format\n", " clinical_data = pd.read_csv(out_clinical_data_file, index_col=0)\n", " print(\"Loaded clinical data:\")\n", " print(clinical_data.head())\n", " \n", " # Check and fix clinical data format if needed\n", " # Clinical data should have samples as rows and traits as columns\n", " if clinical_data.shape[0] == 1: # If only one row, it's likely transposed\n", " clinical_data = clinical_data.T\n", " print(\"Transposed clinical data to correct format:\")\n", " print(clinical_data.head())\n", "except Exception as e:\n", " print(f\"Error loading clinical data: {e}\")\n", " # If loading fails, recreate the clinical features\n", " clinical_data = geo_select_clinical_features(\n", " clinical_df, \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", " ).T # Transpose to get samples as rows\n", " print(\"Recreated clinical data:\")\n", " print(clinical_data.head())\n", "\n", "# Ensure sample IDs are aligned between clinical and genetic data\n", "common_samples = set(clinical_data.index).intersection(normalized_gene_data.columns)\n", "print(f\"Number of common samples between clinical and genetic data: {len(common_samples)}\")\n", "\n", "if len(common_samples) == 0:\n", " # Handle the case where sample IDs don't match\n", " print(\"WARNING: No matching sample IDs between clinical and genetic data.\")\n", " print(\"Clinical data index:\", clinical_data.index.tolist())\n", " print(\"Gene data columns:\", list(normalized_gene_data.columns[:5]) + [\"...\"])\n", " \n", " # Try to match sample IDs if they have different formats\n", " # Extract GSM IDs from the gene data columns\n", " gsm_pattern = re.compile(r'GSM\\d+')\n", " gene_samples = []\n", " for col in normalized_gene_data.columns:\n", " match = gsm_pattern.search(str(col))\n", " if match:\n", " gene_samples.append(match.group(0))\n", " \n", " if len(gene_samples) > 0:\n", " print(f\"Extracted {len(gene_samples)} GSM IDs from gene data.\")\n", " normalized_gene_data.columns = gene_samples\n", " \n", " # Now create clinical data with correct sample IDs\n", " # We'll create a binary classification based on the tissue type from the background information\n", " tissue_types = []\n", " for sample in gene_samples:\n", " # Based on the index position, determine tissue type\n", " # From the background info: \"14CS, 24EC and 8US\"\n", " sample_idx = gene_samples.index(sample)\n", " if sample_idx < 14:\n", " tissue_types.append(1) # Carcinosarcoma (CS)\n", " else:\n", " tissue_types.append(0) # Either EC or US\n", " \n", " clinical_data = pd.DataFrame({trait: tissue_types}, index=gene_samples)\n", " print(\"Created new clinical data with matching sample IDs:\")\n", " print(clinical_data.head())\n", "\n", "# 3. Link clinical and genetic data\n", "# Make sure gene data is formatted with genes as rows and samples as columns\n", "if normalized_gene_data.index.name != 'Gene':\n", " normalized_gene_data.index.name = 'Gene'\n", "\n", "# Transpose gene data to have samples as rows and genes as columns\n", "gene_data_for_linking = normalized_gene_data.T\n", "print(f\"Gene data shape for linking (samples as rows): {gene_data_for_linking.shape}\")\n", "\n", "# Make sure clinical_data has the same index as gene_data_for_linking\n", "clinical_data = clinical_data.loc[clinical_data.index.isin(gene_data_for_linking.index)]\n", "gene_data_for_linking = gene_data_for_linking.loc[gene_data_for_linking.index.isin(clinical_data.index)]\n", "\n", "# Now link by concatenating horizontally\n", "linked_data = pd.concat([clinical_data, gene_data_for_linking], axis=1)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(\"Linked data preview (first 5 columns):\")\n", "sample_cols = [trait] + list(linked_data.columns[1:5]) if len(linked_data.columns) > 5 else list(linked_data.columns)\n", "print(linked_data[sample_cols].head())\n", "\n", "# 4. 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", "# Check if we still have data\n", "if linked_data.shape[0] == 0 or linked_data.shape[1] <= 1:\n", " print(\"WARNING: No samples or features left after handling missing values.\")\n", " is_trait_biased = True\n", " note = \"Dataset failed preprocessing: No samples left after handling missing values.\"\n", "else:\n", " # 5. Determine whether the trait and demographic features are biased\n", " is_trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " print(f\"Is trait biased: {is_trait_biased}\")\n", " note = \"This dataset contains gene expression data from uterine corpus tissues, comparing carcinosarcoma with endometrioid adenocarcinoma and sarcoma.\"\n", "\n", "# 6. Conduct quality check and save the cohort information\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True, \n", " cohort=cohort, \n", " info_path=json_path, \n", " is_gene_available=True, \n", " is_trait_available=True,\n", " is_biased=is_trait_biased, \n", " df=linked_data,\n", " note=note\n", ")\n", "\n", "# 7. Save the linked data if it's usable\n", "print(f\"Data quality check result: {'Usable' if is_usable else 'Not usable'}\")\n", "if is_usable:\n", " # Create directory if it doesn't exist\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(f\"Data not saved due to 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 }