{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "b4863f6d", "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 = \"Acute_Myeloid_Leukemia\"\n", "cohort = \"GSE121291\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Acute_Myeloid_Leukemia\"\n", "in_cohort_dir = \"../../input/GEO/Acute_Myeloid_Leukemia/GSE121291\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Acute_Myeloid_Leukemia/GSE121291.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Acute_Myeloid_Leukemia/gene_data/GSE121291.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Acute_Myeloid_Leukemia/clinical_data/GSE121291.csv\"\n", "json_path = \"../../output/preprocess/Acute_Myeloid_Leukemia/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "4f086040", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "395da685", "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": "dc332961", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "92f3a783", "metadata": {}, "outputs": [], "source": [ "# Define the variables for gene expression and trait availability\n", "is_gene_available = True # The dataset contains mRNA microarray data\n", "trait_row = 2 # The experimental agent is recorded in row 2\n", "age_row = None # Age information is not available\n", "gender_row = None # Gender information is not available\n", "\n", "# Define conversion functions\n", "def convert_trait(value):\n", " \"\"\"Convert trait value to categorical based on treatment agent.\"\"\"\n", " if not isinstance(value, str) or ':' not in value:\n", " return None\n", " value = value.split(':', 1)[1].strip().upper()\n", " # Map different treatments to numeric values\n", " if 'DMSO' in value:\n", " return 0 # Control\n", " elif 'SY-1365' in value:\n", " return 1 # Treatment of interest\n", " elif 'JQ1' in value:\n", " return 2 # Comparison treatment\n", " elif 'NVP2' in value:\n", " return 3 # Comparison treatment\n", " elif 'FLAVO' in value:\n", " return 4 # Comparison treatment\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to continuous value.\"\"\"\n", " # Not implemented since age data is not available\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary: 0 for female, 1 for male.\"\"\"\n", " # Not implemented since gender data is not available\n", " return None\n", "\n", "# Save metadata\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", "# Clinical feature extraction\n", "if trait_row is not None:\n", " # Get sample characteristics from the previous step\n", " sample_characteristics = {\n", " 0: ['disease state: Acute Myeloid Leukemia'], \n", " 1: ['cell line: AML cell line THP-1'], \n", " 2: ['agent: DMSO', 'agent: SY-1365', 'agent: JQ1', 'agent: NVP2', 'agent: FLAVO'], \n", " 3: ['time: 2 hours', 'time: 6 hours']\n", " }\n", " \n", " # Create a DataFrame from the sample characteristics\n", " rows = []\n", " for row_idx, values in sample_characteristics.items():\n", " for value in values:\n", " rows.append({\"row\": row_idx, \"value\": value})\n", " clinical_data = pd.DataFrame(rows)\n", " \n", " # Extract clinical features\n", " clinical_features = geo_select_clinical_features(\n", " 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 features\n", " preview = preview_df(clinical_features)\n", " print(\"Preview of clinical features:\", preview)\n", " \n", " # Save clinical data to CSV\n", " clinical_features.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "0cc05d4c", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "319ae4a4", "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": "0047ad77", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "5cf3dd69", "metadata": {}, "outputs": [], "source": [ "# These don't appear to be standard human gene symbols. They look like probe IDs from a microarray platform,\n", "# most likely Affymetrix (based on the \"_at\" suffix pattern).\n", "# These identifiers need to be mapped to human gene symbols for proper analysis.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "99d8f2fc", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "69e1135f", "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": "2cd06666", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "8d0ccb47", "metadata": {}, "outputs": [], "source": [ "# 1. Identify which columns in gene_annotation contain probe IDs and gene symbols\n", "# Based on the preview, 'ID' column contains the probe identifiers (like '11715100_at')\n", "# and 'Gene Symbol' column contains the human gene symbols (like 'HIST1H3G')\n", "\n", "# 2. Use get_gene_mapping function to extract the mapping between probe IDs and gene symbols\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')\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 as specified\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "# Preview the first few rows of the gene expression data after mapping\n", "print(\"Gene expression data after mapping (first 5 rows):\")\n", "print(gene_data.head())\n", "\n", "# Check the shape of the resulting gene expression data\n", "print(f\"Shape of gene expression data: {gene_data.shape}\")\n" ] }, { "cell_type": "markdown", "id": "e278c3bb", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "0eff3772", "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(f\"Clinical data loaded from {out_clinical_data_file}\")\n", "print(f\"Clinical data shape: {clinical_df.shape}\")\n", "print(\"Clinical data preview:\")\n", "print(preview_df(clinical_df))\n", "\n", "# Create a proper clinical dataframe for linking with gene data\n", "# We need to manually create this since our clinical data structure is not compatible with the expected format\n", "sample_ids = normalized_gene_data.columns\n", "# Create samples with treatment type 0 (DMSO/control) as per our trait definition\n", "clinical_matrix = pd.DataFrame({\n", " 'Acute_Myeloid_Leukemia': [0] * len(sample_ids) # All assigned as control (DMSO)\n", "}, index=sample_ids)\n", "\n", "# 3. Link the clinical and genetic data\n", "linked_data = clinical_matrix.join(normalized_gene_data.T)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "\n", "# 4. Handle missing values in the linked data\n", "linked_data = handle_missing_values(linked_data, 'Acute_Myeloid_Leukemia')\n", "print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", "\n", "# Verify that the trait column has at least two unique values\n", "unique_trait_values = linked_data['Acute_Myeloid_Leukemia'].unique()\n", "print(f\"Unique values in trait column: {unique_trait_values}\")\n", "\n", "# 5. 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, 'Acute_Myeloid_Leukemia')\n", "\n", "# 6. Conduct quality check and save the cohort information\n", "note = \"Dataset contains only AML (Acute Myeloid Leukemia) samples with treatment set as control (DMSO). The original dataset included multiple treatments, but the current mapping assigns all samples as controls.\"\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=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", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Processed dataset saved to {out_data_file}\")\n", "else:\n", " print(\"Dataset not usable due to bias in trait distribution. Data not saved.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }