{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "40a1d3d9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:03:35.184221Z", "iopub.status.busy": "2025-03-25T06:03:35.183774Z", "iopub.status.idle": "2025-03-25T06:03:35.352388Z", "shell.execute_reply": "2025-03-25T06:03:35.352034Z" } }, "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 = \"GSE135820\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Ovarian_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Ovarian_Cancer/GSE135820\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Ovarian_Cancer/GSE135820.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Ovarian_Cancer/gene_data/GSE135820.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Ovarian_Cancer/clinical_data/GSE135820.csv\"\n", "json_path = \"../../output/preprocess/Ovarian_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "bc7a6ed9", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "aaadde26", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:03:35.353888Z", "iopub.status.busy": "2025-03-25T06:03:35.353745Z", "iopub.status.idle": "2025-03-25T06:03:35.569531Z", "shell.execute_reply": "2025-03-25T06:03:35.569206Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the directory:\n", "['GSE135820_family.soft.gz', 'GSE135820_series_matrix.txt.gz']\n", "SOFT file: ../../input/GEO/Ovarian_Cancer/GSE135820/GSE135820_family.soft.gz\n", "Matrix file: ../../input/GEO/Ovarian_Cancer/GSE135820/GSE135820_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Development and validation of PrOTYPE (Predictor of high-grade-serous Ovarian carcinoma molecular subTYPE)\"\n", "!Series_summary\t\"Gene expression-based molecular subtypes of high grade serous tubo-ovarian cancer (HGSOC) are distinguished by differential immune and stromal infiltration and may provide opportunities for the development of targeted therapies. Integration of molecular subtypes into clinical trials has been hindered by inconsistent subtyping methodology. Adopting two independent approaches, we derived and internally validated algorithms for molecular subtype prediction from gene-expression array data in 1650 tumors. We applied resulting models to assign labels to 3829 HGSOCs from the Ovarian Tumor Tissue Analysis (OTTA) consortium evaluated on NanoString. Using the labeled NanoString data, we developed, confirmed, and validated a clinical-grade test and prediction tool. We also used the OTTA dataset to evaluate associations between molecular subtype, biological, and clinical features.\"\n", "!Series_summary\t\"A gene expression study from the Ovarian Tumor Tissue Analysis (OTTA) consortium\"\n", "!Series_overall_design\t\"4077 total samples including 3829 unique high-grade serous ovarian cancer specimens plus controls analyzed on a custom NanoString panel including 513 assay genes (housekeeping genes are also present in raw data). Unique clinical samples are denoted as clinical in the specimen title. Biological replicates are denoted as OTTA2014_####_REPB1 where #### matches a clinical sample. Technical replicates are denoted similarly with REPT1 or XSITE in the sample title. XSITE further denotes sample that are technical replicates but run in different laboratories (experimental site). Only a subset of XSITE samples will be replicates of clinical specimens, others are exclusively for control purpose.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['diagnosis: HGSOC', 'diagnosis: non-HGSOC'], 1: ['sample region cellularity: 21-40', 'sample region cellularity: 81-100', 'sample region cellularity: 41-60', 'sample region cellularity: 0-20', 'sample region cellularity: 61-80', 'sample region cellularity: NA'], 2: ['sample region necrosis: <=20%', 'sample region necrosis: none', 'sample region necrosis: >20%', 'sample region necrosis: NA'], 3: ['age at diagnosis: 56', 'age at diagnosis: 58', 'age at diagnosis: 43', 'age at diagnosis: 61', 'age at diagnosis: 75', 'age at diagnosis: 60', 'age at diagnosis: 49', 'age at diagnosis: 64', 'age at diagnosis: 50', 'age at diagnosis: 45', 'age at diagnosis: 57', 'age at diagnosis: 59', 'age at diagnosis: 68', 'age at diagnosis: 66', 'age at diagnosis: 52', 'age at diagnosis: 53', 'age at diagnosis: 79', 'age at diagnosis: 51', 'age at diagnosis: 63', 'age at diagnosis: 55', 'age at diagnosis: 65', 'age at diagnosis: 62', 'age at diagnosis: 41', 'age at diagnosis: 44', 'age at diagnosis: 72', 'age at diagnosis: 69', 'age at diagnosis: 48', 'age at diagnosis: 73', 'age at diagnosis: 74', 'age at diagnosis: 70'], 4: ['Stage: high', 'Stage: low', 'Stage: unknown'], 5: ['residual disease status: none', 'residual disease status: any', 'residual disease status: unknown'], 6: ['brca1 and brca2 germline mutation status: NA', 'brca1 and brca2 germline mutation status: all wildtypes', 'brca1 and brca2 germline mutation status: pathogenic BRCA1 mutation', 'brca1 and brca2 germline mutation status: pathogenic BRCA2 mutation'], 7: ['race/ethnicity: hispanic', 'race/ethnicity: white', 'race/ethnicity: NA', 'race/ethnicity: other'], 8: ['year of diagnosis: 2000-2004', 'year of diagnosis: 2005-2009', 'year of diagnosis: NA', 'year of diagnosis: 2010-2013', 'year of diagnosis: 1994-1999'], 9: ['vital status: dead', 'vital status: alive', 'vital status: unknown'], 10: ['overall survival time: 1026', 'overall survival time: 1817', 'overall survival time: 1403', 'overall survival time: 1039', 'overall survival time: 539', 'overall survival time: 2156', 'overall survival time: 481', 'overall survival time: 1855', 'overall survival time: 156', 'overall survival time: 273', 'overall survival time: 415', 'overall survival time: 1117', 'overall survival time: 1414', 'overall survival time: 2300', 'overall survival time: 161', 'overall survival time: 869', 'overall survival time: 596', 'overall survival time: 492', 'overall survival time: 1590', 'overall survival time: 497', 'overall survival time: 3735', 'overall survival time: 3556', 'overall survival time: 4213', 'overall survival time: 1187', 'overall survival time: 3028', 'overall survival time: 4176', 'overall survival time: 1561', 'overall survival time: 746', 'overall survival time: 3489', 'overall survival time: 2768'], 11: ['progression-free survival time: 412', 'progression-free survival time: 573', 'progression-free survival time: 324', 'progression-free survival time: 306', 'progression-free survival time: 292', 'progression-free survival time: 673', 'progression-free survival time: 357', 'progression-free survival time: 1855', 'progression-free survival time: 156', 'progression-free survival time: 212', 'progression-free survival time: 297', 'progression-free survival time: 629', 'progression-free survival time: 391', 'progression-free survival time: 2300', 'progression-free survival time: 87', 'progression-free survival time: 406', 'progression-free survival time: 335', 'progression-free survival time: 117', 'progression-free survival time: 249', 'progression-free survival time: 1126', 'progression-free survival time: 3556', 'progression-free survival time: 4213', 'progression-free survival time: 315', 'progression-free survival time: 3028', 'progression-free survival time: 2635', 'progression-free survival time: 1561', 'progression-free survival time: 371', 'progression-free survival time: 815', 'progression-free survival time: 436', 'progression-free survival time: 223'], 12: ['study entry delay: 0', 'study entry delay: 25', 'study entry delay: 7', 'study entry delay: 212', 'study entry delay: 173', 'study entry delay: NA', 'study entry delay: 1', 'study entry delay: 18', 'study entry delay: 93', 'study entry delay: 369', 'study entry delay: 21', 'study entry delay: 24', 'study entry delay: 20', 'study entry delay: 188', 'study entry delay: 96', 'study entry delay: 257', 'study entry delay: 2', 'study entry delay: 65', 'study entry delay: 16', 'study entry delay: 203', 'study entry delay: 272', 'study entry delay: 34', 'study entry delay: 155', 'study entry delay: 28', 'study entry delay: 56', 'study entry delay: 8', 'study entry delay: 259', 'study entry delay: 244', 'study entry delay: 4', 'study entry delay: 13'], 13: ['anatomical site: omentum', 'anatomical site: adnexal', 'anatomical site: presumed adnexal', 'anatomical site: peritoneal', 'anatomical site: upper genital track', 'anatomical site: lower genital track', 'anatomical site: NA'], 14: ['experiment site: AOC', 'experiment site: USC', 'experiment site: VAN'], 15: ['site id: AOC', 'site id: AOV', 'site id: CNI', 'site id: DOV', 'site id: GER', 'site id: LAX', 'site id: POC', 'site id: USC', 'site id: RTR', 'site id: SEA', 'site id: UKO', 'site id: VAN', 'site id: WMH', 'site id: HAW', 'site id: MAY', 'site id: NCO', 'site id: POL', 'site id: SRF', 'site id: TRI', 'site id: BRO']}\n" ] } ], "source": [ "# 1. Check what files are actually in the directory\n", "import os\n", "print(\"Files in the directory:\")\n", "files = os.listdir(in_cohort_dir)\n", "print(files)\n", "\n", "# 2. Find appropriate files with more flexible pattern matching\n", "soft_file = None\n", "matrix_file = None\n", "\n", "for file in files:\n", " file_path = os.path.join(in_cohort_dir, file)\n", " # Look for files that might contain SOFT or matrix data with various possible extensions\n", " if 'soft' in file.lower() or 'family' in file.lower() or file.endswith('.soft.gz'):\n", " soft_file = file_path\n", " if 'matrix' in file.lower() or file.endswith('.txt.gz') or file.endswith('.tsv.gz'):\n", " matrix_file = file_path\n", "\n", "if not soft_file:\n", " print(\"Warning: Could not find a SOFT file. Using the first .gz file as fallback.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if gz_files:\n", " soft_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "if not matrix_file:\n", " print(\"Warning: Could not find a matrix file. Using the second .gz file as fallback if available.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if len(gz_files) > 1 and soft_file != os.path.join(in_cohort_dir, gz_files[1]):\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[1])\n", " elif len(gz_files) == 1 and not soft_file:\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# 3. Read files if found\n", "if soft_file and matrix_file:\n", " # 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", " \n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " \n", " # Obtain the sample characteristics dictionary from the clinical dataframe\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " \n", " # 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", " except Exception as e:\n", " print(f\"Error processing files: {e}\")\n", " # Try swapping files if first attempt fails\n", " print(\"Trying to swap SOFT and matrix files...\")\n", " temp = soft_file\n", " soft_file = matrix_file\n", " matrix_file = temp\n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " print(\"Background Information:\")\n", " print(background_info)\n", " print(\"Sample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", " except Exception as e:\n", " print(f\"Still error after swapping: {e}\")\n", "else:\n", " print(\"Could not find necessary files for processing.\")\n" ] }, { "cell_type": "markdown", "id": "dd6474cc", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "e38618b3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:03:35.570838Z", "iopub.status.busy": "2025-03-25T06:03:35.570722Z", "iopub.status.idle": "2025-03-25T06:03:35.794529Z", "shell.execute_reply": "2025-03-25T06:03:35.794020Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data preview:\n", "{'GSM4030662': [1.0, 56.0], 'GSM4030663': [1.0, 58.0], 'GSM4030664': [1.0, 43.0], 'GSM4030665': [1.0, 61.0], 'GSM4030666': [1.0, 75.0], 'GSM4030667': [1.0, 60.0], 'GSM4030668': [1.0, 49.0], 'GSM4030669': [1.0, 56.0], 'GSM4030670': [1.0, 75.0], 'GSM4030671': [1.0, 64.0], 'GSM4030672': [1.0, 58.0], 'GSM4030673': [1.0, 64.0], 'GSM4030674': [1.0, 58.0], 'GSM4030675': [1.0, 50.0], 'GSM4030676': [1.0, 45.0], 'GSM4030677': [1.0, 57.0], 'GSM4030678': [1.0, 59.0], 'GSM4030679': [1.0, 60.0], 'GSM4030680': [1.0, 68.0], 'GSM4030681': [1.0, 66.0], 'GSM4030682': [1.0, 52.0], 'GSM4030683': [1.0, 60.0], 'GSM4030684': [1.0, 49.0], 'GSM4030685': [1.0, 53.0], 'GSM4030686': [1.0, 79.0], 'GSM4030687': [1.0, 45.0], 'GSM4030688': [1.0, 51.0], 'GSM4030689': [1.0, 66.0], 'GSM4030690': [1.0, 58.0], 'GSM4030691': [1.0, 51.0], 'GSM4030692': [1.0, 63.0], 'GSM4030693': [1.0, 60.0], 'GSM4030694': [1.0, 56.0], 'GSM4030695': [1.0, 55.0], 'GSM4030696': [1.0, 45.0], 'GSM4030697': [1.0, 65.0], 'GSM4030698': [1.0, 62.0], 'GSM4030699': [1.0, 60.0], 'GSM4030700': [1.0, 79.0], 'GSM4030701': [1.0, 57.0], 'GSM4030702': [1.0, 51.0], 'GSM4030703': [1.0, 61.0], 'GSM4030704': [1.0, 61.0], 'GSM4030705': [1.0, 66.0], 'GSM4030706': [1.0, 61.0], 'GSM4030707': [1.0, 59.0], 'GSM4030708': [1.0, 75.0], 'GSM4030709': [1.0, 58.0], 'GSM4030710': [1.0, 51.0], 'GSM4030711': [1.0, 41.0], 'GSM4030712': [1.0, 50.0], 'GSM4030713': [1.0, 53.0], 'GSM4030714': [1.0, 44.0], 'GSM4030715': [1.0, 72.0], 'GSM4030716': [1.0, 52.0], 'GSM4030717': [1.0, 59.0], 'GSM4030718': [1.0, 68.0], 'GSM4030719': [1.0, 69.0], 'GSM4030720': [1.0, 50.0], 'GSM4030721': [1.0, 69.0], 'GSM4030722': [1.0, 48.0], 'GSM4030723': [1.0, 72.0], 'GSM4030724': [1.0, 48.0], 'GSM4030725': [1.0, 62.0], 'GSM4030726': [1.0, 58.0], 'GSM4030727': [1.0, 73.0], 'GSM4030728': [1.0, 60.0], 'GSM4030729': [1.0, 66.0], 'GSM4030730': [1.0, 74.0], 'GSM4030731': [1.0, 59.0], 'GSM4030732': [1.0, 70.0], 'GSM4030733': [1.0, 64.0], 'GSM4030734': [1.0, 63.0], 'GSM4030735': [1.0, 37.0], 'GSM4030736': [1.0, 56.0], 'GSM4030737': [1.0, 60.0], 'GSM4030738': [1.0, 63.0], 'GSM4030739': [1.0, 70.0], 'GSM4030740': [1.0, 55.0], 'GSM4030741': [1.0, 60.0], 'GSM4030742': [1.0, 33.0], 'GSM4030743': [1.0, 67.0], 'GSM4030744': [1.0, 59.0], 'GSM4030745': [1.0, 45.0], 'GSM4030746': [1.0, 63.0], 'GSM4030747': [1.0, 71.0], 'GSM4030748': [1.0, 66.0], 'GSM4030749': [1.0, 73.0], 'GSM4030750': [1.0, 65.0], 'GSM4030751': [1.0, 46.0], 'GSM4030752': [1.0, 71.0], 'GSM4030753': [1.0, 79.0], 'GSM4030754': [1.0, 62.0], 'GSM4030755': [1.0, 74.0], 'GSM4030756': [1.0, 62.0], 'GSM4030757': [1.0, 74.0], 'GSM4030758': [1.0, 56.0], 'GSM4030759': [1.0, 58.0], 'GSM4030760': [1.0, 72.0], 'GSM4030761': [1.0, 70.0], 'GSM4030762': [1.0, 52.0], 'GSM4030763': [1.0, 54.0], 'GSM4030764': [1.0, 52.0], 'GSM4030765': [1.0, 63.0], 'GSM4030766': [1.0, 71.0], 'GSM4030767': [1.0, 64.0], 'GSM4030768': [1.0, 64.0], 'GSM4030769': [1.0, 65.0], 'GSM4030770': [1.0, 42.0], 'GSM4030771': [1.0, 49.0], 'GSM4030772': [1.0, 61.0], 'GSM4030773': [1.0, 57.0], 'GSM4030774': [1.0, 46.0], 'GSM4030775': [1.0, 62.0], 'GSM4030776': [1.0, 48.0], 'GSM4030777': [1.0, 61.0], 'GSM4030778': [1.0, 53.0], 'GSM4030779': [1.0, 64.0], 'GSM4030780': [1.0, 68.0], 'GSM4030781': [1.0, 44.0], 'GSM4030782': [1.0, 56.0], 'GSM4030783': [1.0, 54.0], 'GSM4030784': [1.0, 75.0], 'GSM4030785': [1.0, 54.0], 'GSM4030786': [1.0, 63.0], 'GSM4030787': [1.0, 56.0], 'GSM4030788': [1.0, 51.0], 'GSM4030789': [1.0, 68.0], 'GSM4030790': [1.0, 58.0], 'GSM4030791': [1.0, 60.0], 'GSM4030792': [1.0, 61.0], 'GSM4030793': [1.0, 64.0], 'GSM4030794': [1.0, 57.0], 'GSM4030795': [1.0, 57.0], 'GSM4030796': [1.0, 67.0], 'GSM4030797': [1.0, 52.0], 'GSM4030798': [1.0, 48.0], 'GSM4030799': [1.0, 60.0], 'GSM4030800': [1.0, 66.0], 'GSM4030801': [1.0, 73.0], 'GSM4030802': [1.0, 68.0], 'GSM4030803': [1.0, 55.0], 'GSM4030804': [1.0, 76.0], 'GSM4030805': [1.0, 58.0], 'GSM4030806': [1.0, 68.0], 'GSM4030807': [1.0, 66.0], 'GSM4030808': [1.0, 57.0], 'GSM4030809': [1.0, 46.0], 'GSM4030810': [1.0, 76.0], 'GSM4030811': [1.0, 63.0], 'GSM4030812': [1.0, 78.0], 'GSM4030813': [1.0, 50.0], 'GSM4030814': [1.0, 51.0], 'GSM4030815': [1.0, 51.0], 'GSM4030816': [1.0, 45.0], 'GSM4030817': [1.0, 75.0], 'GSM4030818': [1.0, 68.0], 'GSM4030819': [1.0, 51.0], 'GSM4030820': [1.0, 70.0], 'GSM4030821': [1.0, 66.0], 'GSM4030822': [1.0, 66.0], 'GSM4030823': [1.0, 73.0], 'GSM4030824': [1.0, 55.0], 'GSM4030825': [1.0, 52.0], 'GSM4030826': [1.0, 37.0], 'GSM4030827': [1.0, 76.0], 'GSM4030828': [1.0, 64.0], 'GSM4030829': [1.0, 60.0], 'GSM4030830': [1.0, 73.0], 'GSM4030831': [1.0, 68.0], 'GSM4030832': [1.0, 45.0], 'GSM4030833': [1.0, 67.0], 'GSM4030834': [1.0, 64.0], 'GSM4030835': [1.0, 53.0], 'GSM4030836': [1.0, 68.0], 'GSM4030837': [1.0, 68.0], 'GSM4030838': [1.0, 74.0], 'GSM4030839': [1.0, 61.0], 'GSM4030840': [1.0, 54.0], 'GSM4030841': [1.0, 54.0], 'GSM4030842': [1.0, 57.0], 'GSM4030843': [1.0, 64.0], 'GSM4030844': [1.0, 52.0], 'GSM4030845': [1.0, 62.0], 'GSM4030846': [1.0, 52.0], 'GSM4030847': [1.0, 44.0], 'GSM4030848': [1.0, 78.0], 'GSM4030849': [1.0, 45.0], 'GSM4030850': [1.0, 73.0], 'GSM4030851': [1.0, 52.0], 'GSM4030852': [1.0, 59.0], 'GSM4030853': [1.0, 54.0], 'GSM4030854': [1.0, 53.0], 'GSM4030855': [1.0, 74.0], 'GSM4030856': [1.0, 57.0], 'GSM4030857': [1.0, 65.0], 'GSM4030858': [1.0, 66.0], 'GSM4030859': [1.0, 60.0], 'GSM4030860': [1.0, 60.0], 'GSM4030861': [1.0, 78.0]}\n" ] } ], "source": [ "# Part 1: Check if gene expression data is available\n", "# This is a high-grade serous ovarian cancer study with gene expression data\n", "is_gene_available = True\n", "\n", "# Part 2: Identify available clinical features and create conversion functions\n", "\n", "# 2.1 Trait Availability\n", "# Looking at the sample characteristics dictionary, key 0 contains diagnosis information\n", "trait_row = 0\n", "\n", "# Age Availability - Key 3 contains age information\n", "age_row = 3\n", "\n", "# Gender Availability - No gender information available in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value: str) -> int:\n", " \"\"\"\n", " Convert trait value to binary format.\n", " HGSOC (High Grade Serous Ovarian Cancer) = 1\n", " non-HGSOC = 0\n", " \"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if it exists\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'HGSOC' in value and 'non-HGSOC' not in value:\n", " return 1\n", " elif 'non-HGSOC' in value:\n", " return 0\n", " return None\n", "\n", "def convert_age(value: str) -> float:\n", " \"\"\"\n", " Convert age value to continuous format.\n", " \"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if it exists\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value: str) -> int:\n", " \"\"\"\n", " Placeholder function since gender data is not available.\n", " \"\"\"\n", " return None\n", "\n", "# Part 3: Save Metadata (Initial Filtering)\n", "# Determine trait availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and save cohort info\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", "# Part 4: Clinical Feature Extraction (if trait_row is not None)\n", "if trait_row is not None:\n", " # Extract clinical features using the geo_select_clinical_features function\n", " clinical_selected = 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 clinical dataframe\n", " preview = preview_df(clinical_selected)\n", " print(\"Clinical data preview:\")\n", " print(preview)\n", " \n", " # Save the clinical data to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_selected.to_csv(out_clinical_data_file, index=False)\n" ] }, { "cell_type": "markdown", "id": "101d1968", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "4163f09b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:03:35.795934Z", "iopub.status.busy": "2025-03-25T06:03:35.795823Z", "iopub.status.idle": "2025-03-25T06:03:36.334760Z", "shell.execute_reply": "2025-03-25T06:03:36.334243Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\n", "No subseries references found in the first 1000 lines of the SOFT file.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene data extraction result:\n", "Number of rows: 513\n", "First 20 gene/probe identifiers:\n", "Index(['AJ294735.1:15', 'ENST00000390559.1:246', 'NM_000038.3:6850',\n", " 'NM_000051.3:1561', 'NM_000055.2:1445', 'NM_000059.3:115',\n", " 'NM_000075.2:1055', 'NM_000077.4:673', 'NM_000089.3:2635',\n", " 'NM_000090.3:180', 'NM_000093.3:6345', 'NM_000125.2:1595',\n", " 'NM_000138.3:6420', 'NM_000149.3:340', 'NM_000166.5:165',\n", " 'NM_000181.3:1899', 'NM_000194.1:240', 'NM_000222.1:5',\n", " 'NM_000245.2:405', 'NM_000248.2:624'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. First get the path to the soft and matrix files\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Looking more carefully at the background information\n", "# This is a SuperSeries which doesn't contain direct gene expression data\n", "# Need to investigate the soft file to find the subseries\n", "print(\"This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\")\n", "\n", "# Open the SOFT file to try to identify subseries\n", "with gzip.open(soft_file, 'rt') as f:\n", " subseries_lines = []\n", " for i, line in enumerate(f):\n", " if 'Series_relation' in line and 'SuperSeries of' in line:\n", " subseries_lines.append(line.strip())\n", " if i > 1000: # Limit search to first 1000 lines\n", " break\n", "\n", "# Display the subseries found\n", "if subseries_lines:\n", " print(\"Found potential subseries references:\")\n", " for line in subseries_lines:\n", " print(line)\n", "else:\n", " print(\"No subseries references found in the first 1000 lines of the SOFT file.\")\n", "\n", "# Despite trying to extract gene data, we expect it might fail because this is a SuperSeries\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(\"\\nGene data extraction result:\")\n", " print(\"Number of rows:\", len(gene_data))\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", " print(\"This confirms the dataset is a SuperSeries without direct gene expression data.\")\n" ] }, { "cell_type": "markdown", "id": "5e411945", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "44475192", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:03:36.336141Z", "iopub.status.busy": "2025-03-25T06:03:36.336023Z", "iopub.status.idle": "2025-03-25T06:03:36.338181Z", "shell.execute_reply": "2025-03-25T06:03:36.337804Z" } }, "outputs": [], "source": [ "# These identifiers appear to be RefSeq transcript IDs with position information\n", "# Format is typically: NM_XXXXXX.X:YYYY where XXXXXX is the accession number,\n", "# X is the version, and YYYY is likely a position within the transcript.\n", "# These are not standard human gene symbols and would need to be mapped to gene symbols.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "05d376c0", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "cebe2666", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:03:36.339501Z", "iopub.status.busy": "2025-03-25T06:03:36.339397Z", "iopub.status.idle": "2025-03-25T06:03:39.050428Z", "shell.execute_reply": "2025-03-25T06:03:39.049795Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['NM_001086.2:90', 'NM_005502.3:4936', 'NM_000927.3:3910', 'NM_000392.3:3150', 'NM_001144070.1:460'], 'ORF': ['AADAC', 'ABCA1', 'ABCB1', 'ABCC2', 'ABCC3'], 'GB_ACC': ['NM_001086.2', 'NM_005502.3', 'NM_000927.3', 'NM_000392.3', 'NM_001144070.1'], 'Target.Region': ['91-190', '4937-5036', '3911-4010', '3151-3250', '461-560'], 'SEQUENCE': ['ATGGGAAGAAAATCGCTGTACCTTCTGATTGTGGGGATCCTCATAGCATATTATATTTATACGCCTCTCCCAGATAACGTTGAGGAGCCATGGAGAATGA', 'GACGTATGTGCAGATCATAGCCAAAAGCTTAAAGAACAAGATCTGGGTGAATGAGTTTAGGTATGGCGGCTTTTCCCTGGGTGTCAGTAATACTCAAGCA', 'TATAGCACTAAAGTAGGAGACAAAGGAACTCAGCTCTCTGGTGGCCAGAAACAACGCATTGCCATAGCTCGTGCCCTTGTTAGACAGCCTCATATTTTGC', 'CAGTGACTCTAAAATCTTCAATAGCACCGACTATCCAGCATCTCAGAGGGACATGAGAGTTGGAGTCTACGGAGCTCTGGGATTAGCCCAAGGTATATTT', 'GCTGCAGGGCGTACAGTCTTCGGGGGTCCTCATTATCTTCTGGTTCCTGTGTGTGGTCTGCGCCATCGTCCCATTCCGCTCCAAGATCCTTTTAGCCAAG'], 'Customer.Identifier': ['AADAC', 'ABCA1', 'ABCB1', 'ABCC2', 'ABCC3'], 'SPOT_ID': [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": "2f5d188a", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "53cc0065", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:03:39.052239Z", "iopub.status.busy": "2025-03-25T06:03:39.052113Z", "iopub.status.idle": "2025-03-25T06:03:45.260093Z", "shell.execute_reply": "2025-03-25T06:03:45.259445Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation columns: ['ID', 'ORF', 'GB_ACC', 'Target.Region', 'SEQUENCE', 'Customer.Identifier', 'SPOT_ID']\n", "Using 'ID' for probe IDs and 'ORF' for gene symbols\n", "Gene mapping dataframe shape: (2096091, 2)\n", "Sample of gene mapping data:\n", " ID Gene\n", "0 NM_001086.2:90 AADAC\n", "1 NM_005502.3:4936 ABCA1\n", "2 NM_000927.3:3910 ABCB1\n", "3 NM_000392.3:3150 ABCC2\n", "4 NM_001144070.1:460 ABCC3\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data after mapping:\n", "Number of genes: 509\n", "Number of samples: 4077\n", "First few genes:\n", "Index(['AADAC', 'ABCA1', 'ABCB1', 'ABCC2', 'ABCC3', 'ABCC4', 'ABCC5', 'ABCE1',\n", " 'ADAM12', 'ADAMDEC1'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Ovarian_Cancer/gene_data/GSE135820.csv\n" ] } ], "source": [ "# Examine the gene annotation dataframe to identify the appropriate columns for mapping\n", "print(\"Gene annotation columns:\", gene_annotation.columns.tolist())\n", "\n", "# From the preview, we can see that:\n", "# - 'ID' column in gene_annotation contains identifiers similar to those in gene expression data\n", "# - 'ORF' column appears to contain gene symbols\n", "\n", "# 1. Decide which columns to use for mapping\n", "probe_id_column = 'ID' # Column with probe/transcript IDs matching gene expression data\n", "gene_symbol_column = 'ORF' # Column with gene symbols\n", "\n", "print(f\"Using '{probe_id_column}' for probe IDs and '{gene_symbol_column}' for gene symbols\")\n", "\n", "# 2. Get gene mapping dataframe\n", "mapping_df = get_gene_mapping(gene_annotation, probe_id_column, gene_symbol_column)\n", "print(\"Gene mapping dataframe shape:\", mapping_df.shape)\n", "print(\"Sample of gene mapping data:\")\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(\"\\nGene expression data after mapping:\")\n", "print(\"Number of genes:\", len(gene_data))\n", "print(\"Number of samples:\", len(gene_data.columns))\n", "print(\"First few genes:\")\n", "print(gene_data.index[:10])\n", "\n", "# Save the 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": "2c11e1b8", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "1d06c1e4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:03:45.261917Z", "iopub.status.busy": "2025-03-25T06:03:45.261796Z", "iopub.status.idle": "2025-03-25T06:03:47.066413Z", "shell.execute_reply": "2025-03-25T06:03:47.065888Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalizing gene symbols using NCBI synonym information...\n", "Number of genes before normalization: 509\n", "Number of genes after normalization: 509\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Ovarian_Cancer/gene_data/GSE135820.csv\n", "Sample IDs from gene data: 4077 samples\n", "Clinical data shape: (1, 4077)\n", "Clinical data saved to ../../output/preprocess/Ovarian_Cancer/clinical_data/GSE135820.csv\n", "Shape of linked data: (4077, 510)\n", "Handling missing values...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Shape of linked data after handling missing values: (4077, 510)\n", "Checking for bias in features...\n", "Quartiles for 'Ovarian_Cancer':\n", " 25%: 1.0\n", " 50% (Median): 1.0\n", " 75%: 1.0\n", "Min: 1\n", "Max: 1\n", "The distribution of the feature 'Ovarian_Cancer' in this dataset is severely biased.\n", "\n", "Dataset validation failed due to trait bias. Final linked data not saved.\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/media/techt/DATA/GenoAgent/tools/preprocess.py:455: FutureWarning: Downcasting object dtype arrays on .fillna, .ffill, .bfill is deprecated and will change in a future version. Call result.infer_objects(copy=False) instead. To opt-in to the future behavior, set `pd.set_option('future.no_silent_downcasting', True)`\n", " df[gene_cols] = df[gene_cols].fillna(df[gene_cols].mean())\n" ] } ], "source": [ "# 1. Normalize gene symbols using the NCBI Gene database synonym information\n", "print(\"Normalizing gene symbols using NCBI synonym information...\")\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Number of genes before normalization: {len(gene_data)}\")\n", "print(f\"Number of genes after normalization: {len(normalized_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 expression data saved to {out_gene_data_file}\")\n", "\n", "# 2. Since we determined in step 2 that there's no usable trait variation \n", "# (all samples are cancer cases with no controls), we'll create a clinical dataframe\n", "# but note this limitation\n", "\n", "# Create a clinical dataframe with the trait (Ovarian_Cancer)\n", "sample_ids = normalized_gene_data.columns.tolist()\n", "print(f\"Sample IDs from gene data: {len(sample_ids)} samples\")\n", "\n", "# Create clinical dataframe, but note that all samples have the same trait value\n", "clinical_df = pd.DataFrame(index=[trait], columns=sample_ids)\n", "clinical_df.loc[trait] = 1 # All samples are ovarian cancer tumors\n", "\n", "print(f\"Clinical data shape: {clinical_df.shape}\")\n", "\n", "# Save the clinical data\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "clinical_df.to_csv(out_clinical_data_file)\n", "print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "\n", "# 3. Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_df, normalized_gene_data)\n", "print(f\"Shape of linked data: {linked_data.shape}\")\n", "\n", "# 4. Handle missing values in the linked data\n", "print(\"Handling missing values...\")\n", "linked_data_cleaned = handle_missing_values(linked_data, trait)\n", "print(f\"Shape of linked data after handling missing values: {linked_data_cleaned.shape}\")\n", "\n", "# 5. Check if the trait and demographic features are biased\n", "print(\"Checking for bias in features...\")\n", "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data_cleaned, trait)\n", "\n", "# 6. Validate the dataset and save cohort information\n", "note = \"Dataset contains expression data for ovarian cancer tumors. All samples are tumor samples with no controls, so trait bias is expected and the dataset is not suitable for case-control analysis.\"\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=note\n", ")\n", "\n", "# 7. Save the linked data if it's usable (though we expect it won't be due to trait bias)\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Saved processed linked data to {out_data_file}\")\n", "else:\n", " print(\"Dataset validation failed due to trait bias. Final 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 }