{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "5e3ce48d", "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 = \"Osteoporosis\"\n", "cohort = \"GSE62589\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Osteoporosis\"\n", "in_cohort_dir = \"../../input/GEO/Osteoporosis/GSE62589\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Osteoporosis/GSE62589.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Osteoporosis/gene_data/GSE62589.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Osteoporosis/clinical_data/GSE62589.csv\"\n", "json_path = \"../../output/preprocess/Osteoporosis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "5841ed96", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "20f54e64", "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": "d2199aad", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "4b89068d", "metadata": {}, "outputs": [], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on available information, this is a SuperSeries containing gene expression data from blood samples\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# Trait row is None since there's no explicit osteoporosis status in the sample characteristics\n", "trait_row = None\n", "\n", "# Age row is None since there's no age information in the sample characteristics\n", "age_row = None\n", "\n", "# Gender row is found at index 2, with 'Sex: female'\n", "gender_row = 2\n", "\n", "# 2.2 Data Type Conversion\n", "# Since trait_row is None, no need to define convert_trait but we'll create a placeholder\n", "def convert_trait(value):\n", " return None\n", "\n", "# No age data available, but create placeholder function\n", "def convert_age(value):\n", " return None\n", "\n", "# Gender conversion - Convert to binary (0 for female, 1 for male)\n", "def convert_gender(value):\n", " if value is None:\n", " return None\n", " # Extract the value after the colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " else:\n", " value = value.lower().strip()\n", " \n", " if 'female' in value:\n", " return 0\n", " elif 'male' in value:\n", " return 1\n", " else:\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", "# Skip this step since trait_row is None (no clinical data available for the trait)\n" ] }, { "cell_type": "markdown", "id": "aa06d653", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "add1e709", "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": "7607d5e8", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "150e26ad", "metadata": {}, "outputs": [], "source": [ "# Looking at the gene identifiers provided\n", "# These are numerical identifiers (like '2315554', '2315633', etc.)\n", "# These are not standard human gene symbols (which are typically alphabetic like 'BRCA1', 'TP53')\n", "# These appear to be probe IDs from a microarray platform that need to be mapped to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "b79a007e", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "b7c544fb", "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": "93c2a9d6", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "468e5704", "metadata": {}, "outputs": [], "source": [ "# 1. Determine which columns in gene annotation data correspond to gene IDs and gene symbols\n", "# From the preview, we can see:\n", "# - 'ID' column contains probe identifiers matching the gene expression data\n", "# - 'gene_assignment' column contains gene symbol information\n", "\n", "# 2. Get a gene mapping dataframe by extracting relevant columns\n", "# First, check for empty gene assignments and print some examples to verify the mapping\n", "print(\"Example gene assignments:\")\n", "print(gene_annotation['gene_assignment'].head(10))\n", "\n", "# Create the mapping dataframe\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='gene_assignment')\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n", "# This handles many-to-many relationships between probes and genes\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Preview the resulting gene expression data\n", "print(\"\\nGene expression data after mapping:\")\n", "print(gene_data.head())\n", "print(f\"Shape of gene expression data: {gene_data.shape}\")\n" ] }, { "cell_type": "markdown", "id": "d41e36db", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "26d9d179", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.\n", "normalized_gene_data = normalize_gene_symbols_in_index(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", "# Since trait_row is None, we can't extract proper clinical features\n", "# Create a minimal clinical dataframe with just Gender since that's the only available feature\n", "if gender_row is not None:\n", " gender_data = get_feature_data(clinical_data, gender_row, 'Gender', convert_gender)\n", " clinical_features_df = gender_data.T # Transpose to get samples as rows\n", "else:\n", " # If no clinical features at all, create an empty DataFrame with the same sample IDs\n", " clinical_features_df = pd.DataFrame(index=normalized_gene_data.columns)\n", "\n", "# Save the clinical data\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "clinical_features_df.to_csv(out_clinical_data_file)\n", "print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "\n", "# Now link the clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_features_df, normalized_gene_data)\n", "print(\"Linked data shape:\", linked_data.shape)\n", "\n", "# We can't handle missing values for the trait since there's no trait data\n", "# We can only handle missing values for gender\n", "if 'Gender' in linked_data.columns:\n", " # Fill missing gender values with the mode\n", " mode_gender = linked_data['Gender'].mode()[0] if not linked_data['Gender'].isna().all() else None\n", " linked_data['Gender'] = linked_data['Gender'].fillna(mode_gender)\n", "\n", "# Since trait is not available, we can't evaluate if it's biased\n", "# We only need to evaluate the bias in Gender\n", "if 'Gender' in linked_data.columns:\n", " gender_biased = judge_binary_variable_biased(linked_data, 'Gender')\n", " if gender_biased:\n", " print(\"The distribution of the feature 'Gender' in this dataset is severely biased.\")\n", " linked_data = linked_data.drop(columns='Gender')\n", " else:\n", " print(\"The distribution of the feature 'Gender' in this dataset is fine.\")\n", "\n", "# 5. Conduct quality check and save the cohort information.\n", "# Since trait_row is None, is_trait_available should be False\n", "is_trait_available = trait_row is not None\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=False, # Set to False instead of None when trait is not available\n", " df=linked_data,\n", " note=\"This is a blood monocyte study. No osteoporosis status information is available in the clinical data.\"\n", ")\n", "\n", "# Since trait data is not available, the dataset is not usable for our trait analysis\n", "print(\"Dataset is not usable for trait analysis due to missing trait information.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }