{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "f2874b44", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:38:16.038125Z", "iopub.status.busy": "2025-03-25T08:38:16.037889Z", "iopub.status.idle": "2025-03-25T08:38:16.208333Z", "shell.execute_reply": "2025-03-25T08:38:16.207994Z" } }, "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 = \"Depression\"\n", "cohort = \"GSE208668\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Depression\"\n", "in_cohort_dir = \"../../input/GEO/Depression/GSE208668\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Depression/GSE208668.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Depression/gene_data/GSE208668.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Depression/clinical_data/GSE208668.csv\"\n", "json_path = \"../../output/preprocess/Depression/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "106123a8", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "4b0a00c1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:38:16.209680Z", "iopub.status.busy": "2025-03-25T08:38:16.209534Z", "iopub.status.idle": "2025-03-25T08:38:16.303303Z", "shell.execute_reply": "2025-03-25T08:38:16.302971Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Sleep Disturbance and Activation of Cellular and Transcriptional Mechanisms of Inflammation in Older Adults\"\n", "!Series_summary\t\"Genome-wide transcriptional profiling results were used to systematically assess the extent to which transcriptomes of older adults with insomnia show expression of genes that are different from those without insomnia\"\n", "!Series_overall_design\t\"Total RNA obtained from peripheral blood mononuclear cells (PBMCs) of older adults with insomnia disorder who participated in the Behavioral Treatment of Insomnia in Aging study (n = 17) and older adults without insomnia disorder who participated in the Sleep Health and Aging Research (SHARE) study (n = 25) at UCLA.\"\n", "!Series_overall_design\t\"\"\n", "!Series_overall_design\t\"**Please note that raw data was lost and thus is not included in the records**\"\n", "Sample Characteristics Dictionary:\n", "{0: ['insomnia: yes', 'insomnia: no'], 1: ['age: 65', 'age: 75', 'age: 77', 'age: 64', 'age: 60', 'age: 67', 'age: 72', 'age: 62', 'age: 73', 'age: 74', 'age: 68', 'age: 70', 'age: 61', 'age: 66', 'age: 69', 'age: 71', 'age: 63', 'age: 78', 'age: 79', 'age: 80'], 2: ['gender: female', 'gender: male'], 3: ['race: white', 'race: non-white'], 4: ['education (years): 16', 'education (years): 15', 'education (years): 17', 'education (years): 12', 'education (years): 14', 'education (years): 20', 'education (years): 24', 'education (years): 18', 'education (years): 19'], 5: ['bmi: 21.49923325', 'bmi: 26.41070366', 'bmi: 31.28330994', 'bmi: 25.7443676', 'bmi: 31.59882355', 'bmi: 25.72408867', 'bmi: 27.29999924', 'bmi: 21.45385742', 'bmi: 24.88647461', 'bmi: 24.12071037', 'bmi: 26.60000038', 'bmi: 20.5', 'bmi: 30.81934929', 'bmi: 31.29999924', 'bmi: 23.5', 'bmi: 27.39999962', 'bmi: 22.60000038', 'bmi: 21.28', 'bmi: 26.77', 'bmi: 31.45', 'bmi: 18.84', 'bmi: 29.81', 'bmi: 24.96', 'bmi: 26.69', 'bmi: 28.94', 'bmi: 29.52', 'bmi: 27.21', 'bmi: 26.04', 'bmi: 30.42', 'bmi: 20.63'], 6: ['comorbidity: 0.638977647', 'comorbidity: 0.95846647', 'comorbidity: 1.91693294', 'comorbidity: 0', 'comorbidity: 0.319488823', 'comorbidity: 0.689655172', 'comorbidity: 1.379310345'], 7: ['bdi: 13', 'bdi: 7', 'bdi: 4', 'bdi: 0', 'bdi: 5', 'bdi: 14.44', 'bdi: 6', 'bdi: 3', 'bdi: 2', 'bdi: 17', 'bdi: 5.25', 'bdi: 15', 'bdi: 11', 'bdi: 9', 'bdi: 19', 'bdi: 8', 'bdi: 1'], 8: ['bdins: 13', 'bdins: 7', 'bdins: 3', 'bdins: 5', 'bdins: 0', 'bdins: 13.33', 'bdins: 4', 'bdins: 1', 'bdins: 2', 'bdins: 16', 'bdins: 3.16', 'bdins: 11', 'bdins: 6', 'bdins: 8', 'bdins: 18'], 9: ['history of depression: yes', 'history of depression: no']}\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": "ea18a250", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "679b8ad8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:38:16.304682Z", "iopub.status.busy": "2025-03-25T08:38:16.304573Z", "iopub.status.idle": "2025-03-25T08:38:16.310478Z", "shell.execute_reply": "2025-03-25T08:38:16.310184Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Could not find matrix file at ../../input/GEO/Depression/GSE208668/matrix.csv\n", "Clinical data extraction is unavailable for this cohort.\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# The background information mentions \"genome-wide transcriptional profiling\" and specifically mentions \"Total RNA\" \n", "# from PBMCs - this indicates gene expression data. The note about raw data being lost is concerning,\n", "# but since we're working with processed matrix data, we'll proceed cautiously.\n", "is_gene_available = True # The dataset should contain gene expression data\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For the trait (Depression), we need to look at relevant variables in this insomnia study\n", "# From sample characteristics, row 9 contains \"history of depression\" which is relevant for our trait\n", "trait_row = 9\n", "\n", "# Age is available in row 1\n", "age_row = 1\n", "\n", "# Gender is available in row 2\n", "gender_row = 2\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert depression history data to binary format (0 = no, 1 = yes)\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " else:\n", " value = value.strip().lower()\n", " \n", " if value == 'yes':\n", " return 1\n", " elif value == 'no':\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age data to continuous format\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " age_str = value.split(':', 1)[1].strip()\n", " else:\n", " age_str = value.strip()\n", " \n", " try:\n", " return float(age_str)\n", " except ValueError:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender data to binary format (0 = female, 1 = male)\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " gender = value.split(':', 1)[1].strip().lower()\n", " else:\n", " gender = value.strip().lower()\n", " \n", " if gender == 'female':\n", " return 0\n", " elif gender == 'male':\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata - Initial Filtering\n", "# Check if trait data is available\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", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # Load the sample characteristics from the provided dictionary in the previous output\n", " # This assumes that the sample characteristics data is accessible from a matrix file\n", " # We need to load the actual matrix file here\n", " try:\n", " matrix_file = f\"{in_cohort_dir}/matrix.csv\"\n", " clinical_data = pd.read_csv(matrix_file, skiprows=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 dataframe\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Save to CSV\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", " except FileNotFoundError:\n", " print(f\"Could not find matrix file at {in_cohort_dir}/matrix.csv\")\n", " print(\"Clinical data extraction is unavailable for this cohort.\")\n" ] }, { "cell_type": "markdown", "id": "9db35527", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "26d32871", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:38:16.311685Z", "iopub.status.busy": "2025-03-25T08:38:16.311579Z", "iopub.status.idle": "2025-03-25T08:38:16.417946Z", "shell.execute_reply": "2025-03-25T08:38:16.417556Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Depression/GSE208668/GSE208668_series_matrix.txt.gz\n", "Gene data shape: (33210, 42)\n", "First 20 gene/probe identifiers:\n", "Index(['7A5', 'A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1',\n", " 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS', 'AACS', 'AACSL', 'AADAC',\n", " 'AADACL1', 'AADACL2', 'AADACL3', 'AADACL4'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. Get the SOFT and matrix file paths again \n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "print(f\"Matrix file found: {matrix_file}\")\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_data\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " \n", " # 3. Print the first 20 row IDs (gene or probe identifiers)\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20])\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n" ] }, { "cell_type": "markdown", "id": "060aaca8", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "02af87c1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:38:16.419664Z", "iopub.status.busy": "2025-03-25T08:38:16.419542Z", "iopub.status.idle": "2025-03-25T08:38:16.421528Z", "shell.execute_reply": "2025-03-25T08:38:16.421239Z" } }, "outputs": [], "source": [ "# These identifiers appear to be a mix of human gene symbols and potentially some probe identifiers\n", "# Examples like \"A1BG\", \"A2M\", \"AACS\" are valid human gene symbols\n", "# However, some like \"7A5\" and \"AAA1\" may be probe identifiers or alternative names\n", "# Since the majority appear to be gene symbols already, we won't need extensive mapping\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "98f45e73", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 6, "id": "724a8787", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:38:16.423257Z", "iopub.status.busy": "2025-03-25T08:38:16.423149Z", "iopub.status.idle": "2025-03-25T08:38:25.122573Z", "shell.execute_reply": "2025-03-25T08:38:25.121657Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape after normalization: (19539, 42)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Depression/gene_data/GSE208668.csv\n", "Selected clinical data shape: (3, 42)\n", "Clinical data preview:\n", "{'GSM6360934': [1.0, 65.0, 0.0], 'GSM6360935': [0.0, 75.0, 1.0], 'GSM6360936': [1.0, 77.0, 0.0], 'GSM6360937': [0.0, 64.0, 0.0], 'GSM6360938': [1.0, 60.0, 1.0], 'GSM6360939': [1.0, 67.0, 0.0], 'GSM6360940': [1.0, 72.0, 1.0], 'GSM6360941': [0.0, 62.0, 1.0], 'GSM6360942': [0.0, 73.0, 0.0], 'GSM6360943': [0.0, 74.0, 1.0], 'GSM6360944': [0.0, 73.0, 1.0], 'GSM6360945': [0.0, 68.0, 0.0], 'GSM6360946': [0.0, 62.0, 0.0], 'GSM6360947': [1.0, 73.0, 0.0], 'GSM6360948': [0.0, 70.0, 0.0], 'GSM6360949': [0.0, 60.0, 0.0], 'GSM6360950': [1.0, 61.0, 0.0], 'GSM6360951': [0.0, 66.0, 0.0], 'GSM6360952': [0.0, 69.0, 0.0], 'GSM6360953': [0.0, 62.0, 1.0], 'GSM6360954': [1.0, 67.0, 0.0], 'GSM6360955': [1.0, 62.0, 0.0], 'GSM6360956': [0.0, 71.0, 1.0], 'GSM6360957': [0.0, 63.0, 1.0], 'GSM6360958': [1.0, 62.0, 1.0], 'GSM6360959': [0.0, 61.0, 0.0], 'GSM6360960': [1.0, 67.0, 0.0], 'GSM6360961': [0.0, 78.0, 0.0], 'GSM6360962': [1.0, 79.0, 1.0], 'GSM6360963': [0.0, 72.0, 0.0], 'GSM6360964': [0.0, 73.0, 0.0], 'GSM6360965': [1.0, 77.0, 1.0], 'GSM6360966': [0.0, 72.0, 1.0], 'GSM6360967': [1.0, 62.0, 1.0], 'GSM6360968': [0.0, 70.0, 0.0], 'GSM6360969': [1.0, 65.0, 1.0], 'GSM6360970': [1.0, 63.0, 0.0], 'GSM6360971': [0.0, 74.0, 0.0], 'GSM6360972': [0.0, 71.0, 1.0], 'GSM6360973': [0.0, 80.0, 1.0], 'GSM6360974': [0.0, 78.0, 0.0], 'GSM6360975': [1.0, 65.0, 1.0]}\n", "Clinical data saved to ../../output/preprocess/Depression/clinical_data/GSE208668.csv\n", "Linked data shape: (42, 19542)\n", "Linked data preview (first 5 rows, 5 columns):\n", " Depression Age Gender A1BG A1BG-AS1\n", "GSM6360934 1.0 65.0 0.0 7.0892 7.3113\n", "GSM6360935 0.0 75.0 1.0 7.2068 6.9684\n", "GSM6360936 1.0 77.0 0.0 7.0056 7.0698\n", "GSM6360937 0.0 64.0 0.0 7.0628 7.2414\n", "GSM6360938 1.0 60.0 1.0 7.0675 7.0056\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (42, 19541)\n", "For the feature 'Depression', the least common label is '1.0' with 17 occurrences. This represents 40.48% of the dataset.\n", "The distribution of the feature 'Depression' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 63.0\n", " 50% (Median): 68.5\n", " 75%: 73.0\n", "Min: 60.0\n", "Max: 80.0\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n", "For the feature 'Gender', the least common label is '1.0' with 18 occurrences. This represents 42.86% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Depression/GSE208668.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "try:\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\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", "except Exception as e:\n", " print(f\"Error normalizing gene data: {e}\")\n", " normalized_gene_data = gene_data # Use original data if normalization fails\n", " \n", "# 2. Recreate clinical data using correct row indices from step 2\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", "\n", "# Extract clinical features using correct row indices and conversion functions\n", "def convert_trait(value):\n", " \"\"\"Convert depression history data to binary format (0 = no, 1 = yes)\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " else:\n", " value = value.strip().lower()\n", " \n", " if value == 'yes':\n", " return 1\n", " elif value == 'no':\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age data to continuous format\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " age_str = value.split(':', 1)[1].strip()\n", " else:\n", " age_str = value.strip()\n", " \n", " try:\n", " return float(age_str)\n", " except ValueError:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender data to binary format (0 = female, 1 = male)\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " gender = value.split(':', 1)[1].strip().lower()\n", " else:\n", " gender = value.strip().lower()\n", " \n", " if gender == 'female':\n", " return 0\n", " elif gender == 'male':\n", " return 1\n", " else:\n", " return None\n", "\n", "# Use correct row indices identified in step 2\n", "selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait, # Using the trait variable from context (Depression)\n", " trait_row=9, # Using row 9 for depression history as identified in step 2\n", " convert_trait=convert_trait,\n", " age_row=1, # Age data is in row 1\n", " convert_age=convert_age,\n", " gender_row=2, # Gender data is in row 2\n", " convert_gender=convert_gender\n", ")\n", "\n", "print(f\"Selected clinical data shape: {selected_clinical_df.shape}\")\n", "print(\"Clinical data preview:\")\n", "print(preview_df(selected_clinical_df))\n", "\n", "# Save clinical data for future reference\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "selected_clinical_df.to_csv(out_clinical_data_file)\n", "print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "\n", "# 2. Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(\"Linked data preview (first 5 rows, 5 columns):\")\n", "print(linked_data.iloc[:5, :5] if not linked_data.empty else \"Linked data is empty\")\n", "\n", "# 3. Handle missing values\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", "\n", "# 4. Check for bias in features\n", "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# 5. Validate and save 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_biased,\n", " df=linked_data,\n", " note=\"Dataset contains gene expression data from peripheral blood mononuclear cells of older adults with and without depression history, from a study on insomnia disorder.\"\n", ")\n", "\n", "# 6. Save the linked data if usable\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 analysis. No linked data file 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 }