{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "1b24d76c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:59:47.005233Z", "iopub.status.busy": "2025-03-25T06:59:47.005052Z", "iopub.status.idle": "2025-03-25T06:59:47.176302Z", "shell.execute_reply": "2025-03-25T06:59:47.175929Z" } }, "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 = \"GSE56814\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Bone_Density\"\n", "in_cohort_dir = \"../../input/GEO/Bone_Density/GSE56814\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Bone_Density/GSE56814.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Bone_Density/gene_data/GSE56814.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Bone_Density/clinical_data/GSE56814.csv\"\n", "json_path = \"../../output/preprocess/Bone_Density/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "3f2550e0", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "9a019a2d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:59:47.177792Z", "iopub.status.busy": "2025-03-25T06:59:47.177642Z", "iopub.status.idle": "2025-03-25T06:59:47.295647Z", "shell.execute_reply": "2025-03-25T06:59:47.295342Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Gene expression study of blood monocytes in pre- and postmenopausal females with low or high bone mineral density (HuEx-1_0-st-v2)\"\n", "!Series_summary\t\"Comparison of circulating monocytes from pre- and postmenopausal females with low or high bone mineral density (BMD). Circulating monocytes are progenitors of osteoclasts, and produce factors important to bone metabolism. Results provide insight into the role of monocytes in osteoporosis.\"\n", "!Series_summary\t\"We identify osteoporosis genes by microarray analyses of monocytes in high vs. low hip BMD (bone mineral density) subjects.\"\n", "!Series_overall_design\t\"Microarray analyses of monocytes were performed using Affymetrix 1.0 ST arrays in 73 Caucasian females (age: 47-56) with extremely high (mean ZBMD =1.38, n=42, 16 pre- and 26 postmenopausal subjects) or low hip BMD (mean ZBMD=-1.05, n=31, 15 pre- and 16 postmenopausal subjects). Differential gene expression analysis in high vs. low BMD subjects was conducted in the total cohort as well as pre- and post-menopausal subjects.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['gender: Female'], 1: ['bone mineral density: high BMD', 'bone mineral density: low BMD'], 2: ['state: postmenopausal', 'state: premenopausal'], 3: ['cell type: monocytes']}\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": "731351d4", "metadata": {}, "source": [ "### Step 2: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 3, "id": "95b1710a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:59:47.296973Z", "iopub.status.busy": "2025-03-25T06:59:47.296862Z", "iopub.status.idle": "2025-03-25T06:59:47.581886Z", "shell.execute_reply": "2025-03-25T06:59:47.581546Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Bone_Density/gene_data/GSE56814.csv\n", "Clinical data before extraction:\n", " !Sample_geo_accession GSM1369683 \\\n", "0 !Sample_characteristics_ch1 gender: Female \n", "1 !Sample_characteristics_ch1 bone mineral density: high BMD \n", "2 !Sample_characteristics_ch1 state: postmenopausal \n", "3 !Sample_characteristics_ch1 cell type: monocytes \n", "\n", " GSM1369684 GSM1369685 \\\n", "0 gender: Female gender: Female \n", "1 bone mineral density: high BMD bone mineral density: high BMD \n", "2 state: postmenopausal state: postmenopausal \n", "3 cell type: monocytes cell type: monocytes \n", "\n", " GSM1369686 GSM1369687 \\\n", "0 gender: Female gender: Female \n", "1 bone mineral density: high BMD bone mineral density: low BMD \n", "2 state: postmenopausal state: postmenopausal \n", "3 cell type: monocytes cell type: monocytes \n", "\n", " GSM1369688 GSM1369689 \\\n", "0 gender: Female gender: Female \n", "1 bone mineral density: low BMD bone mineral density: high BMD \n", "2 state: postmenopausal state: postmenopausal \n", "3 cell type: monocytes cell type: monocytes \n", "\n", " GSM1369690 GSM1369691 ... \\\n", "0 gender: Female gender: Female ... \n", "1 bone mineral density: high BMD bone mineral density: high BMD ... \n", "2 state: postmenopausal state: postmenopausal ... \n", "3 cell type: monocytes cell type: monocytes ... \n", "\n", " GSM1369746 GSM1369747 \\\n", "0 gender: Female gender: Female \n", "1 bone mineral density: low BMD bone mineral density: low BMD \n", "2 state: premenopausal state: postmenopausal \n", "3 cell type: monocytes cell type: monocytes \n", "\n", " GSM1369748 GSM1369749 \\\n", "0 gender: Female gender: Female \n", "1 bone mineral density: high BMD bone mineral density: high BMD \n", "2 state: premenopausal state: premenopausal \n", "3 cell type: monocytes cell type: monocytes \n", "\n", " GSM1369750 GSM1369751 \\\n", "0 gender: Female gender: Female \n", "1 bone mineral density: high BMD bone mineral density: high BMD \n", "2 state: postmenopausal state: postmenopausal \n", "3 cell type: monocytes cell type: monocytes \n", "\n", " GSM1369752 GSM1369753 \\\n", "0 gender: Female gender: Female \n", "1 bone mineral density: low BMD bone mineral density: high BMD \n", "2 state: premenopausal state: premenopausal \n", "3 cell type: monocytes cell type: monocytes \n", "\n", " GSM1369754 GSM1369755 \n", "0 gender: Female gender: Female \n", "1 bone mineral density: low BMD bone mineral density: low BMD \n", "2 state: premenopausal state: postmenopausal \n", "3 cell type: monocytes cell type: monocytes \n", "\n", "[4 rows x 74 columns]\n", "Clinical features after extraction:\n", " GSM1369683 GSM1369684 GSM1369685 GSM1369686 GSM1369687 \\\n", "Bone_Density 1.0 1.0 1.0 1.0 0.0 \n", "\n", " GSM1369688 GSM1369689 GSM1369690 GSM1369691 GSM1369692 ... \\\n", "Bone_Density 0.0 1.0 1.0 1.0 1.0 ... \n", "\n", " GSM1369746 GSM1369747 GSM1369748 GSM1369749 GSM1369750 \\\n", "Bone_Density 0.0 0.0 1.0 1.0 1.0 \n", "\n", " GSM1369751 GSM1369752 GSM1369753 GSM1369754 GSM1369755 \n", "Bone_Density 1.0 0.0 1.0 0.0 0.0 \n", "\n", "[1 rows x 73 columns]\n", "Clinical data saved to ../../output/preprocess/Bone_Density/clinical_data/GSE56814.csv\n", "Linked data preview:\n", " Bone_Density\n", "GSM1369683 1.0\n", "GSM1369684 1.0\n", "GSM1369685 1.0\n", "GSM1369686 1.0\n", "GSM1369687 0.0\n", "Quartiles for 'Bone_Density':\n", " 25%: nan\n", " 50% (Median): nan\n", " 75%: nan\n", "Min: nan\n", "Max: nan\n", "The distribution of the feature 'Bone_Density' in this dataset is fine.\n", "\n", "Abnormality detected in the cohort: GSE56814. Preprocessing failed.\n", "Data was determined to be unusable and was not saved\n" ] } ], "source": [ "# 1. Get gene expression data from the matrix file\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# 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. Select clinical features from the clinical data\n", "# Based on the sample characteristics, we need to extract relevant clinical features\n", "print(\"Clinical data before extraction:\")\n", "print(clinical_data.head())\n", "\n", "def convert_bmd(value):\n", " if isinstance(value, str):\n", " if 'high BMD' in value:\n", " return 1\n", " elif 'low BMD' in value:\n", " return 0\n", " return None\n", "\n", "# Row 1 contains bone mineral density information\n", "clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=1,\n", " convert_trait=convert_bmd\n", ")\n", "\n", "print(\"Clinical features after extraction:\")\n", "print(clinical_features)\n", "\n", "# Save clinical data\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "clinical_features.to_csv(out_clinical_data_file)\n", "print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "\n", "# 3. Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n", "print(\"Linked data preview:\")\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", "\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=\"Dataset contains bone mineral density information categorized as high or low BMD.\"\n", ")\n", "\n", "# 7. If the linked data is usable, save it as a CSV file\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": "ca927ae1", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "ac5df793", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:59:47.583409Z", "iopub.status.busy": "2025-03-25T06:59:47.583285Z", "iopub.status.idle": "2025-03-25T06:59:47.588753Z", "shell.execute_reply": "2025-03-25T06:59:47.588437Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data file not found at: ../../input/GEO/Bone_Density/GSE56814/clinical_characteristics.csv\n", "Based on previous output, clinical data was already processed but the cohort was marked as unusable.\n", "Dataset analysis completed.\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Callable, Optional, Dict, Any\n", "\n", "# From the previous output, we can see:\n", "# - Gene data is available (was normalized and saved)\n", "# - Clinical data features show gender, bone mineral density, menopausal state, and cell type\n", "\n", "# 1. Gene Expression Data Availability\n", "is_gene_available = True # Gene expression data is available\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Identify rows containing trait, age, and gender information\n", "trait_row = 1 # \"bone mineral density: low BMD\" is in row 1\n", "age_row = None # Age doesn't appear to be available in the sample characteristics\n", "gender_row = 0 # \"gender: Female\" is in row 0\n", "\n", "# 2.2 Define conversion functions\n", "def convert_trait(value):\n", " if pd.isna(value):\n", " return None\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip().lower()\n", " \n", " if \"high bmd\" in value:\n", " return 1.0\n", " elif \"low bmd\" in value:\n", " return 0.0\n", " else:\n", " return None\n", "\n", "# Age conversion function not needed as age_row is None\n", "convert_age = None\n", "\n", "def convert_gender(value):\n", " if pd.isna(value):\n", " return None\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip().lower()\n", " \n", " if \"female\" in value:\n", " return 0\n", " elif \"male\" in value:\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata for initial filtering\n", "is_trait_available = trait_row is not None\n", "initial_validation = 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. If we have not already processed the data, proceed with clinical feature extraction\n", "# Use the clinical_data from the previous output if available\n", "if trait_row is not None:\n", " try:\n", " # Try to load the clinical data that may have been created earlier in the pipeline\n", " clinical_data_path = os.path.join(in_cohort_dir, \"clinical_characteristics.csv\")\n", " if os.path.exists(clinical_data_path):\n", " clinical_data = pd.read_csv(clinical_data_path)\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 extracted data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of extracted clinical features:\")\n", " for feature, values in preview.items():\n", " print(f\"{feature}: {values}\")\n", " \n", " # Ensure the output directory exists\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the extracted clinical data\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " else:\n", " print(f\"Clinical data file not found at: {clinical_data_path}\")\n", " print(\"Based on previous output, clinical data was already processed but the cohort was marked as unusable.\")\n", " except Exception as e:\n", " print(f\"Error processing clinical data: {e}\")\n", " print(\"Moving forward with the knowledge that this dataset may have issues.\")\n", "else:\n", " print(\"No trait data available. Skipping clinical feature extraction.\")\n", "\n", "print(\"Dataset analysis completed.\")\n" ] }, { "cell_type": "markdown", "id": "5785cb14", "metadata": {}, "source": [ "### Step 4: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 5, "id": "27dcc109", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:59:47.590004Z", "iopub.status.busy": "2025-03-25T06:59:47.589889Z", "iopub.status.idle": "2025-03-25T06:59:47.777073Z", "shell.execute_reply": "2025-03-25T06:59:47.776718Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Index(['2315554', '2315633', '2315674', '2315739', '2315894', '2315918',\n", " '2315951', '2316218', '2316245', '2316379', '2316558', '2316605',\n", " '2316746', '2316905', '2316953', '2317246', '2317317', '2317434',\n", " '2317472', '2317512'],\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": "f4fa7649", "metadata": {}, "source": [ "### Step 5: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 6, "id": "f22b7f26", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:59:47.778464Z", "iopub.status.busy": "2025-03-25T06:59:47.778335Z", "iopub.status.idle": "2025-03-25T06:59:47.780292Z", "shell.execute_reply": "2025-03-25T06:59:47.780008Z" } }, "outputs": [], "source": [ "# These identifiers don't appear to be human gene symbols\n", "# They look like probe IDs from a microarray platform\n", "# Looking at the numeric format (2315554, etc.), these are likely Illumina or Affymetrix probe IDs\n", "# They will need to be mapped to human gene symbols for meaningful analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "5df9778e", "metadata": {}, "source": [ "### Step 6: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 7, "id": "0787f3e8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:59:47.781543Z", "iopub.status.busy": "2025-03-25T06:59:47.781434Z", "iopub.status.idle": "2025-03-25T06:59:51.371548Z", "shell.execute_reply": "2025-03-25T06:59:51.371021Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['2315100', '2315106', '2315109', '2315111', '2315113'], 'GB_LIST': ['NR_024005,NR_034090,NR_024004,AK093685', 'DQ786314', nan, nan, 'DQ786265'], 'SPOT_ID': ['chr1:11884-14409', 'chr1:14760-15198', 'chr1:19408-19712', 'chr1:25142-25532', 'chr1:27563-27813'], 'seqname': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], 'RANGE_GB': ['NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10'], 'RANGE_STRAND': ['+', '+', '+', '+', '+'], 'RANGE_START': ['11884', '14760', '19408', '25142', '27563'], 'RANGE_STOP': ['14409', '15198', '19712', '25532', '27813'], 'total_probes': ['20', '8', '4', '4', '4'], 'gene_assignment': ['NR_024005 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771 /// NR_034090 // DDX11L9 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 9 // 15q26.3 // 100288486 /// NR_024004 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771 /// AK093685 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771', '---', '---', '---', '---'], 'mrna_assignment': ['NR_024005 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 (DDX11L2), transcript variant 2, non-coding RNA. // chr1 // 100 // 80 // 16 // 16 // 0 /// NR_034090 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 9 (DDX11L9), non-coding RNA. // chr1 // 100 // 80 // 16 // 16 // 0 /// NR_024004 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 (DDX11L2), transcript variant 1, non-coding RNA. // chr1 // 100 // 75 // 15 // 15 // 0 /// AK093685 // GenBank // Homo sapiens cDNA FLJ36366 fis, clone THYMU2007824. // chr1 // 94 // 80 // 15 // 16 // 0 /// ENST00000513886 // ENSEMBL // cdna:known chromosome:GRCh37:16:61555:64090:1 gene:ENSG00000233614 // chr1 // 100 // 80 // 16 // 16 // 0 /// ENST00000456328 // ENSEMBL // cdna:known chromosome:GRCh37:1:11869:14409:1 gene:ENSG00000223972 // chr1 // 100 // 80 // 16 // 16 // 0 /// ENST00000518655 // ENSEMBL // cdna:known chromosome:GRCh37:1:11869:14409:1 gene:ENSG00000253101 // chr1 // 100 // 80 // 16 // 16 // 0', 'DQ786314 // GenBank // Homo sapiens clone HLS_IMAGE_811138 mRNA sequence. // chr1 // 100 // 38 // 3 // 3 // 0', '---', '---', 'DQ786265 // GenBank // Homo sapiens clone HLS_IMAGE_298685 mRNA sequence. // chr1 // 100 // 100 // 4 // 4 // 0'], 'category': ['main', 'main', '---', '---', 'main']}\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": "33bf7081", "metadata": {}, "source": [ "### Step 7: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 8, "id": "86a4837c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:59:51.373126Z", "iopub.status.busy": "2025-03-25T06:59:51.373015Z", "iopub.status.idle": "2025-03-25T06:59:51.844303Z", "shell.execute_reply": "2025-03-25T06:59:51.843750Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping preview (first 5 rows):\n", " ID Gene\n", "0 2315100 NR_024005 // DDX11L2 // DEAD/H (Asp-Glu-Ala-As...\n", "1 2315106 ---\n", "2 2315109 ---\n", "3 2315111 ---\n", "4 2315113 ---\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data after mapping - shape: (48895, 73)\n", "First 5 gene symbols and first 3 samples:\n", " GSM1369683 GSM1369684 GSM1369685\n", "Gene \n", "A- 18.363212 19.338694 19.496579\n", "A-2 3.049234 3.030850 2.939030\n", "A-52 4.685952 4.691996 4.603244\n", "A-E 1.581215 1.632573 1.682945\n", "A-I 5.532182 5.607333 5.265896\n" ] } ], "source": [ "# 1. Determine which columns to use for mapping\n", "# From the gene annotation preview, I can see:\n", "# - 'ID' column contains identifiers that match the row IDs seen in the gene expression data\n", "# - 'gene_assignment' column contains gene symbol information\n", "\n", "# 2. Extract gene mapping from the annotation dataframe\n", "# Create the mapping dataframe with the probe IDs and gene symbols\n", "gene_mapping = get_gene_mapping(\n", " annotation=gene_annotation,\n", " prob_col=\"ID\",\n", " gene_col=\"gene_assignment\"\n", ")\n", "\n", "print(\"Gene mapping preview (first 5 rows):\")\n", "print(gene_mapping.head())\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=gene_mapping)\n", "\n", "print(f\"Gene data after mapping - shape: {gene_data.shape}\")\n", "print(\"First 5 gene symbols and first 3 samples:\")\n", "print(gene_data.iloc[:5, :3])\n" ] }, { "cell_type": "markdown", "id": "88a96fa8", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 9, "id": "bab1d929", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:59:51.846180Z", "iopub.status.busy": "2025-03-25T06:59:51.846054Z", "iopub.status.idle": "2025-03-25T07:00:03.071359Z", "shell.execute_reply": "2025-03-25T07:00:03.070865Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Bone_Density/gene_data/GSE56814.csv\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "For the feature 'Bone_Density', the least common label is '0.0' with 31 occurrences. This represents 42.47% of the dataset.\n", "The distribution of the feature 'Bone_Density' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Bone_Density/GSE56814.csv\n" ] } ], "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 link with genetic data\n", "clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)\n", "linked_data = geo_link_clinical_genetic_data(clinical_df, normalized_gene_data)\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, 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(True, cohort, json_path, True, True, is_trait_biased, unbiased_linked_data)\n", "\n", "# 6. If the linked data is usable, save it as a CSV file to 'out_data_file'.\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": { "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 }