{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "4e4786f9", "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 = \"Sjögrens_Syndrome\"\n", "cohort = \"GSE66795\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Sjögrens_Syndrome\"\n", "in_cohort_dir = \"../../input/GEO/Sjögrens_Syndrome/GSE66795\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Sjögrens_Syndrome/GSE66795.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Sjögrens_Syndrome/gene_data/GSE66795.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Sjögrens_Syndrome/clinical_data/GSE66795.csv\"\n", "json_path = \"../../output/preprocess/Sjögrens_Syndrome/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "7e4ea364", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "464718dc", "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": "ac7cfbdf", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "1bdbb45e", "metadata": {}, "outputs": [], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background information and sample characteristics, this dataset likely 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", "# Trait (pSS) can be inferred from \"patient group\" (key 2)\n", "trait_row = 2 # 'patient group: Control', 'patient group: Patient'\n", "\n", "# Age is not available in the sample characteristics\n", "age_row = None \n", "\n", "# Gender is available (key 3), but there's only one value ('gender: Female')\n", "# Since all subjects are female, this is a constant feature and not useful for association analysis\n", "gender_row = None \n", "\n", "# 2.2 Data Type Conversion\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert patient group to binary trait (Sjögren's Syndrome)\"\"\"\n", " if isinstance(value, str) and \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " if value.lower() == \"patient\":\n", " return 1 # Has Sjögren's Syndrome\n", " elif value.lower() == \"control\":\n", " return 0 # Doesn't have Sjögren's Syndrome\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to continuous value\"\"\"\n", " # Age data is not available\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary (0=female, 1=male)\"\"\"\n", " # Gender is constant (all female) so not useful for analysis\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Trait data is available (trait_row is not None)\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and save cohort info with is_final=False for initial filtering\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 (since trait_row is not None)\n", "if trait_row is not None:\n", " # Extract clinical features using the geo_select_clinical_features 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 selected clinical features\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Save the selected clinical features as a CSV file\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": "ac4b7bff", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "84837bbb", "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": "b2e65f0c", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "e4fbc16b", "metadata": {}, "outputs": [], "source": [ "# Analysis of gene identifiers\n", "# The gene identifiers shown (ILMN_xxxxxxx) are Illumina probe IDs, not human gene symbols.\n", "# These are microarray probe identifiers from Illumina BeadArray platforms\n", "# These need to be mapped to standard gene symbols for meaningful analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "5624aa14", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "55f18d39", "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": "68a59826", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "4a8d0708", "metadata": {}, "outputs": [], "source": [ "# 1. Identify the relevant columns for gene mapping\n", "# From the preview, we can see:\n", "# - 'ID' column contains Illumina probe IDs (ILMN_xxxxxx) that match gene_data indices\n", "# - 'Symbol' column contains the gene symbols we need\n", "\n", "# 2. Extract the gene mapping dataframe\n", "mapping_df = get_gene_mapping(gene_annotation, 'ID', 'Symbol')\n", "print(f\"Gene mapping dataframe shape: {mapping_df.shape}\")\n", "print(\"Gene mapping preview:\")\n", "print(mapping_df.head())\n", "\n", "# 3. Apply gene mapping to convert probe-level data to gene expression\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Gene expression dataframe shape after mapping: {gene_data.shape}\")\n", "print(\"Gene expression data preview (first 5 genes, first 5 samples):\")\n", "print(gene_data.iloc[:5, :5])\n", "\n", "# Save the gene expression data\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" ] }, { "cell_type": "markdown", "id": "12faf072", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "14d005e5", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n", "print(f\"First few normalized gene symbols: {list(normalized_gene_data.index[:10])}\")\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. Load the previously saved clinical data\n", "clinical_df = pd.read_csv(out_clinical_data_file)\n", "print(f\"Loaded clinical data shape: {clinical_df.shape}\")\n", "print(clinical_df.head())\n", "\n", "# 3. Link the clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_df.T, normalized_gene_data)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "\n", "# Rename the unnamed index 0 to the trait name\n", "linked_data = linked_data.rename(index={0: trait})\n", "print(linked_data.head())\n", "\n", "# 4. Handle missing values in the linked data\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Shape after handling missing values: {linked_data.shape}\")\n", "\n", "# 5. Determine whether the trait and demographic features are severely biased\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=f\"Dataset contains gene expression data from whole blood of pSS patients and healthy controls.\"\n", ")\n", "\n", "# 7. Save the data if it's usable\n", "if is_usable:\n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " # Save the data\n", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(f\"Data quality check failed. The dataset is not suitable for association studies.\")\n" ] }, { "cell_type": "markdown", "id": "da97eed0", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "5c767754", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n", "print(f\"First few normalized gene symbols: {list(normalized_gene_data.index[:10])}\")\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. Load the previously saved clinical data\n", "clinical_df = pd.read_csv(out_clinical_data_file)\n", "print(f\"Loaded clinical data shape: {clinical_df.shape}\")\n", "print(clinical_df.head())\n", "\n", "# 3. Transform clinical data to have trait as column\n", "sample_ids = clinical_df.columns\n", "trait_values = clinical_df.iloc[0].values\n", "clinical_df_restructured = pd.DataFrame({trait: trait_values}, index=sample_ids)\n", "print(f\"Restructured clinical data shape: {clinical_df_restructured.shape}\")\n", "print(clinical_df_restructured.head())\n", "\n", "# 4. Properly format gene expression data (transpose to have samples as rows)\n", "gene_expr_for_linking = normalized_gene_data.T\n", "print(f\"Transposed gene data shape: {gene_expr_for_linking.shape}\")\n", "\n", "# 5. Merge clinical and gene expression data on sample IDs\n", "linked_data = clinical_df_restructured.join(gene_expr_for_linking)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(linked_data.head(3))\n", "\n", "# 6. Handle missing values in the linked data\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Shape after handling missing values: {linked_data.shape}\")\n", "\n", "# 7. Determine whether the trait and demographic features are severely biased\n", "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# 8. 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=f\"Dataset contains gene expression data from whole blood samples of pSS patients and healthy controls.\"\n", ")\n", "\n", "# 9. Save the data if it's usable\n", "if is_usable:\n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " # Save the data\n", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(f\"Data quality check failed. The dataset is not suitable for association studies.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }