{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "6cbfcbaa", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:06:54.742090Z", "iopub.status.busy": "2025-03-25T06:06:54.741914Z", "iopub.status.idle": "2025-03-25T06:06:54.904644Z", "shell.execute_reply": "2025-03-25T06:06:54.904338Z" } }, "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 = \"Pancreatic_Cancer\"\n", "cohort = \"GSE236951\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Pancreatic_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Pancreatic_Cancer/GSE236951\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Pancreatic_Cancer/GSE236951.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Pancreatic_Cancer/gene_data/GSE236951.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Pancreatic_Cancer/clinical_data/GSE236951.csv\"\n", "json_path = \"../../output/preprocess/Pancreatic_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "e026bb9e", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "0ed7d0e6", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:06:54.906071Z", "iopub.status.busy": "2025-03-25T06:06:54.905926Z", "iopub.status.idle": "2025-03-25T06:06:54.923244Z", "shell.execute_reply": "2025-03-25T06:06:54.922957Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Gene based immune profiling of vermiform appendix GALT of adult patients with pancreatic cancer or colon diseases.\"\n", "!Series_summary\t\"Differential immune gene expression analysis in appendix GALT between patients with pancreatic cancer versus benign or malignant colon disease using the nanostring ncounter platform.\"\n", "!Series_overall_design\t\"In this study the GALT of appendix was analyzed by RNA expression analysis of ~700 immune related genes using the Pan Cancer Immune Panel from nanostring. Non inflamed normal looking FFPE appendix tissue from sixteen pancreatic cancer patients, nine colon cancer patients, and nine benign colon disease patients was used to compare GALT immune profiles among the three groups.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['disease: Pancreatic ductal adenocarcinoma', 'disease: Colon adenocarcinoma', 'disease: Benign colon disease'], 1: ['neoadjuvant therapy: None', 'neoadjuvant therapy: n.a.'], 2: ['Sex: Male', 'Sex: Female'], 3: ['age: 83 years', 'age: 64 years', 'age: 59 years', 'age: 72 years', 'age: 89 years', 'age: 82 years', 'age: 75 years', 'age: 61 years', 'age: 68 years', 'age: 49 years', 'age: 71 years', 'age: 58 years', 'age: 76 years', 'age: 67 years', 'age: 52 years', 'age: 57 years', 'age: 53 years', 'age: 95 years', 'age: 55 years', 'age: 43 years', 'age: 48 years', 'age: 63 years']}\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": "ff04eda3", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "4c97c447", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:06:54.924232Z", "iopub.status.busy": "2025-03-25T06:06:54.924130Z", "iopub.status.idle": "2025-03-25T06:06:54.933877Z", "shell.execute_reply": "2025-03-25T06:06:54.933622Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of processed clinical data:\n", "{'GSM7587683': [1.0, 83.0, 1.0], 'GSM7587684': [1.0, 64.0, 1.0], 'GSM7587685': [1.0, 59.0, 1.0], 'GSM7587686': [1.0, 64.0, 1.0], 'GSM7587687': [1.0, 72.0, 0.0], 'GSM7587688': [1.0, 72.0, 1.0], 'GSM7587689': [1.0, 89.0, 1.0], 'GSM7587690': [1.0, 59.0, 0.0], 'GSM7587691': [1.0, 64.0, 0.0], 'GSM7587692': [1.0, 82.0, 0.0], 'GSM7587693': [1.0, 75.0, 0.0], 'GSM7587694': [1.0, 61.0, 1.0], 'GSM7587695': [1.0, 59.0, 1.0], 'GSM7587696': [1.0, 68.0, 1.0], 'GSM7587697': [1.0, 49.0, 0.0], 'GSM7587698': [1.0, 71.0, 1.0], 'GSM7587699': [0.0, 68.0, 0.0], 'GSM7587700': [0.0, 58.0, 0.0], 'GSM7587701': [0.0, 76.0, 1.0], 'GSM7587702': [0.0, 67.0, 1.0], 'GSM7587703': [0.0, 52.0, 0.0], 'GSM7587704': [0.0, 57.0, 1.0], 'GSM7587705': [0.0, 72.0, 0.0], 'GSM7587706': [0.0, 59.0, 0.0], 'GSM7587707': [0.0, 53.0, 0.0], 'GSM7587708': [0.0, 95.0, 0.0], 'GSM7587709': [0.0, 53.0, 1.0], 'GSM7587710': [0.0, 55.0, 1.0], 'GSM7587711': [0.0, 43.0, 0.0], 'GSM7587712': [0.0, 71.0, 0.0], 'GSM7587713': [0.0, 48.0, 0.0], 'GSM7587714': [0.0, 43.0, 1.0], 'GSM7587715': [0.0, 55.0, 1.0], 'GSM7587716': [0.0, 63.0, 0.0]}\n", "Clinical data saved to ../../output/preprocess/Pancreatic_Cancer/clinical_data/GSE236951.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Looking at Series_title and Series_summary, this is clearly gene expression data for immune genes\n", "# The nanostring ncounter platform is for gene expression profiling\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "\n", "# For trait (Pancreatic Cancer):\n", "# Looking at row 0 which contains disease information, we can identify patients with pancreatic cancer vs others\n", "trait_row = 0\n", "\n", "# For age:\n", "# Row 3 contains age data\n", "age_row = 3\n", "\n", "# For gender:\n", "# Row 2 contains gender (Sex) data\n", "gender_row = 2\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert disease information to binary trait value (1 for Pancreatic Cancer, 0 for other).\n", " \"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract the value after colon\n", " parts = value.split(': ', 1)\n", " if len(parts) != 2:\n", " return None\n", " \n", " disease = parts[1].strip().lower()\n", " # 1 for Pancreatic Cancer, 0 for others (colon cancer or benign)\n", " if \"pancreatic\" in disease:\n", " return 1\n", " elif \"colon\" in disease or \"benign\" in disease:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"\n", " Convert age string to numerical value.\n", " \"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " parts = value.split(': ', 1)\n", " if len(parts) != 2:\n", " return None\n", " \n", " age_str = parts[1].strip()\n", " # Extract numerical value from strings like \"83 years\"\n", " try:\n", " age = int(age_str.split()[0])\n", " return age\n", " except (ValueError, IndexError):\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"\n", " Convert gender information to binary (0 for female, 1 for male).\n", " \"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " parts = value.split(': ', 1)\n", " if len(parts) != 2:\n", " return None\n", " \n", " gender = parts[1].strip().lower()\n", " if \"female\" in gender:\n", " return 0\n", " elif \"male\" in gender:\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Perform initial filtering - we know trait data is available since trait_row is not None\n", "is_trait_available = trait_row is not None\n", "validate_and_save_cohort_info(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", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # We're going to extract clinical features using the function from the library\n", " # We'll include all three features: trait, age, and gender\n", " clinical_features_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 processed clinical data\n", " print(\"Preview of processed clinical data:\")\n", " print(preview_df(clinical_features_df))\n", " \n", " # Save the processed clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_features_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": "e37bdc5c", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "be9c115f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:06:54.934834Z", "iopub.status.busy": "2025-03-25T06:06:54.934736Z", "iopub.status.idle": "2025-03-25T06:06:54.944292Z", "shell.execute_reply": "2025-03-25T06:06:54.944014Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Index(['A2M', 'ABCB1', 'ABL1', 'ADA', 'ADORA2A', 'AICDA', 'AIRE', 'AKT3',\n", " 'ALCAM', 'AMBP', 'AMICA1', 'ANP32B', 'ANXA1', 'APOE', 'APP', 'ARG1',\n", " 'ARG2', 'ATF1', 'ATF2', 'ATG10'],\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": "816443c4", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "d3131abe", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:06:54.945243Z", "iopub.status.busy": "2025-03-25T06:06:54.945143Z", "iopub.status.idle": "2025-03-25T06:06:54.946786Z", "shell.execute_reply": "2025-03-25T06:06:54.946520Z" } }, "outputs": [], "source": [ "# Review gene identifiers to determine if they need mapping\n", "# The indices shown are valid human gene symbols (e.g., A2M, ABCB1, ABL1, etc.) \n", "# These are standard HGNC gene symbols that don't require mapping to another format\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "2ec40f25", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 6, "id": "8f0dd294", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:06:54.947743Z", "iopub.status.busy": "2025-03-25T06:06:54.947646Z", "iopub.status.idle": "2025-03-25T06:06:55.187398Z", "shell.execute_reply": "2025-03-25T06:06:55.187014Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Pancreatic_Cancer/gene_data/GSE236951.csv\n", "Clinical features shape: (3, 34)\n", "Linked data shape: (34, 729)\n", "Linked data columns: ['Pancreatic_Cancer', 'Age', 'Gender', 'A2M', 'ABCB1']\n", "Using 'Pancreatic_Cancer' as the trait column for handling missing values\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "For the feature 'Pancreatic_Cancer', the least common label is '1.0' with 16 occurrences. This represents 47.06% of the dataset.\n", "The distribution of the feature 'Pancreatic_Cancer' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Quartiles for 'Age':\n", " 25%: 55.5\n", " 50% (Median): 63.5\n", " 75%: 71.75\n", "Min: 43.0\n", "Max: 95.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 17 occurrences. This represents 50.00% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n", "Linked data saved to ../../output/preprocess/Pancreatic_Cancer/GSE236951.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. Load the previously saved clinical data and ensure it's in the right format\n", "clinical_features = pd.read_csv(out_clinical_data_file)\n", "print(\"Clinical features shape:\", clinical_features.shape)\n", "\n", "# Reprocess the clinical data from the original source to ensure correct format\n", "def convert_trait(value):\n", " \"\"\"Convert disease information to binary trait value (1 for Pancreatic Cancer, 0 for other).\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " parts = value.split(': ', 1)\n", " if len(parts) != 2:\n", " return None\n", " \n", " disease = parts[1].strip().lower()\n", " if \"pancreatic\" in disease:\n", " return 1\n", " elif \"colon\" in disease or \"benign\" in disease:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age string to numerical value.\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " parts = value.split(': ', 1)\n", " if len(parts) != 2:\n", " return None\n", " \n", " age_str = parts[1].strip()\n", " try:\n", " age = int(age_str.split()[0])\n", " return age\n", " except (ValueError, IndexError):\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender information to binary (0 for female, 1 for male).\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " parts = value.split(': ', 1)\n", " if len(parts) != 2:\n", " return None\n", " \n", " gender = parts[1].strip().lower()\n", " if \"female\" in gender:\n", " return 0\n", " elif \"male\" in gender:\n", " return 1\n", " else:\n", " return None\n", "\n", "# Re-extract clinical features\n", "clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=0,\n", " convert_trait=convert_trait,\n", " age_row=3,\n", " convert_age=convert_age,\n", " gender_row=2,\n", " convert_gender=convert_gender\n", ")\n", "\n", "# Link the clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_df, normalized_gene_data)\n", "print(\"Linked data shape:\", linked_data.shape)\n", "print(\"Linked data columns:\", linked_data.columns[:5].tolist()) # Print first 5 columns\n", "\n", "# Find the correct trait column in linked_data\n", "# Typically the first non-demographic column after transposition\n", "trait_column = linked_data.columns[0] # Assuming it's the first column\n", "print(f\"Using '{trait_column}' as the trait column for handling missing values\")\n", "\n", "# 3. Handle missing values in the linked data\n", "linked_data = handle_missing_values(linked_data, trait_column)\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_column)\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 pancreatic cancer patients compared with colon diseases (benign and malignant).\"\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 }