{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "633b6e24", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:27:58.220636Z", "iopub.status.busy": "2025-03-25T06:27:58.220266Z", "iopub.status.idle": "2025-03-25T06:27:58.390637Z", "shell.execute_reply": "2025-03-25T06:27:58.390299Z" } }, "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 = \"Amyotrophic_Lateral_Sclerosis\"\n", "cohort = \"GSE212134\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Amyotrophic_Lateral_Sclerosis\"\n", "in_cohort_dir = \"../../input/GEO/Amyotrophic_Lateral_Sclerosis/GSE212134\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/GSE212134.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE212134.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE212134.csv\"\n", "json_path = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "a75b92b5", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "a0b60a19", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:27:58.392097Z", "iopub.status.busy": "2025-03-25T06:27:58.391943Z", "iopub.status.idle": "2025-03-25T06:27:58.467075Z", "shell.execute_reply": "2025-03-25T06:27:58.466722Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Establishing mRNA and microRNA interactions driving disease heterogeneity in Amyotrophic lateral sclerosis\"\n", "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n", "!Series_overall_design\t\"Refer to individual Series\"\n", "Sample Characteristics Dictionary:\n", "{0: ['gender: Female', 'gender: Male']}\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": "5d73a6dd", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "51fbb8de", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:27:58.468351Z", "iopub.status.busy": "2025-03-25T06:27:58.468240Z", "iopub.status.idle": "2025-03-25T06:27:58.485912Z", "shell.execute_reply": "2025-03-25T06:27:58.485624Z" } }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the series title, it mentions \"mRNA and microRNA interactions\", \n", "# indicating gene expression data is likely available.\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# There's no explicit disease/trait status in the characteristics dictionary\n", "# The dataset is about ALS, but we don't see any classification of subjects\n", "trait_row = None\n", "\n", "# Age data is not present in the sample characteristics\n", "age_row = None\n", "\n", "# Gender is available at index 0\n", "gender_row = 0\n", "\n", "# 2.2 Data Type Conversion\n", "# Since trait data is not available, we define a placeholder function\n", "def convert_trait(value):\n", " return None\n", "\n", "# Age conversion function (though not used in this case)\n", "def convert_age(value):\n", " return None\n", "\n", "# Gender conversion function\n", "def convert_gender(value):\n", " if not value or \":\" not in value:\n", " return None\n", " \n", " gender = value.split(\":\", 1)[1].strip().lower()\n", " \n", " if \"female\" in gender:\n", " return 0\n", " elif \"male\" in gender:\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Save the cohort information\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", "# Skip the clinical feature extraction since trait_row is None (is_trait_available is False)\n" ] }, { "cell_type": "markdown", "id": "3cf502f9", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "faccb4aa", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:27:58.487072Z", "iopub.status.busy": "2025-03-25T06:27:58.486960Z", "iopub.status.idle": "2025-03-25T06:27:58.575148Z", "shell.execute_reply": "2025-03-25T06:27:58.574745Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "First 20 gene/probe identifiers:\n", "Index(['2315554', '2315633', '2315674', '2315739', '2315894', '2315918',\n", " '2315951', '2316218', '2316245', '2316379', '2316558', '2316605',\n", " '2316746', '2316905', '2316953', '2317246', '2317317', '2317434',\n", " '2317472', '2317512'],\n", " dtype='object', name='ID')\n", "\n", "Gene data dimensions: 22011 genes × 42 samples\n" ] } ], "source": [ "# 1. Re-identify the SOFT and matrix files to ensure we have the correct paths\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Extract the gene expression data from the matrix file\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# 3. Print the first 20 row IDs (gene or probe identifiers)\n", "print(\"\\nFirst 20 gene/probe identifiers:\")\n", "print(gene_data.index[:20])\n", "\n", "# 4. Print the dimensions of the gene expression data\n", "print(f\"\\nGene data dimensions: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n", "\n", "# Note: we keep is_gene_available as True since we successfully extracted gene expression data\n", "is_gene_available = True\n" ] }, { "cell_type": "markdown", "id": "8166fc2f", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "620b5fe3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:27:58.576608Z", "iopub.status.busy": "2025-03-25T06:27:58.576456Z", "iopub.status.idle": "2025-03-25T06:27:58.578424Z", "shell.execute_reply": "2025-03-25T06:27:58.578125Z" } }, "outputs": [], "source": [ "# Looking at the gene identifiers, these appear to be numeric probe IDs from a microarray platform\n", "# rather than standard human gene symbols (which would typically be alphanumeric like APOE, TP53, etc.)\n", "# These numeric IDs (like '2315554') need to be mapped to official gene symbols for biological interpretation.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "6f2d9ec7", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "6c2d1a09", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:27:58.579662Z", "iopub.status.busy": "2025-03-25T06:27:58.579557Z", "iopub.status.idle": "2025-03-25T06:28:01.171779Z", "shell.execute_reply": "2025-03-25T06:28:01.171433Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['2315100', '2315106', '2315109', '2315111', '2315113'], 'GB_LIST': ['NR_024005,NR_034090,NR_024004,AK093685', 'DQ786314', nan, nan, 'DQ786265'], 'SPOT_ID': ['chr1:11884-14409', 'chr1:14760-15198', 'chr1:19408-19712', 'chr1:25142-25532', 'chr1:27563-27813'], 'seqname': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], 'RANGE_GB': ['NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10'], 'RANGE_STRAND': ['+', '+', '+', '+', '+'], 'RANGE_START': ['11884', '14760', '19408', '25142', '27563'], 'RANGE_STOP': ['14409', '15198', '19712', '25532', '27813'], 'total_probes': ['20', '8', '4', '4', '4'], 'gene_assignment': ['NR_024005 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771 /// NR_034090 // DDX11L9 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 9 // 15q26.3 // 100288486 /// NR_024004 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771 /// AK093685 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771', '---', '---', '---', '---'], 'mrna_assignment': ['NR_024005 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 (DDX11L2), transcript variant 2, non-coding RNA. // chr1 // 100 // 80 // 16 // 16 // 0 /// NR_034090 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 9 (DDX11L9), non-coding RNA. // chr1 // 100 // 80 // 16 // 16 // 0 /// NR_024004 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 (DDX11L2), transcript variant 1, non-coding RNA. // chr1 // 100 // 75 // 15 // 15 // 0 /// AK093685 // GenBank // Homo sapiens cDNA FLJ36366 fis, clone THYMU2007824. // chr1 // 94 // 80 // 15 // 16 // 0 /// ENST00000513886 // ENSEMBL // cdna:known chromosome:GRCh37:16:61555:64090:1 gene:ENSG00000233614 // chr1 // 100 // 80 // 16 // 16 // 0 /// ENST00000456328 // ENSEMBL // cdna:known chromosome:GRCh37:1:11869:14409:1 gene:ENSG00000223972 // chr1 // 100 // 80 // 16 // 16 // 0 /// ENST00000518655 // ENSEMBL // cdna:known chromosome:GRCh37:1:11869:14409:1 gene:ENSG00000253101 // chr1 // 100 // 80 // 16 // 16 // 0', 'DQ786314 // GenBank // Homo sapiens clone HLS_IMAGE_811138 mRNA sequence. // chr1 // 100 // 38 // 3 // 3 // 0', '---', '---', 'DQ786265 // GenBank // Homo sapiens clone HLS_IMAGE_298685 mRNA sequence. // chr1 // 100 // 100 // 4 // 4 // 0'], 'category': ['main', 'main', '---', '---', 'main']}\n" ] } ], "source": [ "# 1. First get the file paths using geo_get_relevant_filepaths function\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# 3. Use the 'preview_df' function from the library to preview the data and print out the results.\n", "print(\"Gene annotation preview:\")\n", "print(preview_df(gene_annotation))\n" ] }, { "cell_type": "markdown", "id": "ee683997", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "d5ea13bd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:28:01.173223Z", "iopub.status.busy": "2025-03-25T06:28:01.173099Z", "iopub.status.idle": "2025-03-25T06:28:01.606571Z", "shell.execute_reply": "2025-03-25T06:28:01.606170Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "After mapping: 48895 genes × 42 samples\n", "\n", "First 10 gene symbols after mapping:\n", "Index(['A-', 'A-2', 'A-52', 'A-E', 'A-I', 'A-II', 'A-IV', 'A-V', 'A0', 'A1'], dtype='object', name='Gene')\n" ] } ], "source": [ "# Identify the column containing gene/probe IDs and gene symbols\n", "# From the gene_annotation preview, we can see:\n", "# - 'ID' column contains the same numeric identifiers as in the gene expression data\n", "# - 'gene_assignment' column contains gene information with gene symbols\n", "\n", "# 1. Identify mapping columns and create the mapping dataframe\n", "id_col = 'ID' # Column containing probe IDs\n", "gene_col = 'gene_assignment' # Column containing gene symbols\n", "\n", "# 2. Create a mapping dataframe from gene annotation\n", "gene_mapping = get_gene_mapping(gene_annotation, id_col, gene_col)\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n", "# The 'apply_gene_mapping' function handles splitting values among multiple genes\n", "# and summing contributions for each gene\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "# Check the result - print dimensions and preview some gene symbols\n", "print(f\"\\nAfter mapping: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n", "print(\"\\nFirst 10 gene symbols after mapping:\")\n", "print(gene_data.index[:10])\n" ] }, { "cell_type": "markdown", "id": "e2b068a5", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "5b52469b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:28:01.608047Z", "iopub.status.busy": "2025-03-25T06:28:01.607914Z", "iopub.status.idle": "2025-03-25T06:28:02.219349Z", "shell.execute_reply": "2025-03-25T06:28:02.218945Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape after normalization: (18418, 42)\n", "First 5 gene symbols after normalization: Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1'], dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE212134.csv\n", "Sample IDs in clinical data:\n", "Index(['!Sample_geo_accession', 'GSM6509811', 'GSM6509812', 'GSM6509813',\n", " 'GSM6509814'],\n", " dtype='object') ...\n", "Sample IDs in gene expression data:\n", "Index(['GSM6509811', 'GSM6509812', 'GSM6509813', 'GSM6509814', 'GSM6509815'], dtype='object') ...\n", "Trait data was determined to be unavailable in previous steps.\n", "Abnormality detected in the cohort: GSE212134. Preprocessing failed.\n", "Dataset deemed not usable for associational studies.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the index of gene expression data\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 5 gene symbols after normalization: {normalized_gene_data.index[:5]}\")\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", "\n", "# 2. Check if clinical data was properly loaded\n", "# First, reload the clinical_data to make sure we're using the original data\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", "\n", "# Print the sample IDs to understand the data structure\n", "print(\"Sample IDs in clinical data:\")\n", "print(clinical_data.columns[:5], \"...\") # Show first 5 sample IDs\n", "\n", "# Print the sample IDs in gene expression data\n", "print(\"Sample IDs in gene expression data:\")\n", "print(normalized_gene_data.columns[:5], \"...\") # Show first 5 sample IDs\n", "\n", "# Check trait availability from previous steps\n", "is_trait_available = trait_row is not None\n", "linked_data = None\n", "\n", "if is_trait_available:\n", " # Extract clinical features with proper sample IDs\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\"Clinical data shape: {selected_clinical_df.shape}\")\n", " print(f\"Clinical data preview: {preview_df(selected_clinical_df, n=3)}\")\n", " \n", " # Save the 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", " # Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", " print(f\"Linked data shape before handling missing values: {linked_data.shape}\")\n", " \n", " # 3. Handle missing values\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", " \n", " # 4. Determine if trait and demographic features are biased\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " print(f\"Data shape after removing biased features: {linked_data.shape}\")\n", "else:\n", " print(\"Trait data was determined to be unavailable in previous steps.\")\n", " is_biased = True # Dataset can't be used without trait data\n", " linked_data = pd.DataFrame() # Empty DataFrame instead of artificial data\n", "\n", "# 5. Validate and save cohort info\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=is_trait_available,\n", " is_biased=is_biased,\n", " df=linked_data if not linked_data.empty else pd.DataFrame(index=normalized_gene_data.columns),\n", " note=\"Dataset contains gene expression data from ALS patients, but lacks trait information (disease status) required for associational studies.\"\n", ")\n", "\n", "# 6. Save linked data if usable\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Dataset deemed not usable for associational studies.\")" ] } ], "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 }