{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "ae8c2087", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:07:27.162304Z", "iopub.status.busy": "2025-03-25T05:07:27.162201Z", "iopub.status.idle": "2025-03-25T05:07:27.323727Z", "shell.execute_reply": "2025-03-25T05:07:27.323384Z" } }, "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 = \"X-Linked_Lymphoproliferative_Syndrome\"\n", "cohort = \"GSE211445\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/X-Linked_Lymphoproliferative_Syndrome\"\n", "in_cohort_dir = \"../../input/GEO/X-Linked_Lymphoproliferative_Syndrome/GSE211445\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/X-Linked_Lymphoproliferative_Syndrome/GSE211445.csv\"\n", "out_gene_data_file = \"../../output/preprocess/X-Linked_Lymphoproliferative_Syndrome/gene_data/GSE211445.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/X-Linked_Lymphoproliferative_Syndrome/clinical_data/GSE211445.csv\"\n", "json_path = \"../../output/preprocess/X-Linked_Lymphoproliferative_Syndrome/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "4ed64f0c", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "f9a54bf1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:07:27.325201Z", "iopub.status.busy": "2025-03-25T05:07:27.325054Z", "iopub.status.idle": "2025-03-25T05:07:27.425711Z", "shell.execute_reply": "2025-03-25T05:07:27.425408Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the cohort directory:\n", "['GSE211445-GPL10558_series_matrix.txt.gz', 'GSE211445_family.soft.gz']\n", "Identified SOFT files: ['GSE211445_family.soft.gz']\n", "Identified matrix files: ['GSE211445-GPL10558_series_matrix.txt.gz']\n", "\n", "Background Information:\n", "!Series_title\t\"C99R mutation in IRF4 drives a novel gain of function binding and gene upregulation in classical Hodgkin lymphoma\"\n", "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n", "!Series_overall_design\t\"Refer to individual Series\"\n", "\n", "Sample Characteristics Dictionary:\n", "{0: ['cell line: BJAB'], 1: ['group: Control 0hrs', 'group: Control 6hrs', 'group: Control 24hrs', 'group: Control 48hrs', 'group: IRF4WT 0hrs', 'group: IRF4WT 6hrs', 'group: IRF4WT 24hrs', 'group: IRF4WT 48hrs', 'group: IRF4C99R 0hrs', 'group: IRF4C99R 6hrs', 'group: IRF4C99R 24hrs', 'group: IRF4C99R 48hrs']}\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": "45e4ba79", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "b7cbbc77", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:07:27.426827Z", "iopub.status.busy": "2025-03-25T05:07:27.426715Z", "iopub.status.idle": "2025-03-25T05:07:27.433354Z", "shell.execute_reply": "2025-03-25T05:07:27.433070Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data preview: {'GSM6505368': [0.0], 'GSM6505369': [0.0], 'GSM6505370': [0.0], 'GSM6505371': [0.0], 'GSM6505372': [0.0], 'GSM6505373': [0.0], 'GSM6505374': [0.0], 'GSM6505375': [0.0], 'GSM6505376': [1.0], 'GSM6505377': [1.0], 'GSM6505378': [1.0], 'GSM6505379': [1.0], 'GSM6505380': [0.0], 'GSM6505381': [0.0], 'GSM6505382': [0.0], 'GSM6505383': [0.0], 'GSM6505384': [0.0], 'GSM6505385': [0.0], 'GSM6505386': [0.0], 'GSM6505387': [0.0], 'GSM6505388': [1.0], 'GSM6505389': [1.0], 'GSM6505390': [1.0], 'GSM6505391': [1.0]}\n", "Clinical data saved to ../../output/preprocess/X-Linked_Lymphoproliferative_Syndrome/clinical_data/GSE211445.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background information and available files, this dataset likely contains gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# Based on the sample characteristics dictionary:\n", "\n", "# For trait: The group information in row 1 contains treatment information (IRF4WT vs IRF4C99R vs Control)\n", "# which can be used to derive the trait (X-linked lymphoproliferative syndrome)\n", "trait_row = 1\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", "def convert_trait(value):\n", " \"\"\"\n", " Convert the group information to binary trait data.\n", " IRF4C99R mutation is associated with X-Linked Lymphoproliferative Syndrome, \n", " so samples with IRF4C99R will be coded as 1, others as 0.\n", " \"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after the colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Convert based on the presence of IRF4C99R\n", " if \"IRF4C99R\" in value:\n", " return 1 # Disease/mutation\n", " elif \"Control\" in value or \"IRF4WT\" in value:\n", " return 0 # Control or wild type\n", " else:\n", " return None # Unknown or not applicable\n", "\n", "# Since age and gender are not available, creating placeholder functions\n", "def convert_age(value):\n", " return None\n", "\n", "def convert_gender(value):\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait availability\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", " # Extract clinical features\n", " clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data, # Using the clinical_data from previous steps\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 dataframe\n", " preview = preview_df(clinical_df)\n", " print(\"Clinical data preview:\", preview)\n", " \n", " # Save clinical data to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_df.to_csv(out_clinical_data_file, index=True)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "76d1b7ed", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "84716d39", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:07:27.434369Z", "iopub.status.busy": "2025-03-25T05:07:27.434264Z", "iopub.status.idle": "2025-03-25T05:07:27.553107Z", "shell.execute_reply": "2025-03-25T05:07:27.552742Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First 20 gene/probe identifiers:\n", "Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209',\n", " 'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229',\n", " 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236',\n", " 'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253',\n", " 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262'],\n", " dtype='object', name='ID')\n", "\n", "Gene expression data shape: (47323, 24)\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": "63554675", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "afdc17b4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:07:27.554309Z", "iopub.status.busy": "2025-03-25T05:07:27.554197Z", "iopub.status.idle": "2025-03-25T05:07:27.556034Z", "shell.execute_reply": "2025-03-25T05:07:27.555773Z" } }, "outputs": [], "source": [ "# The identifiers beginning with \"ILMN_\" indicate these are Illumina BeadArray probe IDs,\n", "# not standard human gene symbols. These probe IDs need to be mapped to their corresponding\n", "# gene symbols for biological interpretation and analysis.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "b2f2449c", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "276d8d38", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:07:27.557087Z", "iopub.status.busy": "2025-03-25T05:07:27.556982Z", "iopub.status.idle": "2025-03-25T05:07:31.535732Z", "shell.execute_reply": "2025-03-25T05:07:31.535404Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Sample of gene expression data (first 5 rows, first 5 columns):\n", " GSM6505368 GSM6505369 GSM6505370 GSM6505371 GSM6505372\n", "ID \n", "ILMN_1343291 60335.4400 56748.2800 54508.7400 53976.1000 65779.4800\n", "ILMN_1343295 28342.9800 27970.3300 27209.1000 20349.3500 32162.1300\n", "ILMN_1651199 140.8024 120.8438 121.3026 96.2961 133.4001\n", "ILMN_1651209 185.5267 167.3002 169.0416 167.9951 186.3865\n", "ILMN_1651210 154.0286 129.2618 137.3497 128.1371 136.0509\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Platform information:\n", "!Series_title = C99R mutation in IRF4 drives a novel gain of function binding and gene upregulation in classical Hodgkin lymphoma\n", "!Platform_title = Illumina HumanHT-12 V4.0 expression beadchip\n", "!Platform_description = The HumanHT-12 v4 Expression BeadChip provides high throughput processing of 12 samples per BeadChip without the need for expensive, specialized automation. The BeadChip is designed to support flexible usage across a wide-spectrum of experiments.\n", "!Platform_description =\n", "!Platform_description = The updated content on the HumanHT-12 v4 Expression BeadChips provides more biologically meaningful results through genome-wide transcriptional coverage of well-characterized genes, gene candidates, and splice variants.\n", "!Platform_description =\n", "!Platform_description = Each array on the HumanHT-12 v4 Expression BeadChip targets more than 31,000 annotated genes with more than 47,000 probes derived from the National Center for Biotechnology Information Reference Sequence (NCBI) RefSeq Release 38 (November 7, 2009) and other sources.\n", "!Platform_description =\n", "!Platform_description = Please use the GEO Data Submission Report Plug-in v1.0 for Gene Expression which may be downloaded from https://icom.illumina.com/icom/software.ilmn?id=234 to format the normalized and raw data. These should be submitted as part of a GEOarchive. Instructions for assembling a GEOarchive may be found at http://www.ncbi.nlm.nih.gov/projects/geo/info/spreadsheet.html\n", "!Platform_description =\n", "!Platform_description = October 11, 2012: annotation table updated with HumanHT-12_V4_0_R2_15002873_B.txt\n", "#Definition = Gene description from the source\n", "!Platform_title = Illumina HiSeq 2000 (Homo sapiens)\n", "!Platform_title = AB SOLiD 4 System (Homo sapiens)\n", "!Sample_description = SM_1_sRL_CGATGT\n", "!Sample_description = SM_2_sRL_TGACCA\n", "!Sample_description = SM_3_sRL_ACAGTG\n", "!Sample_description = SM_4_sRL_GCCAAT\n", "!Sample_description = SM_5_sRL_CAGATC\n", "!Sample_description = SM_6_sRL_CTTGTA\n", "!Sample_description = SM_7_sRL_AGTCAA\n", "!Sample_description = SM_8_sRL_AGTTCC\n", "!Sample_description = SM_9_sRL_ATGTCA\n", "!Sample_description = SM_10_sRL_CCGTCC\n", "!Sample_description = SM_11_sRL_GTCCGC\n", "!Sample_description = SM_12_sRL_GTGAAA\n", "!Sample_description = SM_13_sRL_CGATGT\n", "!Sample_description = SM_14_sRL_TGACCA\n", "!Sample_description = SM_17_sRL_ACAGTG\n", "!Sample_description = SM_18_sRL_GCCAAT\n", "!Sample_description = SM_21_sRL_CAGATC\n", "!Sample_description = SM_22_sRL_CTTGTA\n", "!Sample_description = SM_23_sRL_AGTCAA\n", "!Sample_description = SM_24_sRL_AGTTCC\n", "!Sample_description = SM_25_sRL_ATGTCA\n", "!Sample_description = SM_26_sRL_CCGTCC\n", "!Sample_description = SM_27_sRL_GTCCGC\n", "!Sample_description = SM_28_sRL_GTGAAA\n", "!Sample_description = BJK0h1\n", "!Sample_description = BJK6hD1\n", "!Sample_description = BJK24hD1\n", "!Sample_description = BJK48hD1\n", "!Sample_description = BJWT0h1\n", "!Sample_description = BJWT6hD1\n", "!Sample_description = BJWT24hD1\n", "!Sample_description = BJWT48hD1\n", "!Sample_description = BJ1x0h1\n", "!Sample_description = BJ1x6hD1\n", "!Sample_description = BJ1x24hD1\n", "!Sample_description = BJ1x48hD1\n", "!Sample_description = BJK0h2\n", "!Sample_description = BJK6hD2\n", "!Sample_description = BJK24hD2\n", "!Sample_description = BJK48hD2\n", "!Sample_description = BJWT0h2\n", "!Sample_description = BJWT6hD2\n", "!Sample_description = BJWT24hD2\n", "!Sample_description = BJWT48hD2\n", "!Sample_description = BJ1x0h2\n", "!Sample_description = BJ1x6hD2\n", "!Sample_description = BJ1x24hD2\n", "!Sample_description = BJ1x48hD2\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation columns:\n", "['ID', 'Species', 'Source', 'Search_Key', 'Transcript', 'ILMN_Gene', 'Source_Reference_ID', 'RefSeq_ID', 'Unigene_ID', 'Entrez_Gene_ID', 'GI', 'Accession', 'Symbol', 'Protein_Product', 'Probe_Id', '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_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Species': [nan, nan, nan, nan, nan], 'Source': [nan, nan, nan, nan, nan], 'Search_Key': [nan, nan, nan, nan, nan], 'Transcript': [nan, nan, nan, nan, nan], 'ILMN_Gene': [nan, nan, nan, nan, nan], 'Source_Reference_ID': [nan, nan, nan, nan, nan], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Unigene_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': [nan, nan, nan, nan, nan], 'Symbol': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB'], 'Protein_Product': [nan, nan, nan, nan, 'thrB'], 'Probe_Id': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5090180.0, 6510136.0, 7560739.0, 1450438.0, 1240647.0], 'Probe_Type': [nan, nan, nan, nan, nan], 'Probe_Start': [nan, nan, nan, nan, nan], 'SEQUENCE': ['GAATAAAGAACAATCTGCTGATGATCCCTCCGTGGATCTGATTCGTGTAA', 'CCATGTGATACGAGGGCGCGTAGTTTGCATTATCGTTTTTATCGTTTCAA', 'CCGACAGATGTATGTAAGGCCAACGTGCTCAAATCTTCATACAGAAAGAT', 'TCTGTCACTGTCAGGAAAGTGGTAAAACTGCAACTCAATTACTGCAATGC', 'CTTGTGCCTGAGCTGTCAAAAGTAGAGCACGTCGCCGAGATGAAGGGCGC'], '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': [nan, nan, nan, nan, nan], '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': [nan, nan, nan, nan, nan]}\n", "\n", "Matching rows in annotation for sample IDs: 250\n", "\n", "Potential gene symbol columns: ['ILMN_Gene', 'Unigene_ID', '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": "ed2cdb6f", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "7eaedc12", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:07:31.536996Z", "iopub.status.busy": "2025-03-25T05:07:31.536871Z", "iopub.status.idle": "2025-03-25T05:07:31.959856Z", "shell.execute_reply": "2025-03-25T05:07:31.959481Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping dataframe (first 5 rows):\n", " ID Gene\n", "0 ILMN_1343048 phage_lambda_genome\n", "1 ILMN_1343049 phage_lambda_genome\n", "2 ILMN_1343050 phage_lambda_genome:low\n", "3 ILMN_1343052 phage_lambda_genome:low\n", "4 ILMN_1343059 thrB\n", "Mapping dataframe shape: (44837, 2)\n", "\n", "Gene-level expression dataframe (first 5 rows, first 3 columns):\n", " GSM6505368 GSM6505369 GSM6505370\n", "Gene \n", "A1BG 358.11860 313.0659 286.89630\n", "A1CF 405.94150 395.7438 371.76720\n", "A26C3 404.48630 434.8431 426.75660\n", "A2BP1 461.89607 480.3532 434.01131\n", "A2LD1 259.27540 206.9460 203.19940\n", "Gene expression data shape after mapping: (21464, 24)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data saved to: ../../output/preprocess/X-Linked_Lymphoproliferative_Syndrome/gene_data/GSE211445.csv\n" ] } ], "source": [ "# 1. Identify which columns in gene_annotation contain probe IDs and gene symbols\n", "prob_col = 'ID' # The probe identifiers column\n", "gene_col = 'Symbol' # The gene symbols column\n", "\n", "# 2. Get the gene mapping dataframe\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "\n", "# Check the first few rows of mapping_df to verify it has what we need\n", "print(\"Gene mapping dataframe (first 5 rows):\")\n", "print(mapping_df.head())\n", "print(f\"Mapping dataframe shape: {mapping_df.shape}\")\n", "\n", "# 3. Convert probe-level measurements to gene-level expression data\n", "# This applies the gene mapping and handles many-to-many relationships\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Verify the gene-level expression data\n", "print(\"\\nGene-level expression dataframe (first 5 rows, first 3 columns):\")\n", "print(gene_data.iloc[:5, :3])\n", "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n", "\n", "# Save the processed gene 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\"\\nGene expression data saved to: {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "6a648b65", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "8937c544", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:07:31.961179Z", "iopub.status.busy": "2025-03-25T05:07:31.961049Z", "iopub.status.idle": "2025-03-25T05:07:40.357128Z", "shell.execute_reply": "2025-03-25T05:07:40.356801Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape after normalization: (20259, 24)\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/X-Linked_Lymphoproliferative_Syndrome/gene_data/GSE211445.csv\n", "Loaded clinical data:\n", " GSM6505368 GSM6505369 GSM6505370 \\\n", "X-Linked_Lymphoproliferative_Syndrome 0.0 0.0 0.0 \n", "\n", " GSM6505371 GSM6505372 GSM6505373 \\\n", "X-Linked_Lymphoproliferative_Syndrome 0.0 0.0 0.0 \n", "\n", " GSM6505374 GSM6505375 GSM6505376 \\\n", "X-Linked_Lymphoproliferative_Syndrome 0.0 0.0 1.0 \n", "\n", " GSM6505377 ... GSM6505382 \\\n", "X-Linked_Lymphoproliferative_Syndrome 1.0 ... 0.0 \n", "\n", " GSM6505383 GSM6505384 GSM6505385 \\\n", "X-Linked_Lymphoproliferative_Syndrome 0.0 0.0 0.0 \n", "\n", " GSM6505386 GSM6505387 GSM6505388 \\\n", "X-Linked_Lymphoproliferative_Syndrome 0.0 0.0 1.0 \n", "\n", " GSM6505389 GSM6505390 GSM6505391 \n", "X-Linked_Lymphoproliferative_Syndrome 1.0 1.0 1.0 \n", "\n", "[1 rows x 24 columns]\n", "Transposed clinical data to correct format:\n", " X-Linked_Lymphoproliferative_Syndrome\n", "GSM6505368 0.0\n", "GSM6505369 0.0\n", "GSM6505370 0.0\n", "GSM6505371 0.0\n", "GSM6505372 0.0\n", "Number of common samples between clinical and genetic data: 24\n", "Gene data shape for linking (samples as rows): (24, 20259)\n", "Linked data shape: (24, 20260)\n", "Linked data preview (first 5 columns):\n", " X-Linked_Lymphoproliferative_Syndrome A1BG A1BG-AS1 \\\n", "GSM6505368 0.0 358.1186 185.5517 \n", "GSM6505369 0.0 313.0659 147.8219 \n", "GSM6505370 0.0 286.8963 158.4436 \n", "GSM6505371 0.0 287.4026 139.5939 \n", "GSM6505372 0.0 298.9548 142.4706 \n", "\n", " A1CF A2M \n", "GSM6505368 405.94150 113.12230 \n", "GSM6505369 395.74380 97.67080 \n", "GSM6505370 371.76720 88.91967 \n", "GSM6505371 382.38695 88.88231 \n", "GSM6505372 395.66270 112.99410 \n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape after handling missing values: (24, 20260)\n", "For the feature 'X-Linked_Lymphoproliferative_Syndrome', the least common label is '1.0' with 8 occurrences. This represents 33.33% of the dataset.\n", "The distribution of the feature 'X-Linked_Lymphoproliferative_Syndrome' 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/X-Linked_Lymphoproliferative_Syndrome/GSE211445.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 }