{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "17092939", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:56:58.571162Z", "iopub.status.busy": "2025-03-25T03:56:58.570933Z", "iopub.status.idle": "2025-03-25T03:56:58.738449Z", "shell.execute_reply": "2025-03-25T03:56:58.738033Z" } }, "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 = \"Sickle_Cell_Anemia\"\n", "cohort = \"GSE41575\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Sickle_Cell_Anemia\"\n", "in_cohort_dir = \"../../input/GEO/Sickle_Cell_Anemia/GSE41575\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Sickle_Cell_Anemia/GSE41575.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Sickle_Cell_Anemia/gene_data/GSE41575.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Sickle_Cell_Anemia/clinical_data/GSE41575.csv\"\n", "json_path = \"../../output/preprocess/Sickle_Cell_Anemia/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "bcde8cc5", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "54ca12f3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:56:58.739848Z", "iopub.status.busy": "2025-03-25T03:56:58.739709Z", "iopub.status.idle": "2025-03-25T03:56:58.800153Z", "shell.execute_reply": "2025-03-25T03:56:58.799757Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Role of platelet micrornas in sickle cell disease\"\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: ['cell line: Meg-01 cells'], 1: ['genotype/variation: miR1225 overexpression', 'genotype/variation: control']}\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": "4a448e82", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "40662695", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:56:58.801324Z", "iopub.status.busy": "2025-03-25T03:56:58.801217Z", "iopub.status.idle": "2025-03-25T03:56:58.808133Z", "shell.execute_reply": "2025-03-25T03:56:58.807843Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{'GSM1019586': [1.0], 'GSM1019587': [1.0], 'GSM1019588': [1.0], 'GSM1019589': [1.0], 'GSM1019590': [1.0], 'GSM1019591': [0.0], 'GSM1019592': [0.0], 'GSM1019593': [0.0], 'GSM1019594': [0.0], 'GSM1019595': [0.0]}\n", "Clinical data saved to ../../output/preprocess/Sickle_Cell_Anemia/clinical_data/GSE41575.csv\n" ] } ], "source": [ "import os\n", "import json\n", "import pandas as pd\n", "from typing import Callable, Optional, Dict, Any\n", "\n", "# 1. Gene Expression Availability\n", "# This seems to be a study focusing on microRNAs in sickle cell disease\n", "# The description mentions \"Role of platelet micrornas in sickle cell disease\"\n", "# This suggests it's primarily miRNA data, not gene expression\n", "is_gene_available = False\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# Looking at the sample characteristics dictionary:\n", "# {0: ['cell line: Meg-01 cells'], 1: ['genotype/variation: miR1225 overexpression', 'genotype/variation: control']}\n", "\n", "# For trait (Sickle Cell Anemia):\n", "# The data doesn't explicitly show sickle cell status for samples\n", "# It mentions cell lines and miRNA overexpression vs control\n", "# Row 1 has \"genotype/variation\" which could be related to the trait\n", "trait_row = 1\n", "\n", "# For age:\n", "# No information about age is provided in the sample characteristics\n", "age_row = None\n", "\n", "# For gender:\n", "# No information about gender is provided in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert the trait value to binary format.\n", " For sickle cell anemia, we'll use the genotype/variation field.\n", " \"\"\"\n", " if pd.isna(value) or 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", " # Based on the provided data, we need to interpret genotype/variation values\n", " # miR1225 overexpression vs control could indicate an experimental setup\n", " # rather than disease status\n", " if 'control' in value.lower():\n", " return 0 # Control\n", " elif 'overexpression' in value.lower():\n", " return 1 # Experimental condition\n", " \n", " return None # For any other values\n", "\n", "def convert_age(value):\n", " \"\"\"\n", " Convert age value to continuous format.\n", " \"\"\"\n", " # Not used as age_row is None\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"\n", " Convert gender value to binary format.\n", " \"\"\"\n", " # Not used as gender_row is None\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data 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", "# Since trait_row is not None, we need to extract clinical features\n", "if trait_row is not None and 'clinical_data' in locals():\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,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Ensure the output directory exists\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the clinical data to CSV\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "9407638a", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "9d607f59", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:56:58.809105Z", "iopub.status.busy": "2025-03-25T03:56:58.808997Z", "iopub.status.idle": "2025-03-25T03:56:58.854738Z", "shell.execute_reply": "2025-03-25T03:56:58.854443Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 61\n", "Header line: \"ID_REF\"\t\"GSM1019586\"\t\"GSM1019587\"\t\"GSM1019588\"\t\"GSM1019589\"\t\"GSM1019590\"\t\"GSM1019591\"\t\"GSM1019592\"\t\"GSM1019593\"\t\"GSM1019594\"\t\"GSM1019595\"\n", "First data line: \"A_23_P100001\"\t11.38730201\t11.93312075\t11.70949679\t11.91858179\t12.34590109\t13.25895613\t12.94793603\t12.90752861\t12.90612796\t12.907528\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" ] } ], "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", "# 2. First, let's examine the structure of the matrix file to understand its format\n", "import gzip\n", "\n", "# Peek at the first few lines of the file to understand its structure\n", "with gzip.open(matrix_file, 'rt') as file:\n", " # Read first 100 lines to find the header structure\n", " for i, line in enumerate(file):\n", " if '!series_matrix_table_begin' in line:\n", " print(f\"Found data marker at line {i}\")\n", " # Read the next line which should be the header\n", " header_line = next(file)\n", " print(f\"Header line: {header_line.strip()}\")\n", " # And the first data line\n", " first_data_line = next(file)\n", " print(f\"First data line: {first_data_line.strip()}\")\n", " break\n", " if i > 100: # Limit search to first 100 lines\n", " print(\"Matrix table marker not found in first 100 lines\")\n", " break\n", "\n", "# 3. Now try to get the genetic data with better error handling\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(gene_data.index[:20])\n", "except KeyError as e:\n", " print(f\"KeyError: {e}\")\n", " \n", " # Alternative approach: manually extract the data\n", " print(\"\\nTrying alternative approach to read the gene data:\")\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Find the start of the data\n", " for line in file:\n", " if '!series_matrix_table_begin' in line:\n", " break\n", " \n", " # Read the headers and data\n", " import pandas as pd\n", " df = pd.read_csv(file, sep='\\t', index_col=0)\n", " print(f\"Column names: {df.columns[:5]}\")\n", " print(f\"First 20 row IDs: {df.index[:20]}\")\n", " gene_data = df\n" ] }, { "cell_type": "markdown", "id": "e2d12765", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "f00c6e6c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:56:58.855778Z", "iopub.status.busy": "2025-03-25T03:56:58.855670Z", "iopub.status.idle": "2025-03-25T03:56:58.857496Z", "shell.execute_reply": "2025-03-25T03:56:58.857216Z" } }, "outputs": [], "source": [ "# The gene identifiers shown appear to be Agilent microarray probe IDs (e.g., \"A_23_P100001\")\n", "# These are not standard human gene symbols (which would look like \"BRCA1\", \"TP53\", etc.)\n", "# These probe IDs need to be mapped to gene symbols for biological interpretation\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "93ee7321", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "c6c659a7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:56:58.858507Z", "iopub.status.busy": "2025-03-25T03:56:58.858400Z", "iopub.status.idle": "2025-03-25T03:56:58.865108Z", "shell.execute_reply": "2025-03-25T03:56:58.864830Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining SOFT file structure:\n", "Line 0: ^DATABASE = GeoMiame\n", "Line 1: !Database_name = Gene Expression Omnibus (GEO)\n", "Line 2: !Database_institute = NCBI NLM NIH\n", "Line 3: !Database_web_link = http://www.ncbi.nlm.nih.gov/geo\n", "Line 4: !Database_email = geo@ncbi.nlm.nih.gov\n", "Line 5: ^SERIES = GSE41575\n", "Line 6: !Series_title = Role of platelet micrornas in sickle cell disease\n", "Line 7: !Series_geo_accession = GSE41575\n", "Line 8: !Series_status = Public on Jun 20 2013\n", "Line 9: !Series_submission_date = Oct 15 2012\n", "Line 10: !Series_last_update_date = Oct 11 2016\n", "Line 11: !Series_pubmed_id = 23593351\n", "Line 12: !Series_summary = This SuperSeries is composed of the SubSeries listed below.\n", "Line 13: !Series_overall_design = Refer to individual Series\n", "Line 14: !Series_type = Expression profiling by array\n", "Line 15: !Series_type = Non-coding RNA profiling by array\n", "Line 16: !Series_sample_id = GSM1019586\n", "Line 17: !Series_sample_id = GSM1019587\n", "Line 18: !Series_sample_id = GSM1019588\n", "Line 19: !Series_sample_id = GSM1019589\n", "\n", "Gene annotation preview:\n", "{'ID': ['bkv-miR-B1-3p', 'bkv-miR-B1-5p', 'ebv-miR-BART1-3p', 'ebv-miR-BART1-5p', 'ebv-miR-BART10'], 'ControlType': [0, 0, 0, 0, 0], 'miRNA_ID': ['bkv-miR-B1-3p', 'bkv-miR-B1-5p', 'ebv-miR-BART1-3p', 'ebv-miR-BART1-5p', 'ebv-miR-BART10'], 'SPOT_ID': [nan, nan, nan, nan, nan]}\n" ] } ], "source": [ "# 1. Let's first examine the structure of the SOFT file before trying to parse it\n", "import gzip\n", "\n", "# Look at the first few lines of the SOFT file to understand its structure\n", "print(\"Examining SOFT file structure:\")\n", "try:\n", " with gzip.open(soft_file, 'rt') as file:\n", " # Read first 20 lines to understand the file structure\n", " for i, line in enumerate(file):\n", " if i < 20:\n", " print(f\"Line {i}: {line.strip()}\")\n", " else:\n", " break\n", "except Exception as e:\n", " print(f\"Error reading SOFT file: {e}\")\n", "\n", "# 2. Now let's try a more robust approach to extract the gene annotation\n", "# Instead of using the library function which failed, we'll implement a custom approach\n", "try:\n", " # First, look for the platform section which contains gene annotation\n", " platform_data = []\n", " with gzip.open(soft_file, 'rt') as file:\n", " in_platform_section = False\n", " for line in file:\n", " if line.startswith('^PLATFORM'):\n", " in_platform_section = True\n", " continue\n", " if in_platform_section and line.startswith('!platform_table_begin'):\n", " # Next line should be the header\n", " header = next(file).strip()\n", " platform_data.append(header)\n", " # Read until the end of the platform table\n", " for table_line in file:\n", " if table_line.startswith('!platform_table_end'):\n", " break\n", " platform_data.append(table_line.strip())\n", " break\n", " \n", " # If we found platform data, convert it to a DataFrame\n", " if platform_data:\n", " import pandas as pd\n", " import io\n", " platform_text = '\\n'.join(platform_data)\n", " gene_annotation = pd.read_csv(io.StringIO(platform_text), delimiter='\\t', \n", " low_memory=False, on_bad_lines='skip')\n", " print(\"\\nGene annotation preview:\")\n", " print(preview_df(gene_annotation))\n", " else:\n", " print(\"Could not find platform table in SOFT file\")\n", " \n", " # Try an alternative approach - extract mapping from other sections\n", " with gzip.open(soft_file, 'rt') as file:\n", " for line in file:\n", " if 'ANNOTATION information' in line or 'annotation information' in line:\n", " print(f\"Found annotation information: {line.strip()}\")\n", " if line.startswith('!Platform_title') or line.startswith('!platform_title'):\n", " print(f\"Platform title: {line.strip()}\")\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation: {e}\")\n" ] }, { "cell_type": "markdown", "id": "0b354ad4", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "69543d79", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:56:58.866052Z", "iopub.status.busy": "2025-03-25T03:56:58.865948Z", "iopub.status.idle": "2025-03-25T03:56:59.450756Z", "shell.execute_reply": "2025-03-25T03:56:59.450390Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting gene annotation from SOFT file...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully extracted gene annotation with standard method: 334259 rows\n", "Columns in gene annotation: ['ID', 'ControlType', 'miRNA_ID', 'SPOT_ID']\n", "Potential ID columns: ['ID', 'miRNA_ID', 'SPOT_ID']\n", "Potential gene symbol columns: []\n", "\n", "Sample values from ID column 'ID':\n", "0 bkv-miR-B1-3p\n", "1 bkv-miR-B1-5p\n", "2 ebv-miR-BART1-3p\n", "3 ebv-miR-BART1-5p\n", "4 ebv-miR-BART10\n", "Name: ID, dtype: object\n", "\n", "Could not identify appropriate ID and gene symbol columns\n", "Unable to create gene mapping\n", "\n", "No gene expression data available for preview\n" ] } ], "source": [ "# Let's implement a more robust approach to extract gene annotation from the SOFT file\n", "print(\"Extracting gene annotation from SOFT file...\")\n", "\n", "try:\n", " # Approach 1: Use get_gene_annotation function if it works\n", " gene_annotation = get_gene_annotation(soft_file)\n", " \n", " if gene_annotation is None or len(gene_annotation) == 0:\n", " # If that fails, use a more manual approach\n", " print(\"Standard approach failed, trying alternative method to extract gene annotation\")\n", " \n", " # Read the SOFT file and extract the platform table\n", " platform_data = []\n", " with gzip.open(soft_file, 'rt') as file:\n", " in_platform_section = False\n", " for line in file:\n", " if line.startswith('^PLATFORM'):\n", " in_platform_section = True\n", " if in_platform_section and line.startswith('!platform_table_begin'):\n", " # Next line should be the header\n", " header = next(file).strip()\n", " platform_data.append(header)\n", " # Read until the end of the platform table\n", " for table_line in file:\n", " if table_line.startswith('!platform_table_end'):\n", " break\n", " platform_data.append(table_line.strip())\n", " break\n", " \n", " if platform_data:\n", " import io\n", " platform_text = '\\n'.join(platform_data)\n", " gene_annotation = pd.read_csv(io.StringIO(platform_text), delimiter='\\t', \n", " low_memory=False, on_bad_lines='skip')\n", " \n", " print(f\"Successfully extracted gene annotation with {len(gene_annotation)} rows\")\n", " print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n", " else:\n", " print(\"Could not find platform table in SOFT file\")\n", " gene_annotation = None\n", " else:\n", " print(f\"Successfully extracted gene annotation with standard method: {len(gene_annotation)} rows\")\n", " print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n", "\n", " # If we have gene annotation data, check for ID and gene symbol columns\n", " if gene_annotation is not None and len(gene_annotation) > 0:\n", " # Look for columns related to probe ID\n", " id_cols = [col for col in gene_annotation.columns \n", " if 'id' in col.lower() or 'probe' in col.lower() or col == 'ID']\n", " \n", " # Look for columns related to gene symbols\n", " gene_symbol_cols = [col for col in gene_annotation.columns \n", " if 'symbol' in col.lower() or 'gene' in col.lower()]\n", " \n", " print(f\"Potential ID columns: {id_cols}\")\n", " print(f\"Potential gene symbol columns: {gene_symbol_cols}\")\n", " \n", " # Check if we have sample values in these columns\n", " if id_cols:\n", " print(f\"\\nSample values from ID column '{id_cols[0]}':\")\n", " print(gene_annotation[id_cols[0]].head())\n", " \n", " if gene_symbol_cols:\n", " print(f\"\\nSample values from gene symbol column '{gene_symbol_cols[0]}':\")\n", " print(gene_annotation[gene_symbol_cols[0]].head())\n", " \n", " # Determine which columns to use for mapping\n", " id_col = id_cols[0] if id_cols else None\n", " gene_symbol_col = gene_symbol_cols[0] if gene_symbol_cols else None\n", " \n", " # Create the mapping dataframe\n", " if id_col and gene_symbol_col:\n", " print(f\"\\nCreating gene mapping using columns: {id_col} -> {gene_symbol_col}\")\n", " mapping_data = get_gene_mapping(gene_annotation, id_col, gene_symbol_col)\n", " print(f\"Created mapping with {len(mapping_data)} rows\")\n", " \n", " # Apply the mapping to convert probe-level measurements to gene expression\n", " gene_data = apply_gene_mapping(gene_data, mapping_data)\n", " print(f\"Successfully mapped probes to genes. Gene expression data has {len(gene_data)} genes.\")\n", " \n", " # Set gene_available to True since we successfully processed gene expression data\n", " is_gene_available = True\n", " else:\n", " print(\"\\nCould not identify appropriate ID and gene symbol columns\")\n", " print(\"Unable to create gene mapping\")\n", " gene_data = None\n", " is_gene_available = False\n", " else:\n", " print(\"\\nNo gene annotation data available\")\n", " gene_data = None\n", " is_gene_available = False\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation: {e}\")\n", " gene_data = None\n", " is_gene_available = False\n", "\n", "# Update cohort info with the correct gene availability\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", "# If gene data was successfully mapped, print a preview\n", "if gene_data is not None:\n", " print(\"\\nPreview of mapped gene expression data:\")\n", " print(gene_data.head())\n", "else:\n", " print(\"\\nNo gene expression data available for preview\")" ] } ], "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 }