{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "96c4b692", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:50:42.006042Z", "iopub.status.busy": "2025-03-25T03:50:42.005857Z", "iopub.status.idle": "2025-03-25T03:50:42.171708Z", "shell.execute_reply": "2025-03-25T03:50:42.171360Z" } }, "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 = \"Rheumatoid_Arthritis\"\n", "cohort = \"GSE121894\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Rheumatoid_Arthritis\"\n", "in_cohort_dir = \"../../input/GEO/Rheumatoid_Arthritis/GSE121894\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Rheumatoid_Arthritis/GSE121894.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Rheumatoid_Arthritis/gene_data/GSE121894.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Rheumatoid_Arthritis/clinical_data/GSE121894.csv\"\n", "json_path = \"../../output/preprocess/Rheumatoid_Arthritis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "ccca13c1", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "0beade0d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:50:42.173126Z", "iopub.status.busy": "2025-03-25T03:50:42.172977Z", "iopub.status.idle": "2025-03-25T03:50:42.304209Z", "shell.execute_reply": "2025-03-25T03:50:42.303860Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Gene expression profile of endothelial cells derived from circulating progenitors issued from patients with rheumatoid arthritis\"\n", "!Series_summary\t\"Synovial neoangiogenesis is an early and crucial event to promote the development of the hyperplasic proliferative pathologic synovium in rheumatoid arthritis (RA). Endothelial cells (ECs) are critical for the formation of new blood vessels since they highly contribute to angiogenesis and vasculogenesis.\"\n", "!Series_summary\t\"To better characterize these cells, our group has studied the gene expression profiles of ECs issued from 18 RA patients compared to 11 healthy controls.\"\n", "!Series_overall_design\t\"ECs derived from circulating endothelial progenitor cells (EPCs) were isolated from peripheral blood of RA patients and controls for RNA extraction and hybridization on Affymetrix microarrays. Gene expression profiles of EPC-derived ECs were determined in basal conditions and also after hypoxic exposure.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['subject status: Rheumatoid arthritis', 'subject status: Healthy control'], 1: ['tissue: peripheral blood'], 2: ['cell type: Endothelial cells (EC) derived from circulating endothelial progenitor cells (EPCs)'], 3: ['treatment: hypoxic exposure', 'treatment: unstimulated']}\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_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": "9920c1e5", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "00a22569", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:50:42.305367Z", "iopub.status.busy": "2025-03-25T03:50:42.305260Z", "iopub.status.idle": "2025-03-25T03:50:42.310108Z", "shell.execute_reply": "2025-03-25T03:50:42.309815Z" } }, "outputs": [], "source": [ "import pandas as pd\n", "import os\n", "from typing import Optional, Callable, Any, Dict\n", "import json\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the series title and summary, this appears to be gene expression data from microarrays\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "trait_row = 0 # 'subject status' indicates RA vs healthy control\n", "age_row = None # Age information is not available in the sample characteristics\n", "gender_row = None # Gender information is not available in the sample characteristics\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value: str) -> int:\n", " \"\"\"Convert trait value to binary (0 for control, 1 for RA)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'rheumatoid arthritis' in value.lower():\n", " return 1 # RA patient\n", " elif 'healthy control' in value.lower():\n", " return 0 # Healthy control\n", " else:\n", " return None # Unknown\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"Convert age value to continuous\"\"\"\n", " # Not used as age data is not available\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"Convert gender value 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\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Conduct initial filtering and save relevant 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", "# Check if trait_row is not None, which means clinical data is available\n", "if trait_row is not None:\n", " # Assuming clinical_data is a DataFrame from a previous step\n", " # Let's load the clinical data\n", " files = os.listdir(in_cohort_dir)\n", " clinical_file = None\n", " for file in files:\n", " if \"characteristics\" in file.lower():\n", " clinical_file = os.path.join(in_cohort_dir, file)\n", " break\n", " \n", " if clinical_file:\n", " clinical_data = pd.read_csv(clinical_file, sep='\\t', header=0)\n", " \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 data\n", " preview = preview_df(selected_clinical_df)\n", " print(f\"Clinical data preview: {preview}\")\n", " \n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the data\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": "8a09d458", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "2b1e5aca", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:50:42.311129Z", "iopub.status.busy": "2025-03-25T03:50:42.311027Z", "iopub.status.idle": "2025-03-25T03:50:42.527684Z", "shell.execute_reply": "2025-03-25T03:50:42.527314Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Index(['100009613_at', '100009676_at', '10000_at', '10001_at', '10002_at',\n", " '100033423_at', '100033424_at', '100033425_at', '100033426_at',\n", " '100033436_at', '100033444_at', '100033453_at', '100033806_at',\n", " '100033820_at', '100037417_at', '100038246_at', '10003_at',\n", " '100048912_at', '100049587_at', '100049716_at'],\n", " dtype='object', name='ID')\n" ] } ], "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": "6b171eee", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "338c8531", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:50:42.528958Z", "iopub.status.busy": "2025-03-25T03:50:42.528851Z", "iopub.status.idle": "2025-03-25T03:50:42.530666Z", "shell.execute_reply": "2025-03-25T03:50:42.530397Z" } }, "outputs": [], "source": [ "# Based on my biomedical knowledge, these are not standard human gene symbols\n", "# The \"_at\" suffix suggests these are likely probe IDs from a microarray platform (e.g., Affymetrix)\n", "# Human gene symbols would typically be in formats like \"BRCA1\", \"TP53\", etc.\n", "# These identifiers will need to be mapped to standard gene symbols for analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "24ac43f9", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "f3390c48", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:50:42.531831Z", "iopub.status.busy": "2025-03-25T03:50:42.531732Z", "iopub.status.idle": "2025-03-25T03:50:44.206805Z", "shell.execute_reply": "2025-03-25T03:50:44.206220Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['1_at', '10_at', '100_at', '1000_at', '10000_at'], 'ENTREZ_GENE_ID': ['1', '10', '100', '1000', '10000'], 'Description': ['alpha-1-B glycoprotein', 'N-acetyltransferase 2 (arylamine N-acetyltransferase)', 'adenosine deaminase', 'cadherin 2, type 1, N-cadherin (neuronal)', 'v-akt murine thymoma viral oncogene homolog 3'], 'SPOT_ID': [1.0, 10.0, 100.0, 1000.0, 10000.0]}\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": "8913cd91", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "1b40836d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:50:44.208689Z", "iopub.status.busy": "2025-03-25T03:50:44.208562Z", "iopub.status.idle": "2025-03-25T03:50:44.410214Z", "shell.execute_reply": "2025-03-25T03:50:44.409525Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation column names: ['ID', 'ENTREZ_GENE_ID', 'Description', 'SPOT_ID']\n", "\n", "First 5 rows of gene annotation data:\n", " ID ENTREZ_GENE_ID Description \\\n", "0 1_at 1 alpha-1-B glycoprotein \n", "1 10_at 10 N-acetyltransferase 2 (arylamine N-acetyltrans... \n", "2 100_at 100 adenosine deaminase \n", "3 1000_at 1000 cadherin 2, type 1, N-cadherin (neuronal) \n", "4 10000_at 10000 v-akt murine thymoma viral oncogene homolog 3 \n", "\n", " SPOT_ID \n", "0 1.0 \n", "1 10.0 \n", "2 100.0 \n", "3 1000.0 \n", "4 10000.0 \n", "\n", "After normalization - First 10 gene symbols:\n", "Index(['A1BG', 'A2M', 'A4GALT', 'AAA1', 'AAR2', 'AATK', 'ABCC11', 'ABCC5',\n", " 'ABCD1', 'ABCE1'],\n", " dtype='object', name='Gene')\n", "\n", "Total number of genes after mapping: 1884\n" ] } ], "source": [ "# 1. Let's see more of the gene annotation data to better understand the available columns\n", "print(\"Gene annotation column names:\", gene_annotation.columns.tolist())\n", "print(\"\\nFirst 5 rows of gene annotation data:\")\n", "print(gene_annotation.head(5))\n", "\n", "# 2. Looking at this microarray data format (Affymetrix), the ENTREZ_GENE_ID is likely \n", "# the most reliable mapping to official gene symbols. Let's use it for mapping.\n", "# However, we need a way to convert Entrez IDs to gene symbols.\n", "\n", "# Since the function apply_gene_mapping will attempt to extract human gene symbols from text,\n", "# we need a column that contains gene symbols or names from which symbols can be extracted.\n", "# The Description column is our best option in this case.\n", "\n", "# Extract the mapping columns\n", "gene_mapping = get_gene_mapping(gene_annotation, 'ID', 'Description')\n", "\n", "# 3. Apply the gene mapping to convert probe-level data to gene-level expression\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "# Normalize the gene symbols to ensure consistency\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "\n", "# Preview the mapped gene data\n", "print(\"\\nAfter normalization - First 10 gene symbols:\")\n", "print(gene_data.index[:10])\n", "print(\"\\nTotal number of genes after mapping:\", len(gene_data))\n" ] }, { "cell_type": "markdown", "id": "4e85b63b", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "795613cc", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:50:44.411957Z", "iopub.status.busy": "2025-03-25T03:50:44.411832Z", "iopub.status.idle": "2025-03-25T03:50:44.964314Z", "shell.execute_reply": "2025-03-25T03:50:44.963676Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data saved to ../../output/preprocess/Rheumatoid_Arthritis/gene_data/GSE121894.csv\n", "Linked data shape before handling missing values: (58, 1885)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape after handling missing values: (58, 1885)\n", "For the feature 'Rheumatoid_Arthritis', the least common label is '0.0' with 22 occurrences. This represents 37.93% of the dataset.\n", "The distribution of the feature 'Rheumatoid_Arthritis' in this dataset is fine.\n", "\n", "A new JSON file was created at: ../../output/preprocess/Rheumatoid_Arthritis/cohort_info.json\n", "Data is usable. Saving to ../../output/preprocess/Rheumatoid_Arthritis/GSE121894.csv\n" ] } ], "source": [ "# 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.\n", "# Note: We already normalized the gene data in the previous step\n", "normalized_gene_data = gene_data.copy()\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Gene data saved to {out_gene_data_file}\")\n", "\n", "# Re-extract clinical features since we need it for linking\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", "# 2. 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_df, normalized_gene_data)\n", "print(f\"Linked data shape before handling missing values: {linked_data.shape}\")\n", "\n", "# 3. 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", "# 4. 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", "# 5. 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=\"Dataset contains gene expression from endothelial cells derived from circulating progenitors of RA patients\"\n", ")\n", "\n", "# 6. If the linked data is usable, save it as a CSV file to 'out_data_file'.\n", "if is_usable:\n", " print(f\"Data is usable. Saving to {out_data_file}\")\n", " unbiased_linked_data.to_csv(out_data_file)\n", "else:\n", " print(\"Data is not usable. Not saving linked data file.\")" ] } ], "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 }