{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "806d6fc3", "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 = \"Bone_Density\"\n", "cohort = \"GSE56815\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Bone_Density\"\n", "in_cohort_dir = \"../../input/GEO/Bone_Density/GSE56815\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Bone_Density/GSE56815.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Bone_Density/gene_data/GSE56815.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Bone_Density/clinical_data/GSE56815.csv\"\n", "json_path = \"../../output/preprocess/Bone_Density/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "0bdd62c3", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "8d443bba", "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": "83fa5598", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "12b83518", "metadata": {}, "outputs": [], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains gene expression data from Affymetrix arrays\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For trait (bone mineral density): available at index 1\n", "trait_row = 1\n", "# For age: not available in the sample characteristics\n", "age_row = None\n", "# For gender: all subjects are female (constant), so we consider it not available\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert bone mineral density values to binary (0 for low BMD, 1 for high BMD)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value part after the colon if present\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if isinstance(value, str):\n", " value = value.lower()\n", " if 'high' in value:\n", " return 1\n", " elif 'low' in value:\n", " return 0\n", " \n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age values to continuous numbers\"\"\"\n", " # Not used as age data is not available\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender values to binary (0 for female, 1 for male)\"\"\"\n", " # Not used as gender data is not available\n", " return None\n", "\n", "# 3. Save Metadata - Initial Filtering\n", "# Since trait_row is not None, trait data is available\n", "is_trait_available = trait_row is not None\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 data is available, extract clinical features\n", "if trait_row is not None:\n", " # Extract clinical features using the library function\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 extracted clinical data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of extracted clinical data:\")\n", " print(preview)\n", " \n", " # Save the extracted clinical data to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\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": "f7254b68", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "efb5a1b6", "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": "0cca0231", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "d492fa14", "metadata": {}, "outputs": [], "source": [ "# Analyze the gene identifiers in the index\n", "# Looking at the identifiers like '1007_s_at', '1053_at', etc.\n", "# These appear to be probe IDs from Affymetrix microarrays, not standard human gene symbols\n", "\n", "# Probe IDs in the format of '1007_s_at' are typical for Affymetrix platforms\n", "# They need to be mapped to human gene symbols for meaningful analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "0a4c48bd", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "e00bf63e", "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": "a2b8a7c0", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "5a797bdb", "metadata": {}, "outputs": [], "source": [ "# 1. Identify columns in gene annotation data that contain probe IDs and gene symbols\n", "# From the preview, we can see that 'ID' contains probe IDs like '1007_s_at'\n", "# and 'Gene Symbol' contains the gene symbols like 'DDR1 /// MIR4640'\n", "probe_col = 'ID'\n", "gene_col = 'Gene Symbol'\n", "\n", "# 2. Get gene mapping dataframe using the get_gene_mapping function from the library\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_col)\n", "\n", "# 3. Convert probe-level measurements to gene-level expression by applying the mapping\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Print information about the resulting gene expression dataframe\n", "print(f\"Number of genes after mapping: {len(gene_data)}\")\n", "print(\"First 10 gene symbols:\")\n", "print(gene_data.index[:10])\n" ] }, { "cell_type": "markdown", "id": "81dd8993", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "86cfadfc", "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", "# 2. Load the previously saved clinical data\n", "clinical_df = pd.read_csv(out_clinical_data_file)\n", "print(\"Clinical data structure:\")\n", "print(clinical_df.head())\n", "\n", "# Get trait column name (actual name in the DataFrame)\n", "trait_column = clinical_df.columns[0] # First column should be Bone_Density\n", "\n", "# Create a DataFrame with correct structure for geo_link_clinical_genetic_data\n", "# The function expects clinical_df to have features as rows and samples as columns\n", "clinical_df_for_linking = pd.DataFrame(clinical_df[trait_column].values[None, :], \n", " index=[trait], \n", " columns=clinical_df.index)\n", "print(\"Clinical data prepared for linking:\")\n", "print(clinical_df_for_linking.head())\n", "\n", "# Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_df_for_linking, normalized_gene_data)\n", "\n", "# For analysis functions, we need samples as rows and features as columns\n", "linked_data_for_analysis = linked_data.T\n", "\n", "# 3. Handle missing values in the linked data\n", "linked_data_for_analysis = handle_missing_values(linked_data_for_analysis, trait)\n", "\n", "# 4. Determine whether the trait and demographic features are severely biased\n", "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data_for_analysis, trait)\n", "\n", "# 5. Conduct final quality validation 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=True, \n", " is_biased=is_trait_biased, \n", " df=unbiased_linked_data,\n", " note=\"Dataset contains gene expression from blood monocytes in pre- and postmenopausal females with low or high bone mineral density.\"\n", ")\n", "\n", "# 6. If the linked data is usable, save it as CSV\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\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Data was determined to be unusable and was not saved\")\n" ] }, { "cell_type": "markdown", "id": "71f31bb3", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "9cb75063", "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", "# 2. Load the previously saved clinical data and prepare for linking\n", "# Read the clinical data without setting index_col to avoid issues\n", "clinical_df = pd.read_csv(out_clinical_data_file)\n", "\n", "# Get the structure of the clinical data to understand column names\n", "print(\"Clinical data columns:\", clinical_df.columns.tolist())\n", "print(\"Clinical data shape:\", clinical_df.shape)\n", "\n", "# Transform clinical data to have the correct format for linking\n", "# The clinical data appears to have samples as columns with the trait value in each row 0\n", "sample_names = clinical_df.columns.tolist()\n", "trait_values = clinical_df.iloc[0].tolist()\n", "clinical_df_transformed = pd.DataFrame({trait: trait_values}, index=sample_names)\n", "\n", "# Link clinical and genetic data\n", "linked_data = pd.merge(clinical_df_transformed, normalized_gene_data.T, \n", " left_index=True, right_index=True)\n", "\n", "# Check the structure of the linked data\n", "print(\"Linked data shape:\", linked_data.shape)\n", "print(\"Linked data columns include trait column?\", trait in linked_data.columns)\n", "\n", "# 3. Handle missing values in the linked data\n", "linked_data = handle_missing_values(linked_data, trait)\n", "\n", "# 4. Determine whether the trait and some demographic features are severely biased\n", "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# 5. Conduct final quality validation and save relevant 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=\"Dataset contains gene expression from blood monocytes in pre- and postmenopausal females with low or high bone mineral density.\"\n", ")\n", "\n", "# 6. If the linked data is usable, save it as CSV\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\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Data was determined to be unusable and was not saved\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }