{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "0770f776", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:54:55.881333Z", "iopub.status.busy": "2025-03-25T05:54:55.881225Z", "iopub.status.idle": "2025-03-25T05:54:56.037938Z", "shell.execute_reply": "2025-03-25T05:54:56.037623Z" } }, "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 = \"Obesity\"\n", "cohort = \"GSE158850\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Obesity\"\n", "in_cohort_dir = \"../../input/GEO/Obesity/GSE158850\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Obesity/GSE158850.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Obesity/gene_data/GSE158850.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Obesity/clinical_data/GSE158850.csv\"\n", "json_path = \"../../output/preprocess/Obesity/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "ce12126b", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "09df02c9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:54:56.039285Z", "iopub.status.busy": "2025-03-25T05:54:56.039146Z", "iopub.status.idle": "2025-03-25T05:54:56.156442Z", "shell.execute_reply": "2025-03-25T05:54:56.156107Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Skeletal muscle adaptations to an 8-week weight loss intervention in younger and older obese men\"\n", "!Series_summary\t\"Vastus lateralis Skeletal muscle transcriptomes were analyzed between 13 young and 12 elderly obese men during a lifestyle intervention.\"\n", "!Series_summary\t\"Lifestyle intervention: Individuals underwent 8-weeks of calorie-restriction of 20% below their daily energy requirement aerobic combined to two sessions of resistance exercise per weeks.\"\n", "!Series_overall_design\t\"Two groups,young and elderly; two conditions for each individual, baseline (before lifestyle intervention) and after lifestyle intervention.\"\n", "\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: Skeletal muscle'], 1: ['Sex: Male'], 2: ['age group: Young', 'age group: Elderly'], 3: ['disease state: obese'], 4: ['time point: baseline', 'time point: after lifestyle intervention']}\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_ch2']\n", "\n", "# Extract background information and clinical data\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(\"\\nSample Characteristics Dictionary:\")\n", "print(sample_characteristics_dict)\n" ] }, { "cell_type": "markdown", "id": "ec776a86", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "c29e7afc", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:54:56.157672Z", "iopub.status.busy": "2025-03-25T05:54:56.157559Z", "iopub.status.idle": "2025-03-25T05:54:56.167077Z", "shell.execute_reply": "2025-03-25T05:54:56.166791Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{'GSM4812195': [1.0, 0.0], 'GSM4812196': [0.0, 0.0], 'GSM4812197': [1.0, 1.0], 'GSM4812198': [0.0, 1.0], 'GSM4812199': [1.0, 0.0], 'GSM4812200': [0.0, 0.0], 'GSM4812201': [1.0, 1.0], 'GSM4812202': [0.0, 1.0], 'GSM4812203': [1.0, 0.0], 'GSM4812204': [0.0, 0.0], 'GSM4812205': [1.0, 1.0], 'GSM4812206': [0.0, 1.0], 'GSM4812207': [1.0, 0.0], 'GSM4812208': [0.0, 0.0], 'GSM4812209': [1.0, 1.0], 'GSM4812210': [0.0, 1.0], 'GSM4812211': [1.0, 0.0], 'GSM4812212': [0.0, 0.0], 'GSM4812213': [1.0, 1.0], 'GSM4812214': [0.0, 1.0], 'GSM4812215': [1.0, 0.0], 'GSM4812216': [0.0, 0.0], 'GSM4812217': [1.0, 1.0], 'GSM4812218': [0.0, 1.0], 'GSM4812219': [1.0, 0.0], 'GSM4812220': [0.0, 0.0], 'GSM4812221': [1.0, 1.0], 'GSM4812222': [0.0, 1.0], 'GSM4812223': [1.0, 0.0], 'GSM4812224': [0.0, 0.0], 'GSM4812225': [1.0, 1.0], 'GSM4812226': [0.0, 1.0], 'GSM4812227': [1.0, 0.0], 'GSM4812228': [0.0, 0.0], 'GSM4812229': [1.0, 1.0], 'GSM4812230': [0.0, 1.0], 'GSM4812231': [1.0, 0.0], 'GSM4812232': [0.0, 0.0], 'GSM4812233': [1.0, 1.0], 'GSM4812234': [0.0, 1.0], 'GSM4812235': [1.0, 0.0], 'GSM4812236': [0.0, 0.0], 'GSM4812237': [1.0, 1.0], 'GSM4812238': [0.0, 1.0], 'GSM4812239': [1.0, 0.0], 'GSM4812240': [0.0, 0.0], 'GSM4812241': [1.0, 1.0], 'GSM4812242': [0.0, 1.0]}\n", "Clinical data saved to ../../output/preprocess/Obesity/clinical_data/GSE158850.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains skeletal muscle transcriptomes\n", "# which indicates gene expression data is available\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait (Obesity):\n", "# From the sample characteristics, we have \"disease state: obese\" at key 3\n", "# and \"time point: baseline\" vs \"time point: after lifestyle intervention\" at key 4\n", "# The trait we're studying is Obesity, and we can infer it from the time point\n", "# since we're comparing before and after a weight loss intervention\n", "trait_row = 4 # Using time point as a proxy for obesity status\n", "\n", "# For age:\n", "# From the sample characteristics, we have \"age group: Young\" vs \"age group: Elderly\" at key 2\n", "age_row = 2\n", "\n", "# For gender:\n", "# From the sample characteristics, we have \"Sex: Male\" at key 1, which indicates\n", "# all participants are male (constant feature), so we consider it not available\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert time point value to binary obesity status.\n", " \n", " Before intervention (baseline) = 1 (obese)\n", " After intervention = 0 (less obese)\n", " \"\"\"\n", " if isinstance(value, str):\n", " value = value.lower().strip()\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if \"baseline\" in value:\n", " return 1 # Obese at baseline\n", " elif \"after\" in value:\n", " return 0 # Less obese after intervention\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age group value to binary age category.\n", " \n", " Young = 0\n", " Elderly = 1\n", " \"\"\"\n", " if isinstance(value, str):\n", " value = value.lower().strip()\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if \"young\" in value:\n", " return 0\n", " elif \"elderly\" in value:\n", " return 1\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender value to binary.\n", " \n", " Female = 0\n", " Male = 1\n", " \n", " Not used in this dataset as all participants are male.\n", " \"\"\"\n", " if isinstance(value, str):\n", " value = value.lower().strip()\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if \"female\" in value:\n", " return 0\n", " elif \"male\" in value:\n", " return 1\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Conduct initial filtering and save information\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", "if trait_row is not None:\n", " # Extract clinical features\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 features\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Save the clinical data to a CSV file\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "921b57bc", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "927fef11", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:54:56.168184Z", "iopub.status.busy": "2025-03-25T05:54:56.168083Z", "iopub.status.idle": "2025-03-25T05:54:56.372915Z", "shell.execute_reply": "2025-03-25T05:54:56.372545Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First 20 gene/probe identifiers:\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. First get the file paths again to access the matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_data from the matrix_file\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# 3. Print the first 20 row IDs (gene or probe identifiers) for future observation\n", "print(\"First 20 gene/probe identifiers:\")\n", "print(gene_data.index[:20])\n" ] }, { "cell_type": "markdown", "id": "a42ed723", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "3cb9334d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:54:56.374259Z", "iopub.status.busy": "2025-03-25T05:54:56.374139Z", "iopub.status.idle": "2025-03-25T05:54:56.375985Z", "shell.execute_reply": "2025-03-25T05:54:56.375723Z" } }, "outputs": [], "source": [ "# The gene identifiers in this dataset (like 'A_23_P100001') are Agilent probe IDs, not human gene symbols.\n", "# These are probe identifiers from an Agilent microarray platform and need to be mapped to official gene symbols.\n", "# These IDs follow the Agilent naming convention with format \"A_23_P######\" which are platform-specific probe IDs.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "940aa30d", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "a825e54d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:54:56.377122Z", "iopub.status.busy": "2025-03-25T05:54:56.377024Z", "iopub.status.idle": "2025-03-25T05:54:59.331497Z", "shell.execute_reply": "2025-03-25T05:54:59.331129Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107', '(+)E1A_r60_a135'], 'SPOT_ID': ['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107', '(+)E1A_r60_a135'], 'CONTROL_TYPE': ['pos', 'pos', 'pos', 'pos', 'pos'], 'REFSEQ': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan], 'GENE': [nan, nan, nan, nan, nan], 'GENE_SYMBOL': [nan, nan, nan, nan, nan], 'GENE_NAME': [nan, nan, nan, nan, nan], 'UNIGENE_ID': [nan, nan, nan, nan, nan], 'ENSEMBL_ID': [nan, nan, nan, nan, nan], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': [nan, nan, nan, nan, nan], 'CHROMOSOMAL_LOCATION': [nan, nan, nan, nan, nan], 'CYTOBAND': [nan, nan, nan, nan, nan], 'DESCRIPTION': [nan, nan, nan, nan, nan], 'GO_ID': [nan, nan, nan, nan, nan], 'SEQUENCE': [nan, nan, nan, nan, nan]}\n" ] } ], "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": "cb4cb7c1", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "3728e062", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:54:59.332800Z", "iopub.status.busy": "2025-03-25T05:54:59.332675Z", "iopub.status.idle": "2025-03-25T05:55:00.117868Z", "shell.execute_reply": "2025-03-25T05:55:00.117488Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data has been processed and saved to ../../output/preprocess/Obesity/gene_data/GSE158850.csv\n", "Number of genes in the processed data: 19447\n", "Preview of processed gene data:\n", " GSM4812195 GSM4812196 GSM4812197 GSM4812198 GSM4812199 \\\n", "Gene \n", "A1BG -6.346192 -6.284652 -6.555014 -5.325181 -5.702537 \n", "A1BG-AS1 -0.094500 -0.286431 0.034552 0.555810 -0.188718 \n", "A1CF -2.590942 -2.309197 -2.679292 -2.385138 -2.853777 \n", "\n", " GSM4812200 GSM4812201 GSM4812202 GSM4812203 GSM4812204 ... \\\n", "Gene ... \n", "A1BG -6.670208 -6.870791 -7.228066 -3.628051 -3.890610 ... \n", "A1BG-AS1 0.401974 -0.358381 0.251461 0.700686 0.158606 ... \n", "A1CF -2.727571 -3.005896 -2.766465 -1.226089 -1.441245 ... \n", "\n", " GSM4812233 GSM4812234 GSM4812235 GSM4812236 GSM4812237 \\\n", "Gene \n", "A1BG -4.139460 -3.387793 -3.392907 -3.663986 -3.911451 \n", "A1BG-AS1 -0.071149 -0.175127 -0.223059 -0.040320 0.265290 \n", "A1CF -1.682867 -1.151579 -1.063105 -1.379817 -1.666449 \n", "\n", " GSM4812238 GSM4812239 GSM4812240 GSM4812241 GSM4812242 \n", "Gene \n", "A1BG -3.263714 -4.564359 -4.598719 -4.757761 -4.039848 \n", "A1BG-AS1 -0.248500 0.422232 0.074208 -0.062674 -0.136899 \n", "A1CF -1.555213 -1.096951 -1.436406 -1.778076 -1.474446 \n", "\n", "[3 rows x 48 columns]\n" ] } ], "source": [ "# Step 1: Identify which columns in the gene annotation to use for mapping\n", "# Looking at the gene_annotation preview, we need to match 'ID' from annotation with row indices in gene_data.\n", "# The 'GENE_SYMBOL' column contains the gene symbols we want to map to.\n", "\n", "# Step 2: Get a gene mapping dataframe from the gene annotation dataframe\n", "mapping_data = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')\n", "\n", "# Step 3: Apply the gene mapping to convert probe-level data to gene-level data\n", "gene_data = apply_gene_mapping(gene_data, mapping_data)\n", "\n", "# Normalize gene symbols to handle synonyms and aggregate rows with the same normalized symbol\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "\n", "# Save the processed gene expression data\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"Gene expression data has been processed and saved to {out_gene_data_file}\")\n", "print(f\"Number of genes in the processed data: {len(gene_data)}\")\n", "print(f\"Preview of processed gene data:\")\n", "print(gene_data.head(3))\n" ] }, { "cell_type": "markdown", "id": "f0fe07f9", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "09804434", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:55:00.119161Z", "iopub.status.busy": "2025-03-25T05:55:00.119041Z", "iopub.status.idle": "2025-03-25T05:55:08.764652Z", "shell.execute_reply": "2025-03-25T05:55:08.763888Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Loaded clinical data with shape: (2, 48)\n", "Linked data shape: (48, 19449)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After handling missing values, linked data shape: (48, 19449)\n", "For the feature 'Obesity', the least common label is '1.0' with 24 occurrences. This represents 50.00% of the dataset.\n", "The distribution of the feature 'Obesity' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 0.0\n", " 50% (Median): 0.5\n", " 75%: 1.0\n", "Min: 0.0\n", "Max: 1.0\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n", "Is trait biased: False\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Obesity/GSE158850.csv\n" ] } ], "source": [ "# 1. Normalize the obtained gene data\n", "# Note: normalized_gene_data was already created in Step 6 when we applied normalize_gene_symbols_in_index\n", "# and saved to out_gene_data_file, so we can just use gene_data which is already normalized\n", "\n", "# 2. Load the previously saved clinical data\n", "clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)\n", "print(f\"Loaded clinical data with shape: {clinical_df.shape}\")\n", "\n", "# 3. Link the clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_df, gene_data)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "\n", "# 4. Handle missing values in the linked data systematically\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"After handling missing values, linked data shape: {linked_data.shape}\")\n", "\n", "# 5. Determine whether the trait and demographic features are severely biased\n", "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "print(f\"Is trait biased: {is_biased}\")\n", "\n", "# 6. Conduct final quality validation and save cohort information\n", "note = \"This dataset compares skeletal muscle adaptations before and after a weight loss intervention in young and elderly obese men.\"\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True, \n", " cohort=cohort, \n", " info_path=json_path, \n", " is_gene_available=is_gene_available, \n", " is_trait_available=is_trait_available,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=note\n", ")\n", "\n", "# 7. If the linked data is usable, save it\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Dataset is not usable for trait-gene association studies.\")" ] } ], "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 }