{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "47ec711b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:42:33.493188Z", "iopub.status.busy": "2025-03-25T08:42:33.492934Z", "iopub.status.idle": "2025-03-25T08:42:33.659193Z", "shell.execute_reply": "2025-03-25T08:42:33.658855Z" } }, "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 = \"Endometrioid_Cancer\"\n", "cohort = \"GSE68600\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Endometrioid_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Endometrioid_Cancer/GSE68600\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Endometrioid_Cancer/GSE68600.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Endometrioid_Cancer/gene_data/GSE68600.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Endometrioid_Cancer/clinical_data/GSE68600.csv\"\n", "json_path = \"../../output/preprocess/Endometrioid_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "62f04b32", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "54549953", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:42:33.660498Z", "iopub.status.busy": "2025-03-25T08:42:33.660365Z", "iopub.status.idle": "2025-03-25T08:42:33.695291Z", "shell.execute_reply": "2025-03-25T08:42:33.695013Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"caArray_cho-00156: Gene Expression in Ovarian Cancer Reflects Both Morphology and Biological Behavior\"\n", "!Series_summary\t\"Biologically and clinically meaningful tumor classification schemes have long been sought. Some malignant epithelial neoplasms, such as those in the thyroid and endometrium, exhibit more than one pattern of differentiation, each associated with distinctive clinical features and treatments. In other tissues, all carcinomas, regardless of morphological type, are treated as though they represent a single disease. To better understand the biological and clinical features seen in the four major histological types of ovarian carcinoma (OvCa), we analyzed gene expression in 113 ovarian epithelial tumors using oligonucleotide microarrays. Global views of the variation in gene expression were obtained using PCA. These analyses show that mucinous and clear cell OvCas can be readily distinguished from serous OvCas based on their gene expression profiles, regardless of tumor stage and grade. In contrast, endometrioid adenocarcinomas show significant overlap with other histological types. Although high-stage/grade tumors are generally separable from low-stage/grade tumors, clear cell OvCa has a molecular signature that distinguishes it from other poor-prognosis OvCas. Indeed, 73 genes, expressed 2- to 29-fold higher in clear cell OvCas compared with each of the other OvCa types, were identified. Collectively, the data indicate that gene expression patterns in ovarian adenocarcinomas reflect both morphological features and biological behavior. Moreover, these studies provide a foundation for the development of new type-specific diagnostic strategies and treatments for ovarian cancer.\"\n", "!Series_overall_design\t\"cho-00156\"\n", "!Series_overall_design\t\"Assay Type: Gene Expression\"\n", "!Series_overall_design\t\"Provider: Affymetrix\"\n", "!Series_overall_design\t\"Array Designs: Hu6800\"\n", "!Series_overall_design\t\"Organism: Homo sapiens (ncbitax)\"\n", "!Series_overall_design\t\"Material Types: synthetic_RNA, organism_part, whole_organism, total_RNA\"\n", "!Series_overall_design\t\"Disease States: Ovary cancer\"\n", "Sample Characteristics Dictionary:\n", "{0: ['Sex: F'], 1: ['disease state: Ovary cancer'], 2: ['disease location: Ovary'], 3: ['organism part: Ovary'], 4: ['histology: clear cell', 'histology: endometrioid', 'histology: endometrioid/serous', 'histology: mucinous', 'histology: serous', 'histology: clear cell/serous', 'histology: serous/mucinous', 'histology: serous/endometrioid', 'histology: serous/clear cell'], 5: ['disease stage: 1', 'disease stage: 4', 'disease stage: 2', 'disease stage: U', 'disease stage: 3'], 6: ['tumor grading: 3', 'tumor grading: 2', 'tumor grading: 1']}\n" ] } ], "source": [ "from tools.preprocess import *\n", "# 1. Identify the paths to the SOFT file and the matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Read the matrix file to obtain background information and sample characteristics data\n", "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n", "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", "\n", "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n", "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", "\n", "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n", "print(\"Background Information:\")\n", "print(background_info)\n", "print(\"Sample Characteristics Dictionary:\")\n", "print(sample_characteristics_dict)\n" ] }, { "cell_type": "markdown", "id": "ee1bdd42", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "3c5cc5dd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:42:33.696497Z", "iopub.status.busy": "2025-03-25T08:42:33.696393Z", "iopub.status.idle": "2025-03-25T08:42:33.706729Z", "shell.execute_reply": "2025-03-25T08:42:33.706453Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of processed clinical data:\n", "{'GSM1676602': [0.0], 'GSM1676603': [0.0], 'GSM1676604': [1.0], 'GSM1676605': [1.0], 'GSM1676606': [1.0], 'GSM1676607': [1.0], 'GSM1676608': [1.0], 'GSM1676609': [1.0], 'GSM1676610': [1.0], 'GSM1676611': [1.0], 'GSM1676612': [1.0], 'GSM1676613': [1.0], 'GSM1676614': [1.0], 'GSM1676615': [0.0], 'GSM1676616': [0.0], 'GSM1676617': [0.0], 'GSM1676618': [0.0], 'GSM1676619': [0.0], 'GSM1676620': [0.0], 'GSM1676621': [0.0], 'GSM1676622': [0.0], 'GSM1676623': [0.0], 'GSM1676624': [0.0], 'GSM1676625': [0.0], 'GSM1676626': [0.0], 'GSM1676627': [0.0], 'GSM1676628': [0.0], 'GSM1676629': [0.0], 'GSM1676630': [0.0], 'GSM1676631': [0.0], 'GSM1676632': [0.0], 'GSM1676633': [0.0], 'GSM1676634': [0.0], 'GSM1676635': [0.0], 'GSM1676636': [0.0], 'GSM1676637': [0.0], 'GSM1676638': [0.0], 'GSM1676639': [0.0], 'GSM1676640': [0.0], 'GSM1676641': [0.0], 'GSM1676642': [0.0], 'GSM1676643': [0.0], 'GSM1676644': [0.0], 'GSM1676645': [0.0], 'GSM1676646': [1.0], 'GSM1676647': [1.0], 'GSM1676648': [1.0], 'GSM1676649': [1.0], 'GSM1676650': [1.0], 'GSM1676651': [1.0], 'GSM1676652': [1.0], 'GSM1676653': [1.0], 'GSM1676654': [1.0], 'GSM1676655': [1.0], 'GSM1676656': [1.0], 'GSM1676657': [1.0], 'GSM1676658': [1.0], 'GSM1676659': [1.0], 'GSM1676660': [1.0], 'GSM1676661': [1.0], 'GSM1676662': [1.0], 'GSM1676663': [1.0], 'GSM1676664': [1.0], 'GSM1676665': [1.0], 'GSM1676666': [1.0], 'GSM1676667': [1.0], 'GSM1676668': [1.0], 'GSM1676669': [0.0], 'GSM1676670': [0.0], 'GSM1676671': [0.0], 'GSM1676672': [0.0], 'GSM1676673': [0.0], 'GSM1676674': [0.0], 'GSM1676675': [0.0], 'GSM1676676': [0.0], 'GSM1676677': [0.0], 'GSM1676678': [0.0], 'GSM1676679': [0.0], 'GSM1676680': [0.0], 'GSM1676681': [0.0], 'GSM1676682': [0.0], 'GSM1676683': [0.0], 'GSM1676684': [0.0], 'GSM1676685': [0.0], 'GSM1676686': [0.0], 'GSM1676687': [0.0], 'GSM1676688': [0.0], 'GSM1676689': [0.0], 'GSM1676690': [0.0], 'GSM1676691': [0.0], 'GSM1676692': [0.0], 'GSM1676693': [0.0], 'GSM1676694': [0.0], 'GSM1676695': [0.0], 'GSM1676696': [1.0], 'GSM1676697': [0.0], 'GSM1676698': [0.0], 'GSM1676699': [0.0], 'GSM1676700': [0.0], 'GSM1676701': [0.0], 'GSM1676702': [0.0], 'GSM1676703': [0.0], 'GSM1676704': [1.0], 'GSM1676705': [1.0], 'GSM1676706': [0.0], 'GSM1676707': [0.0], 'GSM1676708': [0.0], 'GSM1676709': [1.0], 'GSM1676710': [0.0], 'GSM1676711': [0.0], 'GSM1676712': [0.0], 'GSM1676713': [0.0], 'GSM1676714': [0.0]}\n", "Clinical data saved to ../../output/preprocess/Endometrioid_Cancer/clinical_data/GSE68600.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains gene expression data from oligonucleotide microarrays\n", "# Specifically, it mentions \"Gene Expression in Ovarian Cancer\" and \"gene expression profiles\"\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "# For trait (Endometrioid Cancer), we can determine this from the histology information in row 4\n", "trait_row = 4 # corresponds to histology data\n", "\n", "# Age data is not available in the sample characteristics\n", "age_row = None\n", "\n", "# Gender data appears to be available in row 0, but it shows only \"Sex: F\" which means all samples are female\n", "# Since this is a constant feature (all samples are female), we consider it not available\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert histology value to binary indicator for Endometrioid Cancer.\"\"\"\n", " if value is None 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().lower()\n", " else:\n", " value = value.strip().lower()\n", " \n", " # Check if endometrioid is in the histology\n", " if 'endometrioid' in value:\n", " return 1\n", " else:\n", " return 0\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to numerical format.\"\"\"\n", " # Function defined but not used as age data is not available\n", " if value is None:\n", " return None\n", " \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):\n", " \"\"\"Convert gender value to binary format (0 for female, 1 for male).\"\"\"\n", " # Function defined but not used as gender data is constant (all female)\n", " if value is None:\n", " return None\n", " \n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " else:\n", " value = value.strip().lower()\n", " \n", " if value in ['f', 'female']:\n", " return 0\n", " elif value in ['m', 'male']:\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Trait data is available since trait_row is not None\n", "is_trait_available = trait_row is not None\n", "\n", "# Initial filtering based on gene and trait availability\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\n", "if trait_row is not None:\n", " # Extract clinical features\n", " 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 processed clinical data\n", " print(\"Preview of processed clinical data:\")\n", " print(preview_df(clinical_df))\n", " \n", " # Save the clinical data to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_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": "c7721062", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "4be4f55c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:42:33.708131Z", "iopub.status.busy": "2025-03-25T08:42:33.708028Z", "iopub.status.idle": "2025-03-25T08:42:33.770647Z", "shell.execute_reply": "2025-03-25T08:42:33.770332Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 71\n", "Header line: \"ID_REF\"\t\"GSM1676602\"\t\"GSM1676603\"\t\"GSM1676604\"\t\"GSM1676605\"\t\"GSM1676606\"\t\"GSM1676607\"\t\"GSM1676608\"\t\"GSM1676609\"\t\"GSM1676610\"\t\"GSM1676611\"\t\"GSM1676612\"\t\"GSM1676613\"\t\"GSM1676614\"\t\"GSM1676615\"\t\"GSM1676616\"\t\"GSM1676617\"\t\"GSM1676618\"\t\"GSM1676619\"\t\"GSM1676620\"\t\"GSM1676621\"\t\"GSM1676622\"\t\"GSM1676623\"\t\"GSM1676624\"\t\"GSM1676625\"\t\"GSM1676626\"\t\"GSM1676627\"\t\"GSM1676628\"\t\"GSM1676629\"\t\"GSM1676630\"\t\"GSM1676631\"\t\"GSM1676632\"\t\"GSM1676633\"\t\"GSM1676634\"\t\"GSM1676635\"\t\"GSM1676636\"\t\"GSM1676637\"\t\"GSM1676638\"\t\"GSM1676639\"\t\"GSM1676640\"\t\"GSM1676641\"\t\"GSM1676642\"\t\"GSM1676643\"\t\"GSM1676644\"\t\"GSM1676645\"\t\"GSM1676646\"\t\"GSM1676647\"\t\"GSM1676648\"\t\"GSM1676649\"\t\"GSM1676650\"\t\"GSM1676651\"\t\"GSM1676652\"\t\"GSM1676653\"\t\"GSM1676654\"\t\"GSM1676655\"\t\"GSM1676656\"\t\"GSM1676657\"\t\"GSM1676658\"\t\"GSM1676659\"\t\"GSM1676660\"\t\"GSM1676661\"\t\"GSM1676662\"\t\"GSM1676663\"\t\"GSM1676664\"\t\"GSM1676665\"\t\"GSM1676666\"\t\"GSM1676667\"\t\"GSM1676668\"\t\"GSM1676669\"\t\"GSM1676670\"\t\"GSM1676671\"\t\"GSM1676672\"\t\"GSM1676673\"\t\"GSM1676674\"\t\"GSM1676675\"\t\"GSM1676676\"\t\"GSM1676677\"\t\"GSM1676678\"\t\"GSM1676679\"\t\"GSM1676680\"\t\"GSM1676681\"\t\"GSM1676682\"\t\"GSM1676683\"\t\"GSM1676684\"\t\"GSM1676685\"\t\"GSM1676686\"\t\"GSM1676687\"\t\"GSM1676688\"\t\"GSM1676689\"\t\"GSM1676690\"\t\"GSM1676691\"\t\"GSM1676692\"\t\"GSM1676693\"\t\"GSM1676694\"\t\"GSM1676695\"\t\"GSM1676696\"\t\"GSM1676697\"\t\"GSM1676698\"\t\"GSM1676699\"\t\"GSM1676700\"\t\"GSM1676701\"\t\"GSM1676702\"\t\"GSM1676703\"\t\"GSM1676704\"\t\"GSM1676705\"\t\"GSM1676706\"\t\"GSM1676707\"\t\"GSM1676708\"\t\"GSM1676709\"\t\"GSM1676710\"\t\"GSM1676711\"\t\"GSM1676712\"\t\"GSM1676713\"\t\"GSM1676714\"\n", "First data line: \"A28102_at\"\t268\t149\t130\t131\t292\t414\t125\t105\t118\t175\t174\t171\t247\t468\t202\t127\t131\t210\t250\t129\t198\t157\t138\t142\t86\t224\t114\t120\t184\t184\t263\t107\t116\t304\t183\t150\t155\t200\t160\t112\t112\t92\t367\t197\t408\t136\t223\t192\t165\t253\t96\t220\t152\t114\t334\t100\t78\t101\t125\t792\t120\t223\t156\t263\t174\t157\t233\t255\t224\t115\t229\t403\t102\t258\t198\t172\t145\t111\t88\t179\t471\t166\t153\t132\t142\t169\t100\t204\t131\t221\t157\t221\t92\t139\t252\t142\t132\t183\t195\t114\t129\t247\t604\t188\t140\t125\t87\t75\t110\t283\t366\t104\t122\n", "Index(['A28102_at', 'AB000114_at', 'AB000115_at', 'AB000220_at',\n", " 'AB000381_s_at', 'AB000409_at', 'AB000410_s_at', 'AB000449_at',\n", " 'AB000450_at', 'AB000460_at', 'AB000462_at', 'AB000464_at',\n", " 'AB000466_at', 'AB000467_at', 'AB000468_at', 'AB000584_at',\n", " 'AB000816_s_at', 'AB000895_at', 'AB000896_at', 'AB000897_at'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. Get the file paths for the SOFT file and matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. First, let's examine the structure of the matrix file to understand its format\n", "import gzip\n", "\n", "# Peek at the first few lines of the file to understand its structure\n", "with gzip.open(matrix_file, 'rt') as file:\n", " # Read first 100 lines to find the header structure\n", " for i, line in enumerate(file):\n", " if '!series_matrix_table_begin' in line:\n", " print(f\"Found data marker at line {i}\")\n", " # Read the next line which should be the header\n", " header_line = next(file)\n", " print(f\"Header line: {header_line.strip()}\")\n", " # And the first data line\n", " first_data_line = next(file)\n", " print(f\"First data line: {first_data_line.strip()}\")\n", " break\n", " if i > 100: # Limit search to first 100 lines\n", " print(\"Matrix table marker not found in first 100 lines\")\n", " break\n", "\n", "# 3. Now try to get the genetic data with better error handling\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(gene_data.index[:20])\n", "except KeyError as e:\n", " print(f\"KeyError: {e}\")\n", " \n", " # Alternative approach: manually extract the data\n", " print(\"\\nTrying alternative approach to read the gene data:\")\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Find the start of the data\n", " for line in file:\n", " if '!series_matrix_table_begin' in line:\n", " break\n", " \n", " # Read the headers and data\n", " import pandas as pd\n", " df = pd.read_csv(file, sep='\\t', index_col=0)\n", " print(f\"Column names: {df.columns[:5]}\")\n", " print(f\"First 20 row IDs: {df.index[:20]}\")\n", " gene_data = df\n" ] }, { "cell_type": "markdown", "id": "66a348ee", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "4dba1f90", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:42:33.771715Z", "iopub.status.busy": "2025-03-25T08:42:33.771602Z", "iopub.status.idle": "2025-03-25T08:42:33.773495Z", "shell.execute_reply": "2025-03-25T08:42:33.773225Z" } }, "outputs": [], "source": [ "# Looking at the gene identifiers in the gene expression data, we can see identifiers like \"A28102_at\", \"AB000114_at\", etc.\n", "# These appear to be probe IDs from an Affymetrix microarray platform, not standard human gene symbols.\n", "# Affymetrix probe IDs typically need to be mapped to human gene symbols for biological interpretation.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "54be65c2", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "762526a2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:42:33.774673Z", "iopub.status.busy": "2025-03-25T08:42:33.774569Z", "iopub.status.idle": "2025-03-25T08:42:33.963891Z", "shell.execute_reply": "2025-03-25T08:42:33.963531Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining SOFT file structure:\n", "Line 0: ^DATABASE = GeoMiame\n", "Line 1: !Database_name = Gene Expression Omnibus (GEO)\n", "Line 2: !Database_institute = NCBI NLM NIH\n", "Line 3: !Database_web_link = http://www.ncbi.nlm.nih.gov/geo\n", "Line 4: !Database_email = geo@ncbi.nlm.nih.gov\n", "Line 5: ^SERIES = GSE68600\n", "Line 6: !Series_title = caArray_cho-00156: Gene Expression in Ovarian Cancer Reflects Both Morphology and Biological Behavior\n", "Line 7: !Series_geo_accession = GSE68600\n", "Line 8: !Series_status = Public on May 07 2015\n", "Line 9: !Series_submission_date = May 06 2015\n", "Line 10: !Series_last_update_date = Jul 08 2016\n", "Line 11: !Series_pubmed_id = 12183431\n", "Line 12: !Series_summary = Biologically and clinically meaningful tumor classification schemes have long been sought. Some malignant epithelial neoplasms, such as those in the thyroid and endometrium, exhibit more than one pattern of differentiation, each associated with distinctive clinical features and treatments. In other tissues, all carcinomas, regardless of morphological type, are treated as though they represent a single disease. To better understand the biological and clinical features seen in the four major histological types of ovarian carcinoma (OvCa), we analyzed gene expression in 113 ovarian epithelial tumors using oligonucleotide microarrays. Global views of the variation in gene expression were obtained using PCA. These analyses show that mucinous and clear cell OvCas can be readily distinguished from serous OvCas based on their gene expression profiles, regardless of tumor stage and grade. In contrast, endometrioid adenocarcinomas show significant overlap with other histological types. Although high-stage/grade tumors are generally separable from low-stage/grade tumors, clear cell OvCa has a molecular signature that distinguishes it from other poor-prognosis OvCas. Indeed, 73 genes, expressed 2- to 29-fold higher in clear cell OvCas compared with each of the other OvCa types, were identified. Collectively, the data indicate that gene expression patterns in ovarian adenocarcinomas reflect both morphological features and biological behavior. Moreover, these studies provide a foundation for the development of new type-specific diagnostic strategies and treatments for ovarian cancer.\n", "Line 13: !Series_overall_design = cho-00156\n", "Line 14: !Series_overall_design = Assay Type: Gene Expression\n", "Line 15: !Series_overall_design = Provider: Affymetrix\n", "Line 16: !Series_overall_design = Array Designs: Hu6800\n", "Line 17: !Series_overall_design = Organism: Homo sapiens (ncbitax)\n", "Line 18: !Series_overall_design = Material Types: synthetic_RNA, organism_part, whole_organism, total_RNA\n", "Line 19: !Series_overall_design = Disease States: Ovary cancer\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "{'ID': ['A28102_at', 'AB000114_at', 'AB000115_at', 'AB000220_at', 'AB000381_s_at'], 'GB_ACC': ['A28102', 'AB000114', 'AB000115', 'AB000220', 'AB000381'], 'SPOT_ID': [nan, nan, nan, nan, nan], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014'], 'Sequence Type': ['Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence'], 'Sequence Source': ['GenBank', 'GenBank', 'GenBank', 'GenBank', 'GenBank'], 'Target Description': ['A28102, class A, 20 probes, 16 in A28102cds 986-1442: 4 in reverseSequence, 1546-1582, Human GABAa receptor alpha-3 subunit.', 'AB000114, class A, 20 probes, 20 in AB000114 1818-2208, Human mRNA for osteomodulin, complete cds', 'AB000115, class A, 20 probes, 20 in AB000115 1469-1973, Human mRNA, complete cds', 'AB000220, class A, 20 probes, 20 in AB000220 4588-5134, Human mRNA for semaphorin E, complete cds', 'AB000381, class A, 20 probes, 19 in AB000381exon#2-4 45-395: 1 not in GB record, Human DNA for GPI-anchored molecule-like protein, complete cds'], 'Representative Public ID': ['A28102', 'AB000114', 'AB000115', 'AB000220', 'AB000381'], 'Gene Title': ['gamma-aminobutyric acid (GABA) A receptor, alpha 3', 'osteomodulin', 'interferon-induced protein 44-like', 'sema domain, immunoglobulin domain (Ig), short basic domain, secreted, (semaphorin) 3C', 'glycosylphosphatidylinositol anchored molecule like'], 'Gene Symbol': ['GABRA3', 'OMD', 'IFI44L', 'SEMA3C', 'GML'], 'ENTREZ_GENE_ID': ['2556', '4958', '10964', '10512', '2765'], 'RefSeq Transcript ID': ['NM_000808 /// XM_005274659 /// XM_006724811', 'NM_005014', 'NM_006820 /// XM_005270391 /// XM_005270392 /// XM_005270393 /// XM_006710303 /// XM_006710304', 'NM_006379 /// XM_005250113', 'NM_002066'], 'Gene Ontology Biological Process': ['0006810 // transport // traceable author statement /// 0006811 // ion transport // inferred from electronic annotation /// 0006821 // chloride transport // inferred from electronic annotation /// 0007214 // gamma-aminobutyric acid signaling pathway // inferred from electronic annotation /// 0007268 // synaptic transmission // traceable author statement /// 0034220 // ion transmembrane transport // traceable author statement /// 0055085 // transmembrane transport // traceable author statement /// 1902476 // chloride transmembrane transport // inferred from electronic annotation', '0005975 // carbohydrate metabolic process // traceable author statement /// 0007155 // cell adhesion // inferred from electronic annotation /// 0018146 // keratan sulfate biosynthetic process // traceable author statement /// 0030203 // glycosaminoglycan metabolic process // traceable author statement /// 0042339 // keratan sulfate metabolic process // traceable author statement /// 0042340 // keratan sulfate catabolic process // traceable author statement /// 0044281 // small molecule metabolic process // traceable author statement', '0006955 // immune response // inferred from electronic annotation /// 0051607 // defense response to virus // inferred from electronic annotation', '0001755 // neural crest cell migration // inferred from electronic annotation /// 0001756 // somitogenesis // inferred from electronic annotation /// 0001974 // blood vessel remodeling // inferred from electronic annotation /// 0003151 // outflow tract morphogenesis // inferred from electronic annotation /// 0003215 // cardiac right ventricle morphogenesis // inferred from electronic annotation /// 0003350 // pulmonary myocardium development // inferred from electronic annotation /// 0006955 // immune response // traceable author statement /// 0007275 // multicellular organismal development // inferred from electronic annotation /// 0007399 // nervous system development // inferred from electronic annotation /// 0007411 // axon guidance // inferred from sequence or structural similarity /// 0007507 // heart development // inferred from electronic annotation /// 0009791 // post-embryonic development // inferred from electronic annotation /// 0021915 // neural tube development // inferred from electronic annotation /// 0030154 // cell differentiation // inferred from electronic annotation /// 0042493 // response to drug // traceable author statement /// 0060174 // limb bud formation // inferred from electronic annotation /// 0060666 // dichotomous subdivision of terminal units involved in salivary gland branching // inferred from electronic annotation', '0006915 // apoptotic process // traceable author statement /// 0006977 // DNA damage response, signal transduction by p53 class mediator resulting in cell cycle arrest // traceable author statement /// 0008285 // negative regulation of cell proliferation // traceable author statement'], 'Gene Ontology Cellular Component': ['0005886 // plasma membrane // traceable author statement /// 0005887 // integral component of plasma membrane // traceable author statement /// 0016020 // membrane // inferred from electronic annotation /// 0016021 // integral component of membrane // inferred from electronic annotation /// 0030054 // cell junction // inferred from electronic annotation /// 0034707 // chloride channel complex // inferred from electronic annotation /// 0045202 // synapse // inferred from electronic annotation /// 0045211 // postsynaptic membrane // inferred from electronic annotation', '0005576 // extracellular region // traceable author statement /// 0005578 // proteinaceous extracellular matrix // inferred from electronic annotation /// 0005796 // Golgi lumen // traceable author statement /// 0043202 // lysosomal lumen // traceable author statement', '0005737 // cytoplasm // inferred from electronic annotation', '0005576 // extracellular region // inferred from electronic annotation /// 0005615 // extracellular space // inferred from electronic annotation /// 0016020 // membrane // inferred from electronic annotation', '0005886 // plasma membrane // inferred from electronic annotation /// 0016020 // membrane // inferred from electronic annotation /// 0019898 // extrinsic component of membrane // traceable author statement /// 0031225 // anchored component of membrane // inferred from electronic annotation'], 'Gene Ontology Molecular Function': ['0004890 // GABA-A receptor activity // inferred from electronic annotation /// 0005216 // ion channel activity // inferred from electronic annotation /// 0005230 // extracellular ligand-gated ion channel activity // inferred from electronic annotation /// 0005254 // chloride channel activity // inferred from electronic annotation /// 0008503 // benzodiazepine receptor activity // traceable author statement', '0005515 // protein binding // inferred from electronic annotation', nan, '0004872 // receptor activity // inferred from electronic annotation /// 0005515 // protein binding // inferred from electronic annotation /// 0030215 // semaphorin receptor binding // inferred from electronic annotation', nan]}\n" ] } ], "source": [ "# 1. Let's first examine the structure of the SOFT file before trying to parse it\n", "import gzip\n", "\n", "# Look at the first few lines of the SOFT file to understand its structure\n", "print(\"Examining SOFT file structure:\")\n", "try:\n", " with gzip.open(soft_file, 'rt') as file:\n", " # Read first 20 lines to understand the file structure\n", " for i, line in enumerate(file):\n", " if i < 20:\n", " print(f\"Line {i}: {line.strip()}\")\n", " else:\n", " break\n", "except Exception as e:\n", " print(f\"Error reading SOFT file: {e}\")\n", "\n", "# 2. Now let's try a more robust approach to extract the gene annotation\n", "# Instead of using the library function which failed, we'll implement a custom approach\n", "try:\n", " # First, look for the platform section which contains gene annotation\n", " platform_data = []\n", " with gzip.open(soft_file, 'rt') as file:\n", " in_platform_section = False\n", " for line in file:\n", " if line.startswith('^PLATFORM'):\n", " in_platform_section = True\n", " continue\n", " if in_platform_section and line.startswith('!platform_table_begin'):\n", " # Next line should be the header\n", " header = next(file).strip()\n", " platform_data.append(header)\n", " # Read until the end of the platform table\n", " for table_line in file:\n", " if table_line.startswith('!platform_table_end'):\n", " break\n", " platform_data.append(table_line.strip())\n", " break\n", " \n", " # If we found platform data, convert it to a DataFrame\n", " if platform_data:\n", " import pandas as pd\n", " import io\n", " platform_text = '\\n'.join(platform_data)\n", " gene_annotation = pd.read_csv(io.StringIO(platform_text), delimiter='\\t', \n", " low_memory=False, on_bad_lines='skip')\n", " print(\"\\nGene annotation preview:\")\n", " print(preview_df(gene_annotation))\n", " else:\n", " print(\"Could not find platform table in SOFT file\")\n", " \n", " # Try an alternative approach - extract mapping from other sections\n", " with gzip.open(soft_file, 'rt') as file:\n", " for line in file:\n", " if 'ANNOTATION information' in line or 'annotation information' in line:\n", " print(f\"Found annotation information: {line.strip()}\")\n", " if line.startswith('!Platform_title') or line.startswith('!platform_title'):\n", " print(f\"Platform title: {line.strip()}\")\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation: {e}\")\n" ] }, { "cell_type": "markdown", "id": "f813ec33", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "928a3648", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:42:33.965214Z", "iopub.status.busy": "2025-03-25T08:42:33.965104Z", "iopub.status.idle": "2025-03-25T08:42:34.403909Z", "shell.execute_reply": "2025-03-25T08:42:34.403543Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping preview (first 5 rows):\n", " ID Gene\n", "0 A28102_at GABRA3\n", "1 AB000114_at OMD\n", "2 AB000115_at IFI44L\n", "3 AB000220_at SEMA3C\n", "4 AB000381_s_at GML\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data preview (first 5 genes, 5 samples):\n", " GSM1676602 GSM1676603 GSM1676604 GSM1676605 GSM1676606\n", "Gene \n", "A2M 1811.0 3908.0 3826.0 4674.0 1638.0\n", "AADAC 34.0 81.0 225.0 16.0 155.0\n", "AAMP 2176.0 1885.0 3466.0 1332.0 2475.0\n", "AANAT 998.0 532.0 844.0 556.0 1340.0\n", "AARS 1995.0 3358.0 1931.0 2293.0 2812.0\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Endometrioid_Cancer/gene_data/GSE68600.csv\n" ] } ], "source": [ "# 1. Identify which columns in the gene annotation contain the gene identifier and gene symbol\n", "# Based on the preview, we can see:\n", "# - 'ID' column contains identifiers like 'A28102_at' which match the gene expression data\n", "# - 'Gene Symbol' column contains standard gene symbols like 'GABRA3'\n", "\n", "# 2. Extract the gene mapping dataframe from the gene annotation\n", "gene_mapping = gene_annotation[['ID', 'Gene Symbol']].rename(columns={'Gene Symbol': 'Gene'})\n", "\n", "# Show the first few mappings to verify\n", "print(\"Gene mapping preview (first 5 rows):\")\n", "print(gene_mapping.head())\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "# The apply_gene_mapping function handles the division of probe values among multiple genes\n", "# and summing up all probe values for each gene\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "# Preview the result\n", "print(\"\\nGene expression data preview (first 5 genes, 5 samples):\")\n", "print(gene_data.iloc[:5, :5])\n", "\n", "# Save the processed gene data to CSV\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": "e741c6c4", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "f28c46c2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:42:34.405722Z", "iopub.status.busy": "2025-03-25T08:42:34.405606Z", "iopub.status.idle": "2025-03-25T08:42:36.633007Z", "shell.execute_reply": "2025-03-25T08:42:36.632629Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data shape: (5921, 113)\n", "First few genes with their expression values after normalization:\n", " GSM1676602 GSM1676603 GSM1676604 GSM1676605 GSM1676606 GSM1676607 \\\n", "Gene \n", "A2M 1811.0 3908.0 3826.0 4674.0 1638.0 4061.0 \n", "AADAC 34.0 81.0 225.0 16.0 155.0 63.0 \n", "AAMP 2176.0 1885.0 3466.0 1332.0 2475.0 2772.0 \n", "AANAT 998.0 532.0 844.0 556.0 1340.0 1086.0 \n", "AARS1 1995.0 3358.0 1931.0 2293.0 2812.0 4343.0 \n", "\n", " GSM1676608 GSM1676609 GSM1676610 GSM1676611 ... GSM1676705 \\\n", "Gene ... \n", "A2M 1715.0 14602.0 1861.0 2095.0 ... 1433.0 \n", "AADAC 38.0 61.0 64.0 76.0 ... 126.0 \n", "AAMP 1978.0 1606.0 1904.0 2563.0 ... 1761.0 \n", "AANAT 765.0 672.0 670.0 912.0 ... 730.0 \n", "AARS1 2849.0 2885.0 2221.0 3434.0 ... 2506.0 \n", "\n", " GSM1676706 GSM1676707 GSM1676708 GSM1676709 GSM1676710 GSM1676711 \\\n", "Gene \n", "A2M 1116.0 1520.0 3814.0 2911.0 2055.0 2130.0 \n", "AADAC 12.0 271.0 969.0 177.0 105.0 1856.0 \n", "AAMP 1789.0 2931.0 2151.0 1986.0 2154.0 1674.0 \n", "AANAT 860.0 671.0 571.0 560.0 861.0 776.0 \n", "AARS1 2094.0 2149.0 3076.0 3083.0 1767.0 1589.0 \n", "\n", " GSM1676712 GSM1676713 GSM1676714 \n", "Gene \n", "A2M 713.0 836.0 1095.0 \n", "AADAC 463.0 -10.0 1076.0 \n", "AAMP 2396.0 2458.0 2666.0 \n", "AANAT 834.0 861.0 834.0 \n", "AARS1 3100.0 3455.0 2659.0 \n", "\n", "[5 rows x 113 columns]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Endometrioid_Cancer/gene_data/GSE68600.csv\n", "Raw clinical data shape: (7, 114)\n", "Clinical features:\n", " GSM1676602 GSM1676603 GSM1676604 GSM1676605 \\\n", "Endometrioid_Cancer 0.0 0.0 1.0 1.0 \n", "\n", " GSM1676606 GSM1676607 GSM1676608 GSM1676609 \\\n", "Endometrioid_Cancer 1.0 1.0 1.0 1.0 \n", "\n", " GSM1676610 GSM1676611 ... GSM1676705 GSM1676706 \\\n", "Endometrioid_Cancer 1.0 1.0 ... 1.0 0.0 \n", "\n", " GSM1676707 GSM1676708 GSM1676709 GSM1676710 \\\n", "Endometrioid_Cancer 0.0 0.0 1.0 0.0 \n", "\n", " GSM1676711 GSM1676712 GSM1676713 GSM1676714 \n", "Endometrioid_Cancer 0.0 0.0 0.0 0.0 \n", "\n", "[1 rows x 113 columns]\n", "Clinical features saved to ../../output/preprocess/Endometrioid_Cancer/clinical_data/GSE68600.csv\n", "Linked data shape: (113, 5922)\n", "Linked data preview (first 5 rows, first 5 columns):\n", " Endometrioid_Cancer A2M AADAC AAMP AANAT\n", "GSM1676602 0.0 1811.0 34.0 2176.0 998.0\n", "GSM1676603 0.0 3908.0 81.0 1885.0 532.0\n", "GSM1676604 1.0 3826.0 225.0 3466.0 844.0\n", "GSM1676605 1.0 4674.0 16.0 1332.0 556.0\n", "GSM1676606 1.0 1638.0 155.0 2475.0 1340.0\n", "Missing values before handling:\n", " Trait (Endometrioid_Cancer) missing: 0 out of 113\n", " Genes with >20% missing: 0\n", " Samples with >5% missing genes: 0\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (113, 5922)\n", "For the feature 'Endometrioid_Cancer', the least common label is '1.0' with 38 occurrences. This represents 33.63% of the dataset.\n", "The distribution of the feature 'Endometrioid_Cancer' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Endometrioid_Cancer/GSE68600.csv\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\"Normalized gene data shape: {normalized_gene_data.shape}\")\n", "print(\"First few genes with their expression values after normalization:\")\n", "print(normalized_gene_data.head())\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. Check if trait data is available before proceeding with clinical data extraction\n", "if trait_row is None:\n", " print(\"Trait row is None. Cannot extract trait information from clinical data.\")\n", " # Create an empty dataframe for clinical features\n", " clinical_features = pd.DataFrame()\n", " \n", " # Create an empty dataframe for linked data\n", " linked_data = pd.DataFrame()\n", " \n", " # Validate and save cohort info\n", " 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=False, # Trait data is not available\n", " is_biased=True, # Not applicable but required\n", " df=pd.DataFrame(), # Empty dataframe\n", " note=\"Dataset contains gene expression data but lacks clear trait indicators for Duchenne Muscular Dystrophy status.\"\n", " )\n", " print(\"Data was determined to be unusable due to missing trait indicators and was not saved\")\n", "else:\n", " try:\n", " # Get the file paths for the matrix file to extract clinical data\n", " _, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " \n", " # Get raw clinical data from the matrix file\n", " _, clinical_raw = get_background_and_clinical_data(matrix_file)\n", " \n", " # Verify clinical data structure\n", " print(\"Raw clinical data shape:\", clinical_raw.shape)\n", " \n", " # Extract clinical features using the defined conversion functions\n", " clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_raw,\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", " print(\"Clinical features:\")\n", " print(clinical_features)\n", " \n", " # Save clinical features to file\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_features.to_csv(out_clinical_data_file)\n", " print(f\"Clinical features saved to {out_clinical_data_file}\")\n", " \n", " # 3. Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " print(\"Linked data preview (first 5 rows, first 5 columns):\")\n", " print(linked_data.iloc[:5, :5])\n", " \n", " # 4. Handle missing values\n", " print(\"Missing values before handling:\")\n", " print(f\" Trait ({trait}) missing: {linked_data[trait].isna().sum()} out of {len(linked_data)}\")\n", " if 'Age' in linked_data.columns:\n", " print(f\" Age missing: {linked_data['Age'].isna().sum()} out of {len(linked_data)}\")\n", " if 'Gender' in linked_data.columns:\n", " print(f\" Gender missing: {linked_data['Gender'].isna().sum()} out of {len(linked_data)}\")\n", " \n", " gene_cols = [col for col in linked_data.columns if col not in [trait, 'Age', 'Gender']]\n", " print(f\" Genes with >20% missing: {sum(linked_data[gene_cols].isna().mean() > 0.2)}\")\n", " print(f\" Samples with >5% missing genes: {sum(linked_data[gene_cols].isna().mean(axis=1) > 0.05)}\")\n", " \n", " cleaned_data = handle_missing_values(linked_data, trait)\n", " print(f\"Data shape after handling missing values: {cleaned_data.shape}\")\n", " \n", " # 5. Evaluate bias in trait and demographic features\n", " is_trait_biased = False\n", " if len(cleaned_data) > 0:\n", " trait_biased, cleaned_data = judge_and_remove_biased_features(cleaned_data, trait)\n", " is_trait_biased = trait_biased\n", " else:\n", " print(\"No data remains after handling missing values.\")\n", " is_trait_biased = True\n", " \n", " # 6. Final validation and save\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=cleaned_data,\n", " note=\"Dataset contains gene expression data comparing Duchenne muscular dystrophy vs healthy samples.\"\n", " )\n", " \n", " # 7. Save if usable\n", " if is_usable and len(cleaned_data) > 0:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " cleaned_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", " else:\n", " print(\"Data was determined to be unusable or empty and was not saved\")\n", " \n", " except Exception as e:\n", " print(f\"Error processing data: {e}\")\n", " # Handle the error case by still recording cohort info\n", " 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=False, # Mark as not available due to processing issues\n", " is_biased=True, \n", " df=pd.DataFrame(), # Empty dataframe\n", " note=f\"Error processing data: {str(e)}\"\n", " )\n", " print(\"Data was determined to be unusable and was 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 }