{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "bbcad892", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:02:38.457534Z", "iopub.status.busy": "2025-03-25T06:02:38.457347Z", "iopub.status.idle": "2025-03-25T06:02:38.628221Z", "shell.execute_reply": "2025-03-25T06:02:38.627756Z" } }, "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 = \"GSE126132\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Ovarian_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Ovarian_Cancer/GSE126132\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Ovarian_Cancer/GSE126132.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Ovarian_Cancer/gene_data/GSE126132.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Ovarian_Cancer/clinical_data/GSE126132.csv\"\n", "json_path = \"../../output/preprocess/Ovarian_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "f7410f78", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "0b502f0e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:02:38.629531Z", "iopub.status.busy": "2025-03-25T06:02:38.629379Z", "iopub.status.idle": "2025-03-25T06:02:38.765490Z", "shell.execute_reply": "2025-03-25T06:02:38.765014Z" } }, "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\"Recent studies indicate that cancer-associated fibroblasts (CAFs) are phenotypically and functionally heterogeneous. However, little is known about CAF subtypes and the roles they play in cancer progression. Here we identify and characterize two CAF subtypes that coexist within high grade serous ovarian cancers: Fibroblast activation protein (FAP)-high (FH) CAFs resemble the classical myofibroblast-type CAF, whereas FAP-low (FL) CAFs possesses a preadipocyte-like molecular signature.\"\n", "!Series_overall_design\t\"High-grade serous ovarian cancer single cell suspensions of 12 patients were stained for fluorescence activated cell sorting (FACS) CD31-CD45-EpCAM-CD49e+ (CAFs) cells, and CD31-CD45-EpCAM+CD133+ (epithelial) cells were gated for sorting based on FMO controls. Cells were sorted and RNA was extracted immediately using the RNeasy Plus Micro kit (Qiagen).\"\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": "0aa70102", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "c07f3d1f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:02:38.767066Z", "iopub.status.busy": "2025-03-25T06:02:38.766942Z", "iopub.status.idle": "2025-03-25T06:02:38.777176Z", "shell.execute_reply": "2025-03-25T06:02:38.776770Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{'65846': [1.0], '67794': [0.0], '68584': [0.0], '70535': [1.0], '70924': [0.0], '71029': [0.0], '71377': [1.0], '71423': [0.0], '71853': [0.0], '72130': [1.0], '72143': [0.0], '72199': [0.0]}\n", "Clinical features saved to ../../output/preprocess/Ovarian_Cancer/clinical_data/GSE126132.csv\n" ] } ], "source": [ "# Analyze the dataset and extract clinical features\n", "\n", "# 1. Gene Expression Data Availability\n", "is_gene_available = True # Dataset appears to contain gene expression data (not just miRNA or methylation)\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For trait (Ovarian Cancer):\n", "# From the cell type field (key 3), we can identify cancer-associated fibroblasts (CAFs) vs epithelial cells\n", "trait_row = 3 # 'cell type' field contains information about cell types\n", "\n", "# No age information is available in the sample characteristics\n", "age_row = None\n", "\n", "# No gender information is available in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert cell type information to binary trait (0 for non-CAF, 1 for CAF)\"\"\"\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()\n", " \n", " # CAF (cancer-associated fibroblast) is assigned 1, epithelial is assigned 0\n", " if 'CAF' in value:\n", " return 1\n", " elif 'epithelial' in value:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age information (not available in this dataset)\"\"\"\n", " return None # Age data not available\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender information (not available in this dataset)\"\"\"\n", " return None # Gender data not available\n", "\n", "# 3. Save Metadata\n", "# Determine if trait data is available\n", "is_trait_available = trait_row is not None\n", "# Save initial filtering information\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 (only if trait data is available)\n", "if trait_row is not None:\n", " # Sample characteristics dictionary from the output\n", " sample_chars = {\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'],\n", " 1: ['tissue: high-grade serous ovarian cancer (HGSOC)'] * 12, # Repeat for all samples\n", " 2: ['cell marker: CD31-CD45-EpCAM-CD49e+', 'cell marker: CD31-CD45-EpCAM+CD133+', 'cell marker: CD31-CD45-EpCAM+CD133+', \n", " 'cell marker: CD31-CD45-EpCAM-CD49e+', 'cell marker: CD31-CD45-EpCAM+CD133+', 'cell marker: CD31-CD45-EpCAM+CD133-',\n", " 'cell marker: CD31-CD45-EpCAM-CD49e+', 'cell marker: CD31-CD45-EpCAM+CD133+', 'cell marker: CD31-CD45-EpCAM+CD133-',\n", " 'cell marker: CD31-CD45-EpCAM-CD49e+', 'cell marker: CD31-CD45-EpCAM+CD133+', 'cell marker: CD31-CD45-EpCAM+CD133-'],\n", " 3: ['cell type: CAF', 'cell type: epithelial', 'cell type: epithelial', \n", " 'cell type: CAF', 'cell type: epithelial', 'cell type: epithelial',\n", " 'cell type: CAF', 'cell type: epithelial', 'cell type: epithelial',\n", " 'cell type: CAF', 'cell type: epithelial', 'cell type: epithelial']\n", " }\n", " \n", " # Create a DataFrame with proper structure for geo_select_clinical_features\n", " # Rows are feature types, columns are samples\n", " sample_ids = [val.split(': ')[1] for val in sample_chars[0]]\n", " clinical_data = pd.DataFrame(index=sample_chars.keys(), columns=sample_ids)\n", " \n", " # Fill the DataFrame with values\n", " for row_idx, values in sample_chars.items():\n", " for col_idx, value in enumerate(values):\n", " if col_idx < len(sample_ids): # Ensure we don't go out of bounds\n", " clinical_data.loc[row_idx, sample_ids[col_idx]] = value\n", " \n", " # Use the library function to 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 clinical features\n", " preview_result = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview_result)\n", " \n", " # Create the output directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the extracted clinical features to a CSV file\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical features saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "92f056ca", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "3f1b713d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:02:38.778504Z", "iopub.status.busy": "2025-03-25T06:02:38.778393Z", "iopub.status.idle": "2025-03-25T06:02:38.959640Z", "shell.execute_reply": "2025-03-25T06:02:38.959016Z" } }, "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": "0bce8501", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "c3f85f7e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:02:38.961402Z", "iopub.status.busy": "2025-03-25T06:02:38.961251Z", "iopub.status.idle": "2025-03-25T06:02:38.963780Z", "shell.execute_reply": "2025-03-25T06:02:38.963338Z" } }, "outputs": [], "source": [ "# These identifiers (ILMN_*) are Illumina BeadArray probe IDs and not standard human gene symbols.\n", "# They need to be mapped to official gene symbols for analysis.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "64218f23", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "3545ff2e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:02:38.965410Z", "iopub.status.busy": "2025-03-25T06:02:38.965303Z", "iopub.status.idle": "2025-03-25T06:02:42.725950Z", "shell.execute_reply": "2025-03-25T06:02:42.725316Z" } }, "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": "486b763c", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "9f3ad5b7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:02:42.727752Z", "iopub.status.busy": "2025-03-25T06:02:42.727623Z", "iopub.status.idle": "2025-03-25T06:02:42.914660Z", "shell.execute_reply": "2025-03-25T06:02:42.914123Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping preview (first 5 rows):\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", "Shape of the gene expression data after mapping: (21464, 34)\n", "First 5 genes after mapping:\n", "Index(['A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1'], dtype='object', name='Gene')\n" ] } ], "source": [ "# 1. Based on the output from previous steps, we need to map:\n", "# - 'ID' column in gene_annotation to the index of gene_data (ILMN_* identifiers)\n", "# - 'Symbol' column in gene_annotation to get the gene symbols\n", "\n", "# 2. Using get_gene_mapping to extract the ID and Symbol columns from gene_annotation\n", "gene_mapping = get_gene_mapping(gene_annotation, 'ID', 'Symbol')\n", "print(\"Gene mapping preview (first 5 rows):\")\n", "print(gene_mapping.head())\n", "\n", "# 3. Apply the gene mapping to convert probe-level data to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(f\"Shape of the gene expression data after mapping: {gene_data.shape}\")\n", "print(\"First 5 genes after mapping:\")\n", "print(gene_data.index[:5])\n" ] }, { "cell_type": "markdown", "id": "54617c17", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "717af0dc", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:02:42.916481Z", "iopub.status.busy": "2025-03-25T06:02:42.916363Z", "iopub.status.idle": "2025-03-25T06:02:43.475628Z", "shell.execute_reply": "2025-03-25T06:02:43.475008Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Shape of normalized gene data: (20259, 34)\n", "First 5 genes after normalization:\n", "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1'], dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Ovarian_Cancer/gene_data/GSE126132.csv\n", "Clinical data structure:\n", " 65846 67794 68584 70535 70924 71029 71377 71423 71853 \\\n", "Ovarian_Cancer 1.0 0.0 0.0 1.0 0.0 0.0 1.0 0.0 0.0 \n", "\n", " 72130 72143 72199 \n", "Ovarian_Cancer 1.0 0.0 0.0 \n", "Clinical data columns: ['65846', '67794', '68584', '70535', '70924', '71029', '71377', '71423', '71853', '72130', '72143', '72199']\n", "Clinical data shape: (1, 12)\n", "Normalized gene data shape: (20259, 34)\n", "Linked data shape: (46, 20260)\n", "Linked data columns (first 10): ['Ovarian_Cancer', 'A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1']\n", "Linked data trait column null count: 34\n", "Quartiles for 'Ovarian_Cancer':\n", " 25%: nan\n", " 50% (Median): nan\n", " 75%: nan\n", "Min: nan\n", "Max: nan\n", "The distribution of the feature 'Ovarian_Cancer' in this dataset is fine.\n", "\n", "Abnormality detected in the cohort: GSE126132. Preprocessing failed.\n", "Data quality check failed. Linked data not saved.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Shape of normalized gene data: {normalized_gene_data.shape}\")\n", "print(\"First 5 genes after normalization:\")\n", "print(normalized_gene_data.index[:5])\n", "\n", "# Save the normalized gene data to the specified file\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 clinical data from the file\n", "clinical_data = pd.read_csv(out_clinical_data_file, index_col=0)\n", "print(\"Clinical data structure:\")\n", "print(clinical_data.head())\n", "print(\"Clinical data columns:\", clinical_data.columns.tolist())\n", "\n", "# Print diagnostic information\n", "print(\"Clinical data shape:\", clinical_data.shape)\n", "print(\"Normalized gene data shape:\", normalized_gene_data.shape)\n", "\n", "# Make sure clinical data is properly formatted before linking\n", "# Rename the row to match the trait variable name\n", "clinical_data = clinical_data.rename(index={\"Ovarian_Cancer\": trait})\n", "\n", "# Link the clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_data, normalized_gene_data)\n", "print(\"Linked data shape:\", linked_data.shape)\n", "print(\"Linked data columns (first 10):\", linked_data.columns[:10].tolist())\n", "print(\"Linked data trait column null count:\", linked_data[trait].isna().sum())\n", "\n", "# 3. Handle missing values in the linked data\n", "linked_data = handle_missing_values(linked_data, trait)\n", "\n", "# 4. Determine whether 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(\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 data from CAF vs epithelial cells in ovarian cancer patients.\"\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 }