{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "a0809c98", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:02:22.223357Z", "iopub.status.busy": "2025-03-25T06:02:22.223128Z", "iopub.status.idle": "2025-03-25T06:02:22.387996Z", "shell.execute_reply": "2025-03-25T06:02:22.387659Z" } }, "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 = \"Ovarian_Cancer\"\n", "cohort = \"GSE103737\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Ovarian_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Ovarian_Cancer/GSE103737\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Ovarian_Cancer/GSE103737.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Ovarian_Cancer/gene_data/GSE103737.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Ovarian_Cancer/clinical_data/GSE103737.csv\"\n", "json_path = \"../../output/preprocess/Ovarian_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "b0f5bc8a", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "48ff45c1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:02:22.389378Z", "iopub.status.busy": "2025-03-25T06:02:22.389234Z", "iopub.status.idle": "2025-03-25T06:02:22.563350Z", "shell.execute_reply": "2025-03-25T06:02:22.563011Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Transcriptional correlates of high norepinephrine content in ovarian carcinomas\"\n", "!Series_summary\t\"Genome-wide transcriptome profiling was conducted on 97 Stage I-IV ovarian carcinomas classified according to tissue norepinephrine content.\"\n", "!Series_overall_design\t\"To characterize the impact of norepinephrine on ovarian carcinoma biology, we conducted genome-wide transcriptome profiling of 97 clinical ovarian tumors. Tissue norepinephrine content was assessed by high performance liquid chromatogrphy (0=below median value of 1.05 pg/ml;1=above median). Covariates included age (years), body mass index (kg / m^2), tumor stage (1-4), and tumor grade (0=low;1=high).\"\n", "Sample Characteristics Dictionary:\n", "{0: ['subject age: 70', 'subject age: 49', 'subject age: 87', 'subject age: 65', 'subject age: 63', 'subject age: 50', 'subject age: 71', 'subject age: 62', 'subject age: 51', 'subject age: 68', 'subject age: 48', 'subject age: 61', 'subject age: 79', 'subject age: 73', 'subject age: 76', 'subject age: 59', 'subject age: 69', 'subject age: 39', 'subject age: 56', 'subject age: 47', 'subject age: 53', 'subject age: 58', 'subject age: 77', 'subject age: 80', 'subject age: 40', 'subject age: 41', 'subject age: 44', 'subject age: 60', 'subject age: 64', 'subject age: 33'], 1: ['bmi: 23.92', 'bmi: 55.06', 'bmi: 26.47', 'bmi: 35.82', 'bmi: 32.91', 'bmi: 32.15', 'bmi: 31.83', 'bmi: 22.66', 'bmi: 33.66', 'bmi: 24.65', 'bmi: 28.25', 'bmi: 28.26', 'bmi: 35.83', 'bmi: 28.83', 'bmi: 49.28', 'bmi: 29.58', 'bmi: 31.6', 'bmi: 26.29', 'bmi: 32.2', 'bmi: 21.18', 'bmi: 26.59', 'bmi: 24.06', 'bmi: 20.01', 'bmi: 34.57', 'bmi: 24.37', 'bmi: 35.42', 'bmi: 24.54', 'bmi: 19.64', 'bmi: 36.52', 'bmi: 24.5'], 2: ['tissue: ovarian carcinoma'], 3: ['tumor stage: 3', 'tumor stage: 2', 'tumor stage: 4', 'tumor stage: 1'], 4: ['tumor grade (0=low;1=high): 1', 'tumor grade (0=low;1=high): 0'], 5: ['norepinephrine content (0=below median value of 1.05 pg/ml;1=above median): 0', 'norepinephrine content (0=below median value of 1.05 pg/ml;1=above median): 1']}\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": "1caf1f03", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "3dc3fc20", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:02:22.564639Z", "iopub.status.busy": "2025-03-25T06:02:22.564536Z", "iopub.status.idle": "2025-03-25T06:02:22.569088Z", "shell.execute_reply": "2025-03-25T06:02:22.568805Z" } }, "outputs": [], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on series title and overall design, this appears to be gene expression data\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "# From the sample characteristics dictionary:\n", "# - For trait: norepinephrine content is in position 5\n", "# - For age: subject age is in position 0\n", "# - There is no gender information\n", "\n", "trait_row = 5 # norepinephrine content\n", "age_row = 0 # subject age\n", "gender_row = None # gender not available\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert norepinephrine content to binary values (0 or 1).\n", " Format: \"norepinephrine content (0=below median value of 1.05 pg/ml;1=above median): 0/1\"\n", " \"\"\"\n", " if pd.isna(value) or not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon\n", " parts = value.split(':')\n", " if len(parts) < 2:\n", " return None\n", " \n", " value_str = parts[1].strip()\n", " try:\n", " # Convert to integer (already binary)\n", " return int(value_str)\n", " except:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"\n", " Convert age to continuous values.\n", " Format: \"subject age: XX\"\n", " \"\"\"\n", " if pd.isna(value) or not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon\n", " parts = value.split(':')\n", " if len(parts) < 2:\n", " return None\n", " \n", " value_str = parts[1].strip()\n", " try:\n", " # Convert to float\n", " return float(value_str)\n", " except:\n", " return None\n", "\n", "# Gender conversion function not needed as gender data is not available\n", "\n", "# 3. Save Metadata\n", "# Determine if trait data is available\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. Clinical Feature Extraction (only if trait_row is not None)\n", "if trait_row is not None:\n", " # Load the clinical data from the previous step\n", " clinical_data_path = os.path.join(in_cohort_dir, \"clinical_data.pkl\")\n", " if os.path.exists(clinical_data_path):\n", " clinical_data = pd.read_pickle(clinical_data_path)\n", " \n", " # Extract clinical features\n", " clinical_features = 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=None # No gender data\n", " )\n", " \n", " # Preview the extracted features\n", " preview = preview_df(clinical_features)\n", " print(\"Preview of clinical features:\")\n", " print(preview)\n", " \n", " # Save to CSV file\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 features saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "bf824b6a", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "a556ea42", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:02:22.570213Z", "iopub.status.busy": "2025-03-25T06:02:22.570113Z", "iopub.status.idle": "2025-03-25T06:02:22.871473Z", "shell.execute_reply": "2025-03-25T06:02:22.871102Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "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. 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": "3383977d", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "6eccc489", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:02:22.872762Z", "iopub.status.busy": "2025-03-25T06:02:22.872646Z", "iopub.status.idle": "2025-03-25T06:02:22.874522Z", "shell.execute_reply": "2025-03-25T06:02:22.874249Z" } }, "outputs": [], "source": [ "# Reviewing the gene identifiers based on the provided preview\n", "# These appear to be proper human gene symbols. For example:\n", "# A1BG (Alpha-1-B Glycoprotein)\n", "# A2M (Alpha-2-Macroglobulin)\n", "# AAAS (Aladin WD Repeat Nucleoporin)\n", "# AACS (Acetoacetyl-CoA Synthetase)\n", "\n", "# Some might be older gene symbols that have been updated, but they are gene symbols nonetheless,\n", "# not probe IDs that would require mapping.\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "f048969e", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 6, "id": "301fc7d3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:02:22.875658Z", "iopub.status.busy": "2025-03-25T06:02:22.875556Z", "iopub.status.idle": "2025-03-25T06:02:37.553528Z", "shell.execute_reply": "2025-03-25T06:02:37.552985Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Ovarian_Cancer/gene_data/GSE103737.csv\n", "Clinical features saved to ../../output/preprocess/Ovarian_Cancer/clinical_data/GSE103737.csv\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "For the feature 'Ovarian_Cancer', the least common label is '0.0' with 46 occurrences. This represents 47.42% of the dataset.\n", "The distribution of the feature 'Ovarian_Cancer' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 50.0\n", " 50% (Median): 60.0\n", " 75%: 68.0\n", "Min: 29.0\n", "Max: 87.0\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n", "A new JSON file was created at: ../../output/preprocess/Ovarian_Cancer/cohort_info.json\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Ovarian_Cancer/GSE103737.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\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", "\n", "# 2. Re-extract clinical features since they weren't properly saved in a previous step\n", "# Define the conversion functions again\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert norepinephrine content to binary values (0 or 1).\n", " Format: \"norepinephrine content (0=below median value of 1.05 pg/ml;1=above median): 0/1\"\n", " \"\"\"\n", " if pd.isna(value) or not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon\n", " parts = value.split(':')\n", " if len(parts) < 2:\n", " return None\n", " \n", " value_str = parts[1].strip()\n", " try:\n", " # Convert to integer (already binary)\n", " return int(value_str)\n", " except:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"\n", " Convert age to continuous values.\n", " Format: \"subject age: XX\"\n", " \"\"\"\n", " if pd.isna(value) or not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon\n", " parts = value.split(':')\n", " if len(parts) < 2:\n", " return None\n", " \n", " value_str = parts[1].strip()\n", " try:\n", " # Convert to float\n", " return float(value_str)\n", " except:\n", " return None\n", "\n", "# Extract clinical features\n", "clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=5, # norepinephrine content is in position 5\n", " convert_trait=convert_trait,\n", " age_row=0, # subject age is in position 0\n", " convert_age=convert_age,\n", " gender_row=None,\n", " convert_gender=None\n", ")\n", "\n", "# Save clinical features\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 features saved to {out_clinical_data_file}\")\n", "\n", "# Link the clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_features, 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 demographic features are severely biased\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=\"Cohort contains ovarian cancer patients with norepinephrine content data.\"\n", ")\n", "\n", "# 6. If the linked data is usable, save it as a CSV file\n", "if is_usable:\n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " # Save the data\n", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Data quality check failed. Linked data 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 }