{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "8b2d72eb", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:02:44.234556Z", "iopub.status.busy": "2025-03-25T06:02:44.234458Z", "iopub.status.idle": "2025-03-25T06:02:44.395962Z", "shell.execute_reply": "2025-03-25T06:02:44.395627Z" } }, "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 = \"GSE126133\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Ovarian_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Ovarian_Cancer/GSE126133\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Ovarian_Cancer/GSE126133.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Ovarian_Cancer/gene_data/GSE126133.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Ovarian_Cancer/clinical_data/GSE126133.csv\"\n", "json_path = \"../../output/preprocess/Ovarian_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "e644ff33", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "5536f817", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:02:44.397350Z", "iopub.status.busy": "2025-03-25T06:02:44.397218Z", "iopub.status.idle": "2025-03-25T06:02:44.529141Z", "shell.execute_reply": "2025-03-25T06:02:44.528804Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Distinct fibroblast functional states drive clinical outcomes in ovarian cancer and are regulated by TCF21\"\n", "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n", "!Series_overall_design\t\"Refer to individual Series\"\n", "Sample Characteristics Dictionary:\n", "{0: ['subject id: 65846', 'subject id: 67794', 'subject id: 68584', 'subject id: 70535', 'subject id: 70924', 'subject id: 71029', 'subject id: 71377', 'subject id: 71423', 'subject id: 71853', 'subject id: 72130', 'subject id: 72143', 'subject id: 72199'], 1: ['tissue: high-grade serous ovarian cancer (HGSOC)'], 2: ['cell marker: CD31-CD45-EpCAM-CD49e+', 'cell marker: CD31-CD45-EpCAM+CD133+', 'cell marker: CD31-CD45-EpCAM+CD133-'], 3: ['cell type: CAF', 'cell type: epithelial']}\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": "f397b98f", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "6c260d55", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:02:44.530314Z", "iopub.status.busy": "2025-03-25T06:02:44.530210Z", "iopub.status.idle": "2025-03-25T06:02:44.537292Z", "shell.execute_reply": "2025-03-25T06:02:44.537012Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{0: [1.0], 1: [0.0], 2: [1.0], 3: [0.0], 4: [1.0], 5: [0.0], 6: [1.0], 7: [0.0], 8: [1.0], 9: [0.0], 10: [1.0], 11: [0.0]}\n", "Clinical data saved to ../../output/preprocess/Ovarian_Cancer/clinical_data/GSE126133.csv\n" ] } ], "source": [ "import pandas as pd\n", "import numpy as np\n", "import os\n", "\n", "# First, analyze the metadata and determine if this dataset is suitable\n", "# Create the clinical_data DataFrame with the sample characteristics\n", "clinical_data = pd.DataFrame({0: ['subject id: 65846', 'subject id: 67794', 'subject id: 68584', 'subject id: 70535', 'subject id: 70924', 'subject id: 71029', 'subject id: 71377', 'subject id: 71423', 'subject id: 71853', 'subject id: 72130', 'subject id: 72143', 'subject id: 72199'], \n", " 1: ['tissue: high-grade serous ovarian cancer (HGSOC)'] * 12, \n", " 2: ['cell marker: CD31-CD45-EpCAM-CD49e+', 'cell marker: CD31-CD45-EpCAM+CD133+', 'cell marker: CD31-CD45-EpCAM+CD133-'] * 4, \n", " 3: ['cell type: CAF', 'cell type: epithelial'] * 6})\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background and the presence of cell markers, this appears to be a gene expression dataset\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait: We can infer this from the cell type (row 3)\n", "trait_row = 3 # Using cell type as it differentiates between CAF and epithelial cells\n", "\n", "# Age and gender are not specified in the sample characteristics\n", "age_row = None\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert cell type to binary: 1 for CAF, 0 for epithelial\"\"\"\n", " if pd.isna(value) or 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()\n", " \n", " if value.lower() == \"caf\":\n", " return 1\n", " elif value.lower() == \"epithelial\":\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Placeholder function for age conversion - not used in this dataset\"\"\"\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Placeholder function for gender conversion - not used in this dataset\"\"\"\n", " return None\n", "\n", "# 3. Save Metadata - initial filtering\n", "# Trait data is available (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", " # Transpose the clinical data to match the expected format\n", " # The geo_select_clinical_features function expects samples as columns\n", " clinical_data_t = clinical_data.transpose()\n", " \n", " # Extract clinical features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data_t,\n", " trait=\"Cell_Type\", \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 selected clinical features\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Save the clinical data\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" ] }, { "cell_type": "markdown", "id": "0604a8df", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "8356e807", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:02:44.538344Z", "iopub.status.busy": "2025-03-25T06:02:44.538244Z", "iopub.status.idle": "2025-03-25T06:02:44.707859Z", "shell.execute_reply": "2025-03-25T06:02:44.707478Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209',\n", " 'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229',\n", " 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236',\n", " 'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253',\n", " 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262'],\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": "d5b409e7", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "2761dff4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:02:44.709166Z", "iopub.status.busy": "2025-03-25T06:02:44.709046Z", "iopub.status.idle": "2025-03-25T06:02:44.710918Z", "shell.execute_reply": "2025-03-25T06:02:44.710637Z" } }, "outputs": [], "source": [ "# These identifiers are Illumina probe IDs (ILMN_xxxxxxx format), not human gene symbols\n", "# They need to be mapped to gene symbols for proper analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "6bfe024b", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "8cb3c6cf", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:02:44.711912Z", "iopub.status.busy": "2025-03-25T06:02:44.711811Z", "iopub.status.idle": "2025-03-25T06:02:48.315614Z", "shell.execute_reply": "2025-03-25T06:02:48.315243Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Species': [nan, nan, nan, nan, nan], 'Source': [nan, nan, nan, nan, nan], 'Search_Key': [nan, nan, nan, nan, nan], 'Transcript': [nan, nan, nan, nan, nan], 'ILMN_Gene': [nan, nan, nan, nan, nan], 'Source_Reference_ID': [nan, nan, nan, nan, nan], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Unigene_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': [nan, nan, nan, nan, nan], 'Symbol': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB'], 'Protein_Product': [nan, nan, nan, nan, 'thrB'], 'Probe_Id': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5090180.0, 6510136.0, 7560739.0, 1450438.0, 1240647.0], 'Probe_Type': [nan, nan, nan, nan, nan], 'Probe_Start': [nan, nan, nan, nan, nan], 'SEQUENCE': ['GAATAAAGAACAATCTGCTGATGATCCCTCCGTGGATCTGATTCGTGTAA', 'CCATGTGATACGAGGGCGCGTAGTTTGCATTATCGTTTTTATCGTTTCAA', 'CCGACAGATGTATGTAAGGCCAACGTGCTCAAATCTTCATACAGAAAGAT', 'TCTGTCACTGTCAGGAAAGTGGTAAAACTGCAACTCAATTACTGCAATGC', 'CTTGTGCCTGAGCTGTCAAAAGTAGAGCACGTCGCCGAGATGAAGGGCGC'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': [nan, nan, nan, nan, nan], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan]}\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": "239674f3", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "a21b02d5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:02:48.316925Z", "iopub.status.busy": "2025-03-25T06:02:48.316800Z", "iopub.status.idle": "2025-03-25T06:02:48.977202Z", "shell.execute_reply": "2025-03-25T06:02:48.976822Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Number of probe-to-gene mappings: 44837\n", "First few mappings:\n", " ID Gene\n", "0 ILMN_1343048 phage_lambda_genome\n", "1 ILMN_1343049 phage_lambda_genome\n", "2 ILMN_1343050 phage_lambda_genome:low\n", "3 ILMN_1343052 phage_lambda_genome:low\n", "4 ILMN_1343059 thrB\n", "After mapping: 21464 genes and 34 samples\n", "First few genes:\n", "Index(['A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1', 'A3GALT2',\n", " 'A4GALT', 'A4GNT'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After normalization: 20259 genes and 34 samples\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Ovarian_Cancer/gene_data/GSE126133.csv\n" ] } ], "source": [ "# 1. Identify the relevant columns for mapping\n", "# From the preview, we can see:\n", "# - 'ID' column contains the probe identifiers (ILMN_xxxxxxx format)\n", "# - 'Symbol' column contains the gene symbols we need\n", "\n", "# 2. Get a gene mapping dataframe using the appropriate columns\n", "mapping_df = get_gene_mapping(gene_annotation, 'ID', 'Symbol')\n", "print(f\"Number of probe-to-gene mappings: {len(mapping_df)}\")\n", "print(\"First few mappings:\")\n", "print(mapping_df.head())\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"After mapping: {gene_data.shape[0]} genes and {gene_data.shape[1]} samples\")\n", "print(\"First few genes:\")\n", "print(gene_data.index[:10])\n", "\n", "# Normalize gene symbols to handle synonyms and aggregate duplicate gene symbols\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"After normalization: {gene_data.shape[0]} genes and {gene_data.shape[1]} samples\")\n", "\n", "# Save the processed gene expression data\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"Gene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "2c67e851", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "e282b379", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:02:48.978668Z", "iopub.status.busy": "2025-03-25T06:02:48.978553Z", "iopub.status.idle": "2025-03-25T06:02:49.037227Z", "shell.execute_reply": "2025-03-25T06:02:49.036825Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data shape: (1, 12)\n", "Gene data shape: (20259, 34)\n", "Clinical data preview:\n", " 0 1 2 3 4 5 6 7 8 9 10 11\n", "Cell_Type 1.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0\n", "Transposed clinical data shape: (1, 12)\n", "Transposed gene data shape: (20259, 34)\n", "Linked data initial shape: (46, 20260)\n", "Linked data preview (first 5 rows, 5 columns):\n", " Cell_Type A1BG A1BG-AS1 A1CF A2M\n", "0 1.0 NaN NaN NaN NaN\n", "1 0.0 NaN NaN NaN NaN\n", "2 1.0 NaN NaN NaN NaN\n", "3 0.0 NaN NaN NaN NaN\n", "4 1.0 NaN NaN NaN NaN\n", "After handling missing values, linked data shape: (0, 1)\n", "Quartiles for 'Cell_Type':\n", " 25%: nan\n", " 50% (Median): nan\n", " 75%: nan\n", "Min: nan\n", "Max: nan\n", "The distribution of the feature 'Cell_Type' in this dataset is fine.\n", "\n", "Abnormality detected in the cohort: GSE126133. Preprocessing failed.\n", "Data quality check failed. Linked data not saved.\n" ] } ], "source": [ "# 1. Gene data has already been normalized in the previous step\n", "# No need to normalize again, we can directly use the gene_data from the previous step\n", "\n", "# 2. Load the clinical data from the file since we need it for linking\n", "# Loading clinical data from file to ensure it's available\n", "clinical_data = pd.read_csv(out_clinical_data_file, index_col=0)\n", "\n", "# Diagnostic information\n", "print(f\"Clinical data shape: {clinical_data.shape}\")\n", "print(f\"Gene data shape: {gene_data.shape}\")\n", "print(\"Clinical data preview:\")\n", "print(clinical_data.head())\n", "\n", "# Ensure proper orientation of the datasets\n", "# Clinical data should have traits as rows and samples as columns\n", "clinical_data_t = clinical_data.T if clinical_data.shape[0] > clinical_data.shape[1] else clinical_data\n", "# Gene data should have genes as rows and samples as columns\n", "gene_data_t = gene_data.T if gene_data.shape[0] < gene_data.shape[1] else gene_data\n", "\n", "print(f\"Transposed clinical data shape: {clinical_data_t.shape}\")\n", "print(f\"Transposed gene data shape: {gene_data_t.shape}\")\n", "\n", "# Link the clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_data_t, gene_data_t)\n", "print(f\"Linked data initial shape: {linked_data.shape}\")\n", "print(\"Linked data preview (first 5 rows, 5 columns):\")\n", "print(linked_data.iloc[:5, :5])\n", "\n", "# 3. Handle missing values in the linked data\n", "linked_data = handle_missing_values(linked_data, \"Cell_Type\") # Using the correct trait name from step 2\n", "print(f\"After handling missing values, linked data shape: {linked_data.shape}\")\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, \"Cell_Type\")\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=\"Dataset contains gene expression from CAF and epithelial cells in ovarian cancer samples.\"\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 }