{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "3828e303", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:12:48.574611Z", "iopub.status.busy": "2025-03-25T07:12:48.574508Z", "iopub.status.idle": "2025-03-25T07:12:48.730876Z", "shell.execute_reply": "2025-03-25T07:12:48.730565Z" } }, "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 = \"Irritable_bowel_syndrome_(IBS)\"\n", "cohort = \"GSE36701\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Irritable_bowel_syndrome_(IBS)\"\n", "in_cohort_dir = \"../../input/GEO/Irritable_bowel_syndrome_(IBS)/GSE36701\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Irritable_bowel_syndrome_(IBS)/GSE36701.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Irritable_bowel_syndrome_(IBS)/gene_data/GSE36701.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Irritable_bowel_syndrome_(IBS)/clinical_data/GSE36701.csv\"\n", "json_path = \"../../output/preprocess/Irritable_bowel_syndrome_(IBS)/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "1b922da2", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "2b7bb162", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:12:48.732174Z", "iopub.status.busy": "2025-03-25T07:12:48.732036Z", "iopub.status.idle": "2025-03-25T07:12:49.329639Z", "shell.execute_reply": "2025-03-25T07:12:49.329194Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Gene expression analysis of rectal mucosa in chronic irritable bowel syndrome (IBS) compared to healthy volunteers (HV)\"\n", "!Series_summary\t\"An investigation of gene expression changes in rectal biopsies from donors with IBS compared to controls to begin to understand this complex syndrome. To further investigate differences between IBS groups (constipation and diarrhoea predominant) (part1) and how IBS relates to bacterial infection (part2) with biopsies taken 6 months after Campylobacter jejuni infection.\"\n", "!Series_overall_design\t\"Part1: 18 Constipation predominant IBS subjects (IBS-C) and 27 diarrhoea predominant IBS subjects (IBS-D) compared to 21 healthy volunteers (HV).\"\n", "!Series_overall_design\t\"Part2: 21 Campylobacter jejuni infection (PIBD, PIBS, PINIBS) compared to 19 healthy volunteers (HV).\"\n", "!Series_overall_design\t\"PIBD = post Campylobacter infection with IBS (within 6 months)\"\n", "!Series_overall_design\t\"PIBS = post infection IBS (unknown time point and organism)\"\n", "!Series_overall_design\t\"PINIBS = post Campylobacter infection with no resulting IBS\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: Rectal Colon Biopsy'], 1: ['gender: M', 'gender: F'], 2: ['subject identifier: SD52930', 'subject identifier: SD52931', 'subject identifier: SD52932', 'subject identifier: SD52933', 'subject identifier: SD52934', 'subject identifier: SD52935', 'subject identifier: SD52936', 'subject identifier: SD52937', 'subject identifier: SD52938', 'subject identifier: SD52939', 'subject identifier: SD52940', 'subject identifier: SD52941', 'subject identifier: SD52942', 'subject identifier: SD52943', 'subject identifier: SD52944', 'subject identifier: SD52945', 'subject identifier: SD52946', 'subject identifier: SD52947', 'subject identifier: SD52948', 'subject identifier: SD52949', 'subject identifier: SD52950', 'subject identifier: SD52951', 'subject identifier: SD52952', 'subject identifier: SD52953', 'subject identifier: SD52954', 'subject identifier: SD52958', 'subject identifier: SD52959', 'subject identifier: SD52960', 'subject identifier: SD52961', 'subject identifier: SD52962'], 3: ['disease: HV', 'disease: IBS-D', 'disease: IBS-C', 'disease: PIBD', 'disease: PINIBS', 'disease: PIBS'], 4: ['batch: 1_C', 'batch: 1_E', 'batch: 1_A', 'batch: 1_B', 'batch: 1_F', 'batch: 1_D', 'batch: 2_A', 'batch: 2_B']}\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": "7e101bbf", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "42dadc1c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:12:49.331150Z", "iopub.status.busy": "2025-03-25T07:12:49.331033Z", "iopub.status.idle": "2025-03-25T07:12:49.351761Z", "shell.execute_reply": "2025-03-25T07:12:49.351442Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "GSM899034: [0.0, 1.0]\n", "GSM899035: [0.0, 1.0]\n", "GSM899036: [0.0, 1.0]\n", "GSM899037: [0.0, 1.0]\n", "GSM899038: [0.0, 0.0]\n", "GSM899039: [0.0, 0.0]\n", "GSM899040: [0.0, 0.0]\n", "GSM899041: [0.0, 1.0]\n", "GSM899042: [0.0, 1.0]\n", "GSM899043: [0.0, 1.0]\n", "GSM899044: [0.0, 1.0]\n", "GSM899045: [0.0, 0.0]\n", "GSM899046: [0.0, 0.0]\n", "GSM899047: [0.0, 0.0]\n", "GSM899048: [0.0, 0.0]\n", "GSM899049: [0.0, 1.0]\n", "GSM899050: [0.0, 1.0]\n", "GSM899051: [0.0, 0.0]\n", "GSM899052: [0.0, 0.0]\n", "GSM899053: [0.0, 0.0]\n", "GSM899054: [0.0, 0.0]\n", "GSM899055: [0.0, 0.0]\n", "GSM899056: [0.0, 0.0]\n", "GSM899057: [0.0, 1.0]\n", "GSM899058: [0.0, 1.0]\n", "GSM899059: [0.0, 1.0]\n", "GSM899060: [0.0, 1.0]\n", "GSM899061: [0.0, 0.0]\n", "GSM899062: [0.0, 0.0]\n", "GSM899063: [0.0, 0.0]\n", "GSM899064: [0.0, 0.0]\n", "GSM899065: [0.0, 0.0]\n", "GSM899066: [0.0, 0.0]\n", "GSM899067: [0.0, 0.0]\n", "GSM899068: [0.0, 1.0]\n", "GSM899069: [0.0, 1.0]\n", "GSM899070: [0.0, 0.0]\n", "GSM899071: [0.0, 0.0]\n", "GSM899072: [0.0, 0.0]\n", "GSM899073: [0.0, 0.0]\n", "GSM899074: [1.0, 0.0]\n", "GSM899075: [1.0, 0.0]\n", "GSM899076: [1.0, 1.0]\n", "GSM899077: [1.0, 1.0]\n", "GSM899078: [1.0, 0.0]\n", "GSM899079: [1.0, 0.0]\n", "GSM899080: [1.0, 0.0]\n", "GSM899081: [1.0, 0.0]\n", "GSM899082: [1.0, 0.0]\n", "GSM899083: [1.0, 0.0]\n", "GSM899084: [1.0, 0.0]\n", "GSM899085: [1.0, 0.0]\n", "GSM899086: [1.0, 1.0]\n", "GSM899087: [1.0, 1.0]\n", "GSM899088: [1.0, 0.0]\n", "GSM899089: [1.0, 0.0]\n", "GSM899090: [1.0, 1.0]\n", "GSM899091: [1.0, 1.0]\n", "GSM899092: [1.0, 0.0]\n", "GSM899093: [1.0, 0.0]\n", "GSM899094: [1.0, 1.0]\n", "GSM899095: [1.0, 1.0]\n", "GSM899096: [1.0, 1.0]\n", "GSM899097: [1.0, 1.0]\n", "GSM899098: [1.0, 0.0]\n", "GSM899099: [1.0, 1.0]\n", "GSM899100: [1.0, 1.0]\n", "GSM899101: [1.0, 1.0]\n", "GSM899102: [1.0, 1.0]\n", "GSM899103: [1.0, 0.0]\n", "GSM899104: [1.0, 0.0]\n", "GSM899105: [1.0, 0.0]\n", "GSM899106: [1.0, 0.0]\n", "GSM899107: [1.0, 0.0]\n", "GSM899108: [1.0, 0.0]\n", "GSM899109: [1.0, 0.0]\n", "GSM899110: [1.0, 0.0]\n", "GSM899111: [1.0, 0.0]\n", "GSM899112: [1.0, 0.0]\n", "GSM899113: [1.0, 1.0]\n", "GSM899114: [1.0, 1.0]\n", "GSM899115: [1.0, 0.0]\n", "GSM899116: [1.0, 0.0]\n", "GSM899117: [1.0, 0.0]\n", "GSM899118: [1.0, 0.0]\n", "GSM899119: [1.0, 1.0]\n", "GSM899120: [1.0, 1.0]\n", "GSM899121: [1.0, 0.0]\n", "GSM899122: [1.0, 0.0]\n", "GSM899123: [1.0, 0.0]\n", "GSM899124: [1.0, 0.0]\n", "GSM899125: [1.0, 0.0]\n", "GSM899126: [1.0, 1.0]\n", "GSM899127: [1.0, 0.0]\n", "GSM899128: [1.0, 0.0]\n", "GSM899129: [1.0, 0.0]\n", "GSM899130: [1.0, 0.0]\n", "GSM899131: [1.0, 0.0]\n", "GSM899132: [1.0, 0.0]\n", "GSM899133: [1.0, 0.0]\n", "GSM899134: [1.0, 0.0]\n", "GSM899135: [1.0, 0.0]\n", "GSM899136: [1.0, 0.0]\n", "GSM899137: [1.0, 0.0]\n", "GSM899138: [1.0, 0.0]\n", "GSM899139: [1.0, 0.0]\n", "GSM899140: [1.0, 0.0]\n", "GSM899141: [1.0, 1.0]\n", "GSM899142: [1.0, 1.0]\n", "GSM899143: [1.0, 0.0]\n", "GSM899144: [1.0, 0.0]\n", "GSM899145: [1.0, 0.0]\n", "GSM899146: [1.0, 0.0]\n", "GSM899147: [1.0, 0.0]\n", "GSM899148: [1.0, 0.0]\n", "GSM899149: [1.0, 0.0]\n", "GSM899150: [1.0, 0.0]\n", "GSM899151: [1.0, 0.0]\n", "GSM899152: [1.0, 0.0]\n", "GSM899153: [1.0, 0.0]\n", "GSM899154: [1.0, 0.0]\n", "GSM899155: [1.0, 0.0]\n", "GSM899156: [1.0, 0.0]\n", "GSM899157: [1.0, 0.0]\n", "GSM899158: [1.0, 0.0]\n", "GSM899159: [1.0, 0.0]\n", "GSM899160: [1.0, 0.0]\n", "GSM899161: [1.0, 1.0]\n", "GSM899162: [1.0, 1.0]\n", "GSM899163: [1.0, 1.0]\n", "GSM899164: [1.0, 1.0]\n", "GSM899165: [0.0, 0.0]\n", "GSM899166: [0.0, 0.0]\n", "GSM899167: [0.0, 1.0]\n", "GSM899168: [1.0, 0.0]\n", "GSM899169: [1.0, 0.0]\n", "GSM899170: [0.0, 1.0]\n", "GSM899171: [1.0, 1.0]\n", "GSM899172: [0.0, 1.0]\n", "GSM899173: [1.0, 1.0]\n", "GSM899174: [0.0, 1.0]\n", "GSM899175: [1.0, 0.0]\n", "GSM899176: [0.0, 0.0]\n", "GSM899177: [0.0, 0.0]\n", "GSM899178: [1.0, 1.0]\n", "GSM899179: [0.0, 1.0]\n", "GSM899180: [0.0, 1.0]\n", "GSM899181: [0.0, 1.0]\n", "GSM899182: [1.0, 0.0]\n", "GSM899183: [1.0, 0.0]\n", "GSM899184: [0.0, 1.0]\n", "GSM899185: [1.0, 1.0]\n", "GSM899186: [0.0, 1.0]\n", "GSM899187: [0.0, 0.0]\n", "GSM899188: [0.0, 0.0]\n", "GSM899189: [0.0, 0.0]\n", "GSM899190: [0.0, 0.0]\n", "GSM899191: [0.0, 1.0]\n", "GSM899192: [1.0, 0.0]\n", "GSM899193: [0.0, 1.0]\n", "GSM899194: [1.0, 1.0]\n", "GSM899195: [1.0, 0.0]\n", "GSM899196: [1.0, 0.0]\n", "GSM899197: [1.0, 0.0]\n", "GSM899198: [1.0, 0.0]\n", "GSM899199: [0.0, 1.0]\n", "GSM899200: [1.0, 1.0]\n", "GSM899201: [0.0, 0.0]\n", "GSM899202: [1.0, 0.0]\n", "GSM899203: [1.0, 0.0]\n", "GSM899204: [0.0, 0.0]\n", "GSM899205: [0.0, 0.0]\n", "GSM899206: [0.0, 0.0]\n", "GSM899207: [0.0, 0.0]\n", "GSM899208: [1.0, 1.0]\n", "GSM899209: [1.0, 1.0]\n", "GSM899210: [0.0, 1.0]\n", "GSM899211: [0.0, 1.0]\n", "GSM899212: [1.0, 0.0]\n", "GSM899213: [1.0, 1.0]\n", "GSM899214: [0.0, 0.0]\n", "GSM899215: [1.0, 1.0]\n", "GSM899216: [0.0, 0.0]\n", "GSM899217: [1.0, 0.0]\n", "GSM899218: [1.0, 1.0]\n", "GSM899219: [0.0, 1.0]\n", "GSM899220: [0.0, 0.0]\n", "GSM899221: [1.0, 0.0]\n", "GSM899222: [0.0, 0.0]\n", "GSM899223: [1.0, 0.0]\n", "GSM899224: [1.0, 0.0]\n", "GSM899225: [1.0, 0.0]\n", "GSM899226: [0.0, 1.0]\n", "GSM899227: [0.0, 1.0]\n", "GSM899228: [0.0, 0.0]\n", "GSM899229: [0.0, 0.0]\n", "GSM899230: [0.0, 1.0]\n", "GSM899231: [0.0, 1.0]\n", "GSM899232: [0.0, 1.0]\n", "GSM899233: [0.0, 0.0]\n", "Clinical data saved to ../../output/preprocess/Irritable_bowel_syndrome_(IBS)/clinical_data/GSE36701.csv\n" ] } ], "source": [ "import os\n", "import pandas as pd\n", "import numpy as np\n", "import json\n", "from typing import Dict, Any, Optional, List, Callable, Union\n", "\n", "# 1. Gene Expression Data Availability\n", "# Looking at the background info, this appears to be a gene expression study in rectal biopsies\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait, we can see disease status at index 3 in the sample characteristics\n", "trait_row = 3 # 'disease: HV', 'disease: IBS-D', 'disease: IBS-C', etc.\n", "\n", "# Age is not available in the sample characteristics\n", "age_row = None\n", "\n", "# Gender is available at index 1\n", "gender_row = 1 # 'gender: M', 'gender: F'\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value: str) -> int:\n", " \"\"\"Convert IBS disease status to binary (0 for healthy, 1 for IBS)\"\"\"\n", " if value is None or \":\" not in value:\n", " return None\n", " \n", " disease = value.split(\":\", 1)[1].strip().upper()\n", " \n", " # Healthy volunteers\n", " if disease == \"HV\":\n", " return 0\n", " # IBS cases (IBS-D, IBS-C, PIBD, PIBS)\n", " elif disease.startswith(\"IBS\") or disease == \"PIBD\" or disease == \"PIBS\":\n", " return 1\n", " # PINIBS = post infection with no IBS\n", " elif disease == \"PINIBS\":\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_gender(value: str) -> int:\n", " \"\"\"Convert gender to binary (0 for female, 1 for male)\"\"\"\n", " if value is None or \":\" not in value:\n", " return None\n", " \n", " gender = value.split(\":\", 1)[1].strip().upper()\n", " \n", " if gender == \"F\":\n", " return 0\n", " elif gender == \"M\":\n", " return 1\n", " else:\n", " return None\n", "\n", "# No convert_age function needed since age data is not available\n", "\n", "# 3. Save Metadata\n", "# Determine if trait data is available\n", "is_trait_available = trait_row is not None\n", "validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path, \n", " is_gene_available=is_gene_available, \n", " is_trait_available=is_trait_available)\n", "\n", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # Assuming clinical_data is already loaded from a previous step\n", " # If not, we need to load it from the cohort directory\n", " clinical_data_path = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n", " if os.path.exists(clinical_data_path):\n", " clinical_data = pd.read_csv(clinical_data_path)\n", " else:\n", " # Using the first available matrix file in the directory\n", " matrix_files = [f for f in os.listdir(in_cohort_dir) if f.endswith('_series_matrix.txt')]\n", " if matrix_files:\n", " matrix_path = os.path.join(in_cohort_dir, matrix_files[0])\n", " # Assuming there's a function to extract clinical data from matrix file\n", " # For now, we'll use a placeholder approach\n", " with open(matrix_path, 'r') as f:\n", " lines = f.readlines()\n", " \n", " # Find sample characteristic lines\n", " sample_chars = [line for line in lines if line.startswith('!Sample_characteristics_ch1')]\n", " \n", " # Create a simple dataframe with sample characteristics\n", " sample_ids = [line for line in lines if line.startswith('!Sample_geo_accession')]\n", " if sample_ids:\n", " sample_ids = [s.strip().split('\\t')[1].replace('\"', '') for s in sample_ids]\n", " \n", " # Transpose the data for proper format\n", " clinical_data = pd.DataFrame(index=sample_ids)\n", " \n", " for i, char in enumerate(sample_chars):\n", " char_values = char.strip().split('\\t')[1:]\n", " char_values = [c.replace('\"', '') for c in char_values]\n", " if len(char_values) == len(sample_ids):\n", " clinical_data[i] = char_values\n", " \n", " # Extract clinical features\n", " selected_clinical = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the selected clinical features\n", " preview = preview_df(selected_clinical)\n", " print(\"Preview of selected clinical features:\")\n", " for key, value in preview.items():\n", " print(f\"{key}: {value}\")\n", " \n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the clinical data\n", " selected_clinical.to_csv(out_clinical_data_file, index=True)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "a9fe7930", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "4123c189", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:12:49.352970Z", "iopub.status.busy": "2025-03-25T07:12:49.352863Z", "iopub.status.idle": "2025-03-25T07:12:50.421382Z", "shell.execute_reply": "2025-03-25T07:12:50.421013Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 72\n", "Header line: \"ID_REF\"\t\"GSM899034\"\t\"GSM899035\"\t\"GSM899036\"\t\"GSM899037\"\t\"GSM899038\"\t\"GSM899039\"\t\"GSM899040\"\t\"GSM899041\"\t\"GSM899042\"\t\"GSM899043\"\t\"GSM899044\"\t\"GSM899045\"\t\"GSM899046\"\t\"GSM899047\"\t\"GSM899048\"\t\"GSM899049\"\t\"GSM899050\"\t\"GSM899051\"\t\"GSM899052\"\t\"GSM899053\"\t\"GSM899054\"\t\"GSM899055\"\t\"GSM899056\"\t\"GSM899057\"\t\"GSM899058\"\t\"GSM899059\"\t\"GSM899060\"\t\"GSM899061\"\t\"GSM899062\"\t\"GSM899063\"\t\"GSM899064\"\t\"GSM899065\"\t\"GSM899066\"\t\"GSM899067\"\t\"GSM899068\"\t\"GSM899069\"\t\"GSM899070\"\t\"GSM899071\"\t\"GSM899072\"\t\"GSM899073\"\t\"GSM899074\"\t\"GSM899075\"\t\"GSM899076\"\t\"GSM899077\"\t\"GSM899078\"\t\"GSM899079\"\t\"GSM899080\"\t\"GSM899081\"\t\"GSM899082\"\t\"GSM899083\"\t\"GSM899084\"\t\"GSM899085\"\t\"GSM899086\"\t\"GSM899087\"\t\"GSM899088\"\t\"GSM899089\"\t\"GSM899090\"\t\"GSM899091\"\t\"GSM899092\"\t\"GSM899093\"\t\"GSM899094\"\t\"GSM899095\"\t\"GSM899096\"\t\"GSM899097\"\t\"GSM899098\"\t\"GSM899099\"\t\"GSM899100\"\t\"GSM899101\"\t\"GSM899102\"\t\"GSM899103\"\t\"GSM899104\"\t\"GSM899105\"\t\"GSM899106\"\t\"GSM899107\"\t\"GSM899108\"\t\"GSM899109\"\t\"GSM899110\"\t\"GSM899111\"\t\"GSM899112\"\t\"GSM899113\"\t\"GSM899114\"\t\"GSM899115\"\t\"GSM899116\"\t\"GSM899117\"\t\"GSM899118\"\t\"GSM899119\"\t\"GSM899120\"\t\"GSM899121\"\t\"GSM899122\"\t\"GSM899123\"\t\"GSM899124\"\t\"GSM899125\"\t\"GSM899126\"\t\"GSM899127\"\t\"GSM899128\"\t\"GSM899129\"\t\"GSM899130\"\t\"GSM899131\"\t\"GSM899132\"\t\"GSM899133\"\t\"GSM899134\"\t\"GSM899135\"\t\"GSM899136\"\t\"GSM899137\"\t\"GSM899138\"\t\"GSM899139\"\t\"GSM899140\"\t\"GSM899141\"\t\"GSM899142\"\t\"GSM899143\"\t\"GSM899144\"\t\"GSM899145\"\t\"GSM899146\"\t\"GSM899147\"\t\"GSM899148\"\t\"GSM899149\"\t\"GSM899150\"\t\"GSM899151\"\t\"GSM899152\"\t\"GSM899153\"\t\"GSM899154\"\t\"GSM899155\"\t\"GSM899156\"\t\"GSM899157\"\t\"GSM899158\"\t\"GSM899159\"\t\"GSM899160\"\t\"GSM899161\"\t\"GSM899162\"\t\"GSM899163\"\t\"GSM899164\"\t\"GSM899165\"\t\"GSM899166\"\t\"GSM899167\"\t\"GSM899168\"\t\"GSM899169\"\t\"GSM899170\"\t\"GSM899171\"\t\"GSM899172\"\t\"GSM899173\"\t\"GSM899174\"\t\"GSM899175\"\t\"GSM899176\"\t\"GSM899177\"\t\"GSM899178\"\t\"GSM899179\"\t\"GSM899180\"\t\"GSM899181\"\t\"GSM899182\"\t\"GSM899183\"\t\"GSM899184\"\t\"GSM899185\"\t\"GSM899186\"\t\"GSM899187\"\t\"GSM899188\"\t\"GSM899189\"\t\"GSM899190\"\t\"GSM899191\"\t\"GSM899192\"\t\"GSM899193\"\t\"GSM899194\"\t\"GSM899195\"\t\"GSM899196\"\t\"GSM899197\"\t\"GSM899198\"\t\"GSM899199\"\t\"GSM899200\"\t\"GSM899201\"\t\"GSM899202\"\t\"GSM899203\"\t\"GSM899204\"\t\"GSM899205\"\t\"GSM899206\"\t\"GSM899207\"\t\"GSM899208\"\t\"GSM899209\"\t\"GSM899210\"\t\"GSM899211\"\t\"GSM899212\"\t\"GSM899213\"\t\"GSM899214\"\t\"GSM899215\"\t\"GSM899216\"\t\"GSM899217\"\t\"GSM899218\"\t\"GSM899219\"\t\"GSM899220\"\t\"GSM899221\"\t\"GSM899222\"\t\"GSM899223\"\t\"GSM899224\"\t\"GSM899225\"\t\"GSM899226\"\t\"GSM899227\"\t\"GSM899228\"\t\"GSM899229\"\t\"GSM899230\"\t\"GSM899231\"\t\"GSM899232\"\t\"GSM899233\"\t\"GSM899234\"\t\"GSM899235\"\t\"GSM899236\"\t\"GSM899237\"\t\"GSM899238\"\t\"GSM899239\"\t\"GSM899240\"\t\"GSM899241\"\t\"GSM899242\"\t\"GSM899243\"\t\"GSM899244\"\t\"GSM899245\"\t\"GSM899246\"\t\"GSM899247\"\t\"GSM899248\"\t\"GSM899249\"\t\"GSM899250\"\t\"GSM899251\"\t\"GSM899252\"\t\"GSM899253\"\t\"GSM899254\"\n", "First data line: \"1007_s_at\"\t185.72598\t229.74765\t242.88435\t218.21414\t242.50253\t206.75014\t185.58952\t224.16792\t192.36656\t207.47267\t225.76723\t181.40237\t176.49051\t221.95686\t254.62015\t268.32703\t229.78616\t173.94818\t152.33916\t225.68501\t210.63287\t256.89148\t248.1562\t206.52242\t211.96779\t231.72282\t243.45383\t211.63222\t229.06021\t208.37259\t264.66058\t240.68483\t174.8918\t201.48293\t180.44887\t257.17688\t204.1358\t209.85728\t227.88644\t229.41309\t204.53709\t217.3555\t192.21962\t163.47949\t219.46638\t291.98941\t207.43112\t279.39215\t194.0504\t267.97806\t303.66391\t479.61176\t220.0407\t224.95721\t194.09662\t255.16838\t247.42099\t275.52377\t222.28633\t308.16586\t234.43587\t224.66356\t225.56795\t207.60841\t242.2921\t272.79517\t202.01349\t164.14247\t182.5464\t159.1055\t172.77225\t207.25876\t173.58626\t231.89653\t191.83318\t250.41296\t230.07974\t198.702\t161.93951\t243.94601\t211.6264\t219.85257\t245.88127\t187.34547\t208.12399\t325.26895\t285.7323\t264.21204\t263.38818\t176.49274\t159.83627\t192.96454\t234.15585\t177.95679\t186.58371\t227.87657\t223.89487\t202.98863\t248.25714\t175.42241\t189.68236\t267.59796\t316.64423\t214.32347\t200.64833\t263.81668\t246.93298\t215.14217\t216.0675\t193.65045\t282.6449\t234.21855\t203.25673\t233.83952\t261.55414\t240.57495\t189.9234\t241.13214\t278.02762\t237.22137\t156.56143\t160.55548\t242.64813\t285.44528\t285.06372\t267.54413\t266.94662\t1202.76135\t1336.30249\t1102.35596\t1207.14026\t1087.99878\t1200.53125\t1043.41394\t1258.95679\t1042.89648\t1337.43079\t1120.41382\t1261.58496\t1294.70483\t1250.5542\t1340.90747\t1440.04639\t1206.47876\t1230.15186\t1409.04956\t1423.72864\t1319.32397\t1216.56433\t1294.047\t1214.25879\t1370.20605\t1303.98303\t1102.80103\t1190.68335\t1221.86365\t1189.16357\t1180.75891\t1160.21887\t1376.52759\t1686.65063\t1532.61707\t1354.67395\t1339.16113\t1591.88757\t1400.88208\t1396.35425\t1258.21753\t1399.9873\t1128.07068\t1421.83423\t1483.70081\t1460.75745\t1407.31946\t1125.8252\t1330.3949\t1531.61841\t1436.43237\t1550.67517\t1314.73218\t1203.77026\t1359.42444\t1422.11853\t1195.00635\t1524.96362\t1282.13318\t1380.45544\t1338.80188\t1383.69324\t1396.3125\t1377.81677\t1358.76025\t1429.84875\t1449.93201\t1572.38538\t1452.1969\t1336.27795\t1496.70728\t1520.24597\t1845.96021\t1666.54077\t1339.03687\t1486.651\t1415.63293\t1342.64978\t1367.94922\t1389.11096\t1350.40051\t1439.28931\t1426.44885\t1286.59485\t1443.64771\t1349.30005\t1538.22852\t1581.9812\t1497.49963\t1370.56934\t1360.6897\t1399.82837\t1556.16846\t954.24634\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Index(['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at', '1294_at',\n", " '1316_at', '1320_at', '1405_i_at', '1431_at', '1438_at', '1487_at',\n", " '1494_f_at', '1552256_a_at', '1552257_a_at', '1552258_at', '1552261_at',\n", " '1552263_at', '1552264_a_at', '1552266_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": "3593efe4", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "6ae5dfac", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:12:50.422696Z", "iopub.status.busy": "2025-03-25T07:12:50.422578Z", "iopub.status.idle": "2025-03-25T07:12:50.424581Z", "shell.execute_reply": "2025-03-25T07:12:50.424280Z" } }, "outputs": [], "source": [ "# Looking at the gene identifiers in the expression data\n", "# The identifiers like \"1007_s_at\", \"1053_at\", \"117_at\", etc. appear to be\n", "# Affymetrix probe IDs from a microarray platform, not standard human gene symbols.\n", "# These need to be mapped to official gene symbols for meaningful analysis.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "9130961a", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "356442f5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:12:50.425688Z", "iopub.status.busy": "2025-03-25T07:12:50.425584Z", "iopub.status.idle": "2025-03-25T07:13:07.478609Z", "shell.execute_reply": "2025-03-25T07:13:07.478215Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at'], 'GB_ACC': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], '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': ['Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database'], 'Target Description': ['U48705 /FEATURE=mRNA /DEFINITION=HSU48705 Human receptor tyrosine kinase DDR gene, complete cds', 'M87338 /FEATURE= /DEFINITION=HUMA1SBU Human replication factor C, 40-kDa subunit (A1) mRNA, complete cds', \"X51757 /FEATURE=cds /DEFINITION=HSP70B Human heat-shock protein HSP70B' gene\", 'X69699 /FEATURE= /DEFINITION=HSPAX8A H.sapiens Pax8 mRNA', 'L36861 /FEATURE=expanded_cds /DEFINITION=HUMGCAPB Homo sapiens guanylate cyclase activating protein (GCAP) gene exons 1-4, complete cds'], 'Representative Public ID': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'Gene Title': ['discoidin domain receptor tyrosine kinase 1 /// microRNA 4640', 'replication factor C (activator 1) 2, 40kDa', \"heat shock 70kDa protein 6 (HSP70B')\", 'paired box 8', 'guanylate cyclase activator 1A (retina)'], 'Gene Symbol': ['DDR1 /// MIR4640', 'RFC2', 'HSPA6', 'PAX8', 'GUCA1A'], 'ENTREZ_GENE_ID': ['780 /// 100616237', '5982', '3310', '7849', '2978'], 'RefSeq Transcript ID': ['NM_001202521 /// NM_001202522 /// NM_001202523 /// NM_001954 /// NM_013993 /// NM_013994 /// NR_039783 /// XM_005249385 /// XM_005249386 /// XM_005249387 /// XM_005249389 /// XM_005272873 /// XM_005272874 /// XM_005272875 /// XM_005272877 /// XM_005275027 /// XM_005275028 /// XM_005275030 /// XM_005275031 /// XM_005275162 /// XM_005275163 /// XM_005275164 /// XM_005275166 /// XM_005275457 /// XM_005275458 /// XM_005275459 /// XM_005275461 /// XM_006715185 /// XM_006715186 /// XM_006715187 /// XM_006715188 /// XM_006715189 /// XM_006715190 /// XM_006725501 /// XM_006725502 /// XM_006725503 /// XM_006725504 /// XM_006725505 /// XM_006725506 /// XM_006725714 /// XM_006725715 /// XM_006725716 /// XM_006725717 /// XM_006725718 /// XM_006725719 /// XM_006725720 /// XM_006725721 /// XM_006725722 /// XM_006725827 /// XM_006725828 /// XM_006725829 /// XM_006725830 /// XM_006725831 /// XM_006725832 /// XM_006726017 /// XM_006726018 /// XM_006726019 /// XM_006726020 /// XM_006726021 /// XM_006726022 /// XR_427836 /// XR_430858 /// XR_430938 /// XR_430974 /// XR_431015', 'NM_001278791 /// NM_001278792 /// NM_001278793 /// NM_002914 /// NM_181471 /// XM_006716080', 'NM_002155', 'NM_003466 /// NM_013951 /// NM_013952 /// NM_013953 /// NM_013992', 'NM_000409 /// XM_006715073'], 'Gene Ontology Biological Process': ['0001558 // regulation of cell growth // inferred from electronic annotation /// 0001952 // regulation of cell-matrix adhesion // inferred from electronic annotation /// 0006468 // protein phosphorylation // inferred from electronic annotation /// 0007155 // cell adhesion // traceable author statement /// 0007169 // transmembrane receptor protein tyrosine kinase signaling pathway // inferred from electronic annotation /// 0007565 // female pregnancy // inferred from electronic annotation /// 0007566 // embryo implantation // inferred from electronic annotation /// 0007595 // lactation // inferred from electronic annotation /// 0008285 // negative regulation of cell proliferation // inferred from electronic annotation /// 0010715 // regulation of extracellular matrix disassembly // inferred from mutant phenotype /// 0014909 // smooth muscle cell migration // inferred from mutant phenotype /// 0016310 // phosphorylation // inferred from electronic annotation /// 0018108 // peptidyl-tyrosine phosphorylation // inferred from electronic annotation /// 0030198 // extracellular matrix organization // traceable author statement /// 0038063 // collagen-activated tyrosine kinase receptor signaling pathway // inferred from direct assay /// 0038063 // collagen-activated tyrosine kinase receptor signaling pathway // inferred from mutant phenotype /// 0038083 // peptidyl-tyrosine autophosphorylation // inferred from direct assay /// 0043583 // ear development // inferred from electronic annotation /// 0044319 // wound healing, spreading of cells // inferred from mutant phenotype /// 0046777 // protein autophosphorylation // inferred from direct assay /// 0060444 // branching involved in mammary gland duct morphogenesis // inferred from electronic annotation /// 0060749 // mammary gland alveolus development // inferred from electronic annotation /// 0061302 // smooth muscle cell-matrix adhesion // inferred from mutant phenotype', '0000278 // mitotic cell cycle // traceable author statement /// 0000722 // telomere maintenance via recombination // traceable author statement /// 0000723 // telomere maintenance // traceable author statement /// 0006260 // DNA replication // traceable author statement /// 0006271 // DNA strand elongation involved in DNA replication // traceable author statement /// 0006281 // DNA repair // traceable author statement /// 0006283 // transcription-coupled nucleotide-excision repair // traceable author statement /// 0006289 // nucleotide-excision repair // traceable author statement /// 0006297 // nucleotide-excision repair, DNA gap filling // traceable author statement /// 0015979 // photosynthesis // inferred from electronic annotation /// 0015995 // chlorophyll biosynthetic process // inferred from electronic annotation /// 0032201 // telomere maintenance via semi-conservative replication // traceable author statement', '0000902 // cell morphogenesis // inferred from electronic annotation /// 0006200 // ATP catabolic process // inferred from direct assay /// 0006950 // response to stress // inferred from electronic annotation /// 0006986 // response to unfolded protein // traceable author statement /// 0034605 // cellular response to heat // inferred from direct assay /// 0042026 // protein refolding // inferred from direct assay /// 0070370 // cellular heat acclimation // inferred from mutant phenotype', '0001655 // urogenital system development // inferred from sequence or structural similarity /// 0001656 // metanephros development // inferred from electronic annotation /// 0001658 // branching involved in ureteric bud morphogenesis // inferred from expression pattern /// 0001822 // kidney development // inferred from expression pattern /// 0001823 // mesonephros development // inferred from sequence or structural similarity /// 0003337 // mesenchymal to epithelial transition involved in metanephros morphogenesis // inferred from expression pattern /// 0006351 // transcription, DNA-templated // inferred from direct assay /// 0006355 // regulation of transcription, DNA-templated // inferred from electronic annotation /// 0007275 // multicellular organismal development // inferred from electronic annotation /// 0007417 // central nervous system development // inferred from expression pattern /// 0009653 // anatomical structure morphogenesis // traceable author statement /// 0030154 // cell differentiation // inferred from electronic annotation /// 0030878 // thyroid gland development // inferred from expression pattern /// 0030878 // thyroid gland development // inferred from mutant phenotype /// 0038194 // thyroid-stimulating hormone signaling pathway // traceable author statement /// 0039003 // pronephric field specification // inferred from sequence or structural similarity /// 0042472 // inner ear morphogenesis // inferred from sequence or structural similarity /// 0042981 // regulation of apoptotic process // inferred from sequence or structural similarity /// 0045893 // positive regulation of transcription, DNA-templated // inferred from direct assay /// 0045893 // positive regulation of transcription, DNA-templated // inferred from sequence or structural similarity /// 0045944 // positive regulation of transcription from RNA polymerase II promoter // inferred from direct assay /// 0048793 // pronephros development // inferred from sequence or structural similarity /// 0071371 // cellular response to gonadotropin stimulus // inferred from direct assay /// 0071599 // otic vesicle development // inferred from expression pattern /// 0072050 // S-shaped body morphogenesis // inferred from electronic annotation /// 0072073 // kidney epithelium development // inferred from electronic annotation /// 0072108 // positive regulation of mesenchymal to epithelial transition involved in metanephros morphogenesis // inferred from sequence or structural similarity /// 0072164 // mesonephric tubule development // inferred from electronic annotation /// 0072207 // metanephric epithelium development // inferred from expression pattern /// 0072221 // metanephric distal convoluted tubule development // inferred from sequence or structural similarity /// 0072278 // metanephric comma-shaped body morphogenesis // inferred from expression pattern /// 0072284 // metanephric S-shaped body morphogenesis // inferred from expression pattern /// 0072289 // metanephric nephron tubule formation // inferred from sequence or structural similarity /// 0072305 // negative regulation of mesenchymal cell apoptotic process involved in metanephric nephron morphogenesis // inferred from sequence or structural similarity /// 0072307 // regulation of metanephric nephron tubule epithelial cell differentiation // inferred from sequence or structural similarity /// 0090190 // positive regulation of branching involved in ureteric bud morphogenesis // inferred from sequence or structural similarity /// 1900212 // negative regulation of mesenchymal cell apoptotic process involved in metanephros development // inferred from sequence or structural similarity /// 1900215 // negative regulation of apoptotic process involved in metanephric collecting duct development // inferred from sequence or structural similarity /// 1900218 // negative regulation of apoptotic process involved in metanephric nephron tubule development // inferred from sequence or structural similarity /// 2000594 // positive regulation of metanephric DCT cell differentiation // inferred from sequence or structural similarity /// 2000611 // positive regulation of thyroid hormone generation // inferred from mutant phenotype /// 2000612 // regulation of thyroid-stimulating hormone secretion // inferred from mutant phenotype', '0007165 // signal transduction // non-traceable author statement /// 0007601 // visual perception // inferred from electronic annotation /// 0007602 // phototransduction // inferred from electronic annotation /// 0007603 // phototransduction, visible light // traceable author statement /// 0016056 // rhodopsin mediated signaling pathway // traceable author statement /// 0022400 // regulation of rhodopsin mediated signaling pathway // traceable author statement /// 0030828 // positive regulation of cGMP biosynthetic process // inferred from electronic annotation /// 0031282 // regulation of guanylate cyclase activity // inferred from electronic annotation /// 0031284 // positive regulation of guanylate cyclase activity // inferred from electronic annotation /// 0050896 // response to stimulus // inferred from electronic annotation'], 'Gene Ontology Cellular Component': ['0005576 // extracellular region // inferred from electronic annotation /// 0005615 // extracellular space // inferred from direct assay /// 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 /// 0043235 // receptor complex // inferred from direct assay /// 0070062 // extracellular vesicular exosome // inferred from direct assay', '0005634 // nucleus // inferred from electronic annotation /// 0005654 // nucleoplasm // traceable author statement /// 0005663 // DNA replication factor C complex // inferred from direct assay', '0005737 // cytoplasm // inferred from direct assay /// 0005814 // centriole // inferred from direct assay /// 0005829 // cytosol // inferred from direct assay /// 0008180 // COP9 signalosome // inferred from direct assay /// 0070062 // extracellular vesicular exosome // inferred from direct assay /// 0072562 // blood microparticle // inferred from direct assay', '0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // inferred from sequence or structural similarity /// 0005730 // nucleolus // inferred from direct assay', '0001750 // photoreceptor outer segment // inferred from electronic annotation /// 0001917 // photoreceptor inner segment // inferred from electronic annotation /// 0005578 // proteinaceous extracellular matrix // inferred from electronic annotation /// 0005886 // plasma membrane // inferred from direct assay /// 0016020 // membrane // inferred from electronic annotation /// 0097381 // photoreceptor disc membrane // traceable author statement'], 'Gene Ontology Molecular Function': ['0000166 // nucleotide binding // inferred from electronic annotation /// 0004672 // protein kinase activity // inferred from electronic annotation /// 0004713 // protein tyrosine kinase activity // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // traceable author statement /// 0005515 // protein binding // inferred from physical interaction /// 0005518 // collagen binding // inferred from direct assay /// 0005518 // collagen binding // inferred from mutant phenotype /// 0005524 // ATP binding // inferred from electronic annotation /// 0016301 // kinase activity // inferred from electronic annotation /// 0016740 // transferase activity // inferred from electronic annotation /// 0016772 // transferase activity, transferring phosphorus-containing groups // inferred from electronic annotation /// 0038062 // protein tyrosine kinase collagen receptor activity // inferred from direct assay /// 0046872 // metal ion binding // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0005524 // ATP binding // inferred from electronic annotation /// 0016851 // magnesium chelatase activity // inferred from electronic annotation /// 0017111 // nucleoside-triphosphatase activity // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation /// 0019899 // enzyme binding // inferred from physical interaction /// 0031072 // heat shock protein binding // inferred from physical interaction /// 0042623 // ATPase activity, coupled // inferred from direct assay /// 0051082 // unfolded protein binding // inferred from direct assay', '0000979 // RNA polymerase II core promoter sequence-specific DNA binding // inferred from direct assay /// 0003677 // DNA binding // inferred from direct assay /// 0003677 // DNA binding // inferred from mutant phenotype /// 0003700 // sequence-specific DNA binding transcription factor activity // inferred from direct assay /// 0004996 // thyroid-stimulating hormone receptor activity // traceable author statement /// 0005515 // protein binding // inferred from physical interaction /// 0044212 // transcription regulatory region DNA binding // inferred from direct assay', '0005509 // calcium ion binding // inferred from electronic annotation /// 0008048 // calcium sensitive guanylate cyclase activator activity // inferred from electronic annotation /// 0030249 // guanylate cyclase regulator activity // inferred from electronic annotation /// 0046872 // metal ion binding // inferred from electronic annotation']}\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": "5394ed1f", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "6533c184", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:13:07.479876Z", "iopub.status.busy": "2025-03-25T07:13:07.479755Z", "iopub.status.idle": "2025-03-25T07:13:10.878282Z", "shell.execute_reply": "2025-03-25T07:13:10.877895Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First 10 mapped gene symbols:\n", "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2M-AS1', 'A2ML1', 'A2MP1',\n", " 'A4GALT', 'A4GNT', 'AA06'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Irritable_bowel_syndrome_(IBS)/gene_data/GSE36701.csv\n" ] } ], "source": [ "# 1. Looking at the dataframe preview, 'ID' column contains probe IDs, and 'Gene Symbol' contains gene symbols\n", "prob_col = 'ID'\n", "gene_col = 'Gene Symbol'\n", "\n", "# 2. Get the gene mapping dataframe\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "\n", "# 3. Apply the gene mapping to convert from probe-level to gene-level expression\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Verify the type of identifiers in the gene_data\n", "print(\"First 10 mapped gene symbols:\")\n", "print(gene_data.index[:10])\n", "\n", "# Save the gene data to a CSV file\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": "617bbd55", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "a6647541", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:13:10.879682Z", "iopub.status.busy": "2025-03-25T07:13:10.879564Z", "iopub.status.idle": "2025-03-25T07:13:29.654011Z", "shell.execute_reply": "2025-03-25T07:13:29.653346Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data structure:\n", "{0: ['tissue: Rectal Colon Biopsy'], 1: ['gender: M', 'gender: F'], 2: ['subject identifier: SD52930', 'subject identifier: SD52931', 'subject identifier: SD52932', 'subject identifier: SD52933', 'subject identifier: SD52934', 'subject identifier: SD52935', 'subject identifier: SD52936', 'subject identifier: SD52937', 'subject identifier: SD52938', 'subject identifier: SD52939', 'subject identifier: SD52940', 'subject identifier: SD52941', 'subject identifier: SD52942', 'subject identifier: SD52943', 'subject identifier: SD52944', 'subject identifier: SD52945', 'subject identifier: SD52946', 'subject identifier: SD52947', 'subject identifier: SD52948', 'subject identifier: SD52949', 'subject identifier: SD52950', 'subject identifier: SD52951', 'subject identifier: SD52952', 'subject identifier: SD52953', 'subject identifier: SD52954', 'subject identifier: SD52958', 'subject identifier: SD52959', 'subject identifier: SD52960', 'subject identifier: SD52961', 'subject identifier: SD52962'], 3: ['disease: HV', 'disease: IBS-D', 'disease: IBS-C', 'disease: PIBD', 'disease: PINIBS', 'disease: PIBS'], 4: ['batch: 1_C', 'batch: 1_E', 'batch: 1_A', 'batch: 1_B', 'batch: 1_F', 'batch: 1_D', 'batch: 2_A', 'batch: 2_B']}\n", "Corrected clinical data saved to ../../output/preprocess/Irritable_bowel_syndrome_(IBS)/clinical_data/GSE36701.csv\n", "Linked data shape: (221, 21279)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data after handling missing values: (144, 21279)\n", "For the feature 'Irritable_bowel_syndrome_(IBS)', the least common label is '0.0' with 28 occurrences. This represents 19.44% of the dataset.\n", "The distribution of the feature 'Irritable_bowel_syndrome_(IBS)' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Irritable_bowel_syndrome_(IBS)/GSE36701.csv\n" ] } ], "source": [ "# 1. Load the normalized gene data \n", "gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n", "\n", "# 2. Re-extract clinical features from the SOFT file to get proper clinical data\n", "# Use the actual clinical data from the matrix file properly\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", "\n", "# 3. Create a correct clinical features dataframe\n", "# First inspect what's in the clinical data\n", "clinical_data_dict = get_unique_values_by_row(clinical_data)\n", "print(\"Clinical data structure:\")\n", "print(clinical_data_dict)\n", "\n", "# Based on the sample characteristics dictionary shown previously, \n", "# extract and process clinical features\n", "selected_clinical_df = pd.DataFrame()\n", "\n", "# Process disease state row manually to ensure correct mapping\n", "disease_row = clinical_data.iloc[trait_row]\n", "samples = [col for col in disease_row.index if col != \"!Sample_geo_accession\"]\n", "trait_values = []\n", "\n", "for sample in samples:\n", " value = disease_row[sample]\n", " if pd.isna(value):\n", " trait_values.append(None)\n", " else:\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if \"IBS\" in value:\n", " trait_values.append(1) # IBS is our target trait\n", " elif \"IBD\" in value:\n", " trait_values.append(0) # IBD is the control\n", " else:\n", " trait_values.append(None)\n", "\n", "# Create dataframe with processed values\n", "selected_clinical_df[trait] = trait_values\n", "selected_clinical_df.index = samples\n", "\n", "# Save the corrected clinical data\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "selected_clinical_df.to_csv(out_clinical_data_file)\n", "print(f\"Corrected clinical data saved to {out_clinical_data_file}\")\n", "\n", "# 4. Link the clinical and genetic data\n", "linked_data = pd.DataFrame()\n", "# Transpose gene data to have samples as rows and genes as columns\n", "gene_data_t = gene_data.T\n", "# Verify alignment of sample IDs between clinical and gene data\n", "common_samples = list(set(selected_clinical_df.index) & set(gene_data_t.index))\n", "if common_samples:\n", " gene_data_filtered = gene_data_t.loc[common_samples]\n", " clinical_data_filtered = selected_clinical_df.loc[common_samples]\n", " # Join the data\n", " linked_data = pd.concat([clinical_data_filtered, gene_data_filtered], axis=1)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", "else:\n", " # Alternative linking approach if sample IDs don't directly match\n", " print(\"No common sample IDs found. Attempting alternative linking...\")\n", " # The GSM ids in gene data columns may correspond to the sample IDs\n", " clinical_data_reset = selected_clinical_df.reset_index()\n", " clinical_data_reset.columns = [\"Sample\"] + list(clinical_data_reset.columns[1:])\n", " gene_data_cols = list(gene_data.columns)\n", " \n", " # Create merged dataframe\n", " data_dict = {trait: []}\n", " # Add trait values\n", " for col in gene_data_cols:\n", " sample_idx = clinical_data_reset.index[clinical_data_reset[\"Sample\"] == col] if \"Sample\" in clinical_data_reset.columns else []\n", " if len(sample_idx) > 0:\n", " data_dict[trait].append(clinical_data_reset.loc[sample_idx[0], trait])\n", " else:\n", " data_dict[trait].append(None)\n", " \n", " # Add gene expression values\n", " for gene in gene_data.index:\n", " data_dict[gene] = list(gene_data.loc[gene])\n", " \n", " linked_data = pd.DataFrame(data_dict, index=gene_data_cols)\n", " print(f\"Alternative linked data shape: {linked_data.shape}\")\n", "\n", "# 5. Handle missing values in the linked data\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Data after handling missing values: {linked_data.shape}\")\n", "\n", "# 6. Determine whether the trait and some demographic features are severely biased\n", "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# 7. 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 patients with IBS and IBD, examining effects of relaxation response mind-body intervention.\"\n", ")\n", "\n", "# 8. If the linked data is usable, save it as a CSV file\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\"Linked data saved to {out_data_file}\")\n", "else:\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 }