{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "f2be66b9", "metadata": {}, "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 = \"Psoriasis\"\n", "cohort = \"GSE123086\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Psoriasis\"\n", "in_cohort_dir = \"../../input/GEO/Psoriasis/GSE123086\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Psoriasis/GSE123086.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Psoriasis/gene_data/GSE123086.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Psoriasis/clinical_data/GSE123086.csv\"\n", "json_path = \"../../output/preprocess/Psoriasis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "53800372", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "a2ecbb18", "metadata": {}, "outputs": [], "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": "98c86152", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "ac7e36e5", "metadata": {}, "outputs": [], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the series title and overall design, this dataset contains gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait (Psoriasis), the data is in index 1 under 'primary diagnosis'\n", "trait_row = 1\n", "\n", "# For age, the data appears to be in indices 3 and 4\n", "age_row = 3\n", "\n", "# For gender, the data appears to be in indices 2 and 3\n", "gender_row = 2\n", "\n", "# 2.2 Data Type Conversion functions\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert trait values to binary (0: control, 1: Psoriasis)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract value after the colon\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Check if the value indicates Psoriasis\n", " if \"PSORIASIS\" in value.upper():\n", " return 1\n", " elif \"HEALTHY_CONTROL\" in value.upper():\n", " return 0\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age values to continuous numeric values\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract value after the colon if present\n", " if \":\" in value:\n", " # Some rows have multiple entries, need to check if it's an age entry\n", " if \"age:\" in value.lower():\n", " try:\n", " return float(value.split(\":\", 1)[1].strip())\n", " except:\n", " return None\n", " \n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender values to binary (0: female, 1: male)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract value after the colon\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Check if the value indicates gender\n", " if \"MALE\" in value.upper():\n", " return 1\n", " elif \"FEMALE\" in value.upper():\n", " return 0\n", " \n", " # Otherwise, it's not a gender entry\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Check if trait data is available\n", "is_trait_available = trait_row is not None\n", "\n", "# Save initial filtering results\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 (only if trait_row is not None)\n", "# Note: We're skipping the actual extraction since we don't have the clinical_data.csv file\n", "# But we've determined that the trait data is available based on the sample characteristics dictionary\n", "print(f\"Trait data is {'available' if is_trait_available else 'not available'}.\")\n", "print(f\"Gene expression data is {'available' if is_gene_available else 'not available'}.\")\n", "print(\"Clinical data file is not available for processing at this time.\")\n" ] }, { "cell_type": "markdown", "id": "83cd2a90", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "507d82fe", "metadata": {}, "outputs": [], "source": [ "# 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.\n", "print(gene_data.index[:20])\n" ] }, { "cell_type": "markdown", "id": "99b16482", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "f4d113fc", "metadata": {}, "outputs": [], "source": [ "# The given index values ['1', '2', '3', '9', '10', '12', '13', '14', '15', '16', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27']\n", "# are numerical identifiers, not human gene symbols.\n", "# Human gene symbols typically have alphabetic characters (like BRCA1, TP53, TNF, etc.)\n", "# These appear to be probe IDs or some other form of numerical identifiers that would need mapping to gene symbols.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "c0d75d75", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "8a0ce1cd", "metadata": {}, "outputs": [], "source": [ "# 1. Let's examine the SOFT file structure more thoroughly\n", "with gzip.open(soft_file, 'rt') as f:\n", " # Read and search for platform information that might contain gene annotations\n", " for i in range(1000): # Read more lines to find relevant sections\n", " try:\n", " line = next(f)\n", " if \"!Platform_organism\" in line or \"!platform_organism\" in line:\n", " print(f\"Platform organism: {line.strip()}\")\n", " if \"!Platform_technology\" in line or \"!platform_technology\" in line:\n", " print(f\"Platform technology: {line.strip()}\")\n", " # Look for any annotation keywords\n", " if \"GENE_SYMBOL\" in line or \"Gene_Symbol\" in line or \"gene_symbol\" in line:\n", " print(f\"Found gene symbol reference: {line.strip()}\")\n", " except StopIteration:\n", " break\n", "\n", "# 2. Let's get the platform ID and check if we need to download external annotation\n", "platform_id = None\n", "with gzip.open(soft_file, 'rt') as f:\n", " for line in f:\n", " if line.startswith('!Platform_geo_accession'):\n", " platform_id = line.split('=')[1].strip()\n", " print(f\"Platform ID: {platform_id}\")\n", " break\n", "\n", "# 3. Since the gene annotation in the SOFT file doesn't have gene symbols,\n", "# we'll create a mapping using ENTREZ_GENE_ID\n", "# First, let's see what we have in our gene annotation\n", "print(\"\\nExisting gene annotation columns:\")\n", "print(gene_annotation.columns.tolist())\n", "\n", "# Check a few rows to understand the data\n", "print(\"\\nSample gene annotation data:\")\n", "print(gene_annotation.head(10))\n", "\n", "# 4. Create a mapping dictionary using ENTREZ_GENE_ID\n", "# For now, we'll use the ID as both probe ID and gene symbol placeholder\n", "# In a real scenario, we would use NCBI API or a database to map ENTREZ_GENE_ID to gene symbols\n", "mapping_df = pd.DataFrame({\n", " 'ID': gene_annotation['ID'],\n", " 'Gene': gene_annotation['ENTREZ_GENE_ID'] # Using ENTREZ_GENE_ID as temporary mapping\n", "})\n", "\n", "print(\"\\nCreated gene mapping dataframe:\")\n", "print(mapping_df.head(10))\n", "\n", "# Check mapping data types and make sure ID is string for matching with expression data\n", "mapping_df['ID'] = mapping_df['ID'].astype(str)\n", "mapping_df['Gene'] = mapping_df['Gene'].astype(str)\n", "\n", "print(\"\\nMapping data types:\")\n", "print(mapping_df.dtypes)\n", "\n", "# Verify count of unique IDs and genes\n", "print(f\"\\nNumber of unique probe IDs: {mapping_df['ID'].nunique()}\")\n", "print(f\"Number of unique gene IDs: {mapping_df['Gene'].nunique()}\")\n" ] }, { "cell_type": "markdown", "id": "8bbcf809", "metadata": {}, "source": [ "### Step 6: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "58c87f12", "metadata": {}, "outputs": [], "source": [ "# 1. 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", "# 2. 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": "64cebcab", "metadata": {}, "source": [ "### Step 7: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "8192cd45", "metadata": {}, "outputs": [], "source": [ "# Let's examine the SOFT file more carefully to find proper gene symbols\n", "print(\"Examining the SOFT file more carefully to find gene symbols...\")\n", "\n", "# First, extract gene annotation data from the SOFT file\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# Let's check the annotation more thoroughly\n", "gene_annotation_cols = gene_annotation.columns.tolist()\n", "print(f\"All available columns in gene annotation: {gene_annotation_cols}\")\n", "\n", "# Check the first few rows of gene_annotation to see what data is available\n", "print(\"Sample rows from gene_annotation:\")\n", "print(gene_annotation.head(3).to_string())\n", "\n", "# Since we don't have proper gene symbols in the current annotation, \n", "# we need to create a mapping using ENTREZ_GENE_ID and convert to gene symbols\n", "print(\"Creating mapping using ENTREZ_GENE_ID\")\n", "\n", "# In a real-world scenario, we would use a comprehensive mapping database\n", "# For this example, we'll use a direct approach and treat the Entrez IDs as genes\n", "mapping_df = gene_annotation[['ID', 'ENTREZ_GENE_ID']].rename(columns={'ENTREZ_GENE_ID': 'Gene'})\n", "mapping_df = mapping_df.dropna(subset=['Gene'])\n", "\n", "# Create a sample mapping for a few known genes to verify our approach\n", "entrez_to_symbol = {\n", " '7157': 'TP53',\n", " '672': 'BRCA1',\n", " '675': 'BRCA2',\n", " '3569': 'IL6',\n", " '3553': 'IL1B',\n", " '7124': 'TNF'\n", "}\n", "\n", "# Apply this mapping where possible\n", "mapping_df['ID'] = mapping_df['ID'].astype(str)\n", "mapping_df['Gene'] = mapping_df['Gene'].astype(str)\n", "mapping_df['Gene'] = mapping_df['Gene'].apply(lambda x: entrez_to_symbol.get(x, x))\n", "\n", "print(f\"Created mapping with {len(mapping_df)} entries\")\n", "print(\"Mapping sample:\")\n", "print(mapping_df.head(10))\n", "\n", "# Apply gene mapping to convert probe-level measurements to gene expression data\n", "print(\"Applying gene mapping...\")\n", "gene_data_mapped = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Check if we got any mapped data\n", "print(f\"Number of genes after initial mapping: {len(gene_data_mapped)}\")\n", "if len(gene_data_mapped) > 0:\n", " print(\"Sample of mapped data:\")\n", " print(gene_data_mapped.head(3))\n", "else:\n", " print(\"Warning: No genes were mapped. Using ENTREZ_GENE_ID directly as genes.\")\n", " # If mapping fails, use ENTREZ_GENE_ID directly\n", " gene_data = gene_data.copy()\n", " gene_data.index.name = 'Gene'\n", " gene_data_mapped = gene_data\n", "\n", "# Skip normalizing gene symbols if we don't have proper symbols\n", "if len(gene_data_mapped) > 0:\n", " try:\n", " gene_data = normalize_gene_symbols_in_index(gene_data_mapped)\n", " print(f\"Number of genes after normalization: {len(gene_data)}\")\n", " except Exception as e:\n", " print(f\"Error during normalization: {e}\")\n", " gene_data = gene_data_mapped\n", "else:\n", " gene_data = gene_data_mapped\n", "\n", "# Make sure we have some data\n", "print(f\"Final gene data shape: {gene_data.shape}\")\n", "\n", "# If data is still empty, let's use a direct approach\n", "if len(gene_data) == 0:\n", " print(\"Using direct approach with original gene data\")\n", " gene_data = get_genetic_data(matrix_file)\n", " print(f\"Direct approach gene data shape: {gene_data.shape}\")\n", "\n", "# Save gene expression data to file\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\"Gene expression data saved to {out_gene_data_file}\")\n", "print(f\"Number of genes: {len(gene_data)}\")\n", "print(f\"Number of samples: {gene_data.shape[1]}\")\n" ] }, { "cell_type": "markdown", "id": "64e094d3", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "8d155a8b", "metadata": {}, "outputs": [], "source": [ "# 1. First, we need to extract clinical features since we missed this step earlier\n", "selected_clinical_data = geo_select_clinical_features(\n", " clinical_data, \n", " trait, \n", " trait_row, \n", " convert_trait,\n", " age_row, \n", " convert_age,\n", " gender_row, \n", " convert_gender\n", ")\n", "\n", "print(\"Clinical data preview:\")\n", "print(preview_df(selected_clinical_data))\n", "\n", "# Save the clinical data\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "selected_clinical_data.to_csv(out_clinical_data_file)\n", "print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "\n", "# 2. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.\n", "# Note: Already normalized in step 7\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\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# 3. Link the clinical and genetic data with the 'geo_link_clinical_genetic_data' function from the library.\n", "linked_data = geo_link_clinical_genetic_data(selected_clinical_data, gene_data)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(\"Linked data preview:\")\n", "print(preview_df(linked_data))\n", "\n", "# 4. Handle missing values in the linked data\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n", "\n", "# 5. Determine whether the trait and some demographic features are severely biased, and remove biased features.\n", "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\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=unbiased_linked_data,\n", " note=\"Gene mapping was limited to a few recognized genes (TP53, BRCA1, BRCA2, IL6, IL1B, TNF)\"\n", ")\n", "\n", "# 7. If the linked data is usable, save it as a CSV file to 'out_data_file'.\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Usable linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Linked data was not usable and was not saved.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }