{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "4b434cfc", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:37:51.995139Z", "iopub.status.busy": "2025-03-25T08:37:51.995040Z", "iopub.status.idle": "2025-03-25T08:37:52.157665Z", "shell.execute_reply": "2025-03-25T08:37:52.157332Z" } }, "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 = \"Depression\"\n", "cohort = \"GSE149980\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Depression\"\n", "in_cohort_dir = \"../../input/GEO/Depression/GSE149980\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Depression/GSE149980.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Depression/gene_data/GSE149980.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Depression/clinical_data/GSE149980.csv\"\n", "json_path = \"../../output/preprocess/Depression/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "bbcda955", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "bcfc6570", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:37:52.159011Z", "iopub.status.busy": "2025-03-25T08:37:52.158877Z", "iopub.status.idle": "2025-03-25T08:37:53.110834Z", "shell.execute_reply": "2025-03-25T08:37:53.110423Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Gene expression of Lymphoblastoid Cell Lines–LCLs from Depressed Patients after in-vitro treatment with citalopram–CTP\"\n", "!Series_summary\t\"We used whole gene gene expression profiling to identify potential gene expression biomarkers associated for the treatment individualization of unipolar depression.\"\n", "!Series_overall_design\t\"Gene expression was measured after 24 and 48 hours of in-vitro treatment with 3 µM CTP in n=17 LCLs derived from depressed patients with documented clinical treatment outcome to SSRIs.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['response status: responder', 'response status: non-responder'], 1: ['tissue: Lymphoblastoid Cell Lines (LCLs)']}\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": "cb1f51b5", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "eb7e8699", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:37:53.112366Z", "iopub.status.busy": "2025-03-25T08:37:53.112260Z", "iopub.status.idle": "2025-03-25T08:37:53.120791Z", "shell.execute_reply": "2025-03-25T08:37:53.120517Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of extracted clinical data:\n", "{'GSM4519184': [1.0], 'GSM4519185': [1.0], 'GSM4519186': [1.0], 'GSM4519187': [1.0], 'GSM4519188': [1.0], 'GSM4519189': [1.0], 'GSM4519190': [1.0], 'GSM4519191': [1.0], 'GSM4519192': [1.0], 'GSM4519193': [1.0], 'GSM4519194': [1.0], 'GSM4519195': [1.0], 'GSM4519196': [1.0], 'GSM4519197': [1.0], 'GSM4519198': [1.0], 'GSM4519199': [1.0], 'GSM4519200': [1.0], 'GSM4519201': [1.0], 'GSM4519202': [0.0], 'GSM4519203': [0.0], 'GSM4519204': [0.0], 'GSM4519205': [0.0], 'GSM4519206': [0.0], 'GSM4519207': [0.0], 'GSM4519208': [0.0], 'GSM4519209': [0.0], 'GSM4519210': [0.0], 'GSM4519211': [0.0], 'GSM4519212': [0.0], 'GSM4519213': [0.0], 'GSM4519214': [0.0], 'GSM4519215': [0.0], 'GSM4519216': [0.0], 'GSM4519217': [0.0], 'GSM4519218': [1.0], 'GSM4519219': [1.0], 'GSM4519220': [1.0], 'GSM4519221': [1.0], 'GSM4519222': [1.0], 'GSM4519223': [1.0], 'GSM4519224': [1.0], 'GSM4519225': [1.0], 'GSM4519226': [1.0], 'GSM4519227': [1.0], 'GSM4519228': [1.0], 'GSM4519229': [1.0], 'GSM4519230': [1.0], 'GSM4519231': [1.0], 'GSM4519232': [1.0], 'GSM4519233': [1.0], 'GSM4519234': [1.0], 'GSM4519235': [1.0], 'GSM4519236': [0.0], 'GSM4519237': [0.0], 'GSM4519238': [0.0], 'GSM4519239': [0.0], 'GSM4519240': [0.0], 'GSM4519241': [0.0], 'GSM4519242': [0.0], 'GSM4519243': [0.0], 'GSM4519244': [0.0], 'GSM4519245': [0.0], 'GSM4519246': [0.0], 'GSM4519247': [0.0], 'GSM4519248': [0.0], 'GSM4519249': [0.0], 'GSM4519250': [0.0], 'GSM4519251': [0.0]}\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "from typing import Optional, Dict, Any, Callable\n", "import json\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains gene expression data of Lymphoblastoid Cell Lines\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# Looking at the Sample Characteristics Dictionary:\n", "# Key 0 contains 'response status' which can be used as our trait (depression treatment response)\n", "# There's no age or gender information\n", "trait_row = 0\n", "age_row = None\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value: str) -> int:\n", " \"\"\"Convert depression treatment response to binary value.\"\"\"\n", " if isinstance(value, str):\n", " # Extract the part after the colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Convert to binary\n", " if \"responder\" in value.lower() and \"non\" not in value.lower():\n", " return 1 # Responder\n", " elif \"non-responder\" in value.lower():\n", " return 0 # Non-responder\n", " \n", " return None # For any other or unknown values\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"Convert age to float. Not used in this dataset.\"\"\"\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"Convert gender to binary. Not used in this dataset.\"\"\"\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Conduct initial filtering on dataset usability\n", "is_trait_available = trait_row is not None\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", " # We should use the clinical_data that was loaded in a previous step\n", " # Since the actual clinical_data should be available in the environment\n", " # We'll use geo_select_clinical_features with the existing clinical_data\n", " \n", " try:\n", " # Extract clinical features using the provided function\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data, # Assuming clinical_data is already loaded\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the extracted data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of extracted clinical data:\")\n", " print(preview)\n", " \n", " # Save to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " except NameError:\n", " print(\"Warning: clinical_data not found. The clinical data extraction step cannot be completed.\")\n", " print(\"Please ensure the clinical_data DataFrame is available from a previous step.\")\n" ] }, { "cell_type": "markdown", "id": "4c444503", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "c7ffc2a4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:37:53.121914Z", "iopub.status.busy": "2025-03-25T08:37:53.121813Z", "iopub.status.idle": "2025-03-25T08:37:53.489631Z", "shell.execute_reply": "2025-03-25T08:37:53.489317Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Depression/GSE149980/GSE149980_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (50739, 68)\n", "First 20 gene/probe identifiers:\n", "Index(['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107',\n", " '(+)E1A_r60_a135', '(+)E1A_r60_a20', '(+)E1A_r60_a22', '(+)E1A_r60_a97',\n", " '(+)E1A_r60_n11', '(+)E1A_r60_n9', '3xSLv1', 'A_19_P00315452',\n", " 'A_19_P00315459', 'A_19_P00315482', 'A_19_P00315492', 'A_19_P00315493',\n", " 'A_19_P00315502', 'A_19_P00315506', 'A_19_P00315518', 'A_19_P00315519'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. Get the SOFT and matrix file paths again \n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "print(f\"Matrix file found: {matrix_file}\")\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_data\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " \n", " # 3. Print the first 20 row IDs (gene or probe identifiers)\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20])\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n" ] }, { "cell_type": "markdown", "id": "cc2f2dcf", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "35651d57", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:37:53.490749Z", "iopub.status.busy": "2025-03-25T08:37:53.490630Z", "iopub.status.idle": "2025-03-25T08:37:53.492478Z", "shell.execute_reply": "2025-03-25T08:37:53.492205Z" } }, "outputs": [], "source": [ "# Analyze the gene identifiers\n", "# These identifiers (like '(+)E1A_r60_1', 'A_19_P00315452') are not standard human gene symbols\n", "# They appear to be probe IDs from a microarray platform that need to be mapped to gene symbols\n", "\n", "# Human gene symbols would typically be like BRCA1, TP53, IL6, etc.\n", "# The identifiers we see are platform-specific probe IDs that need mapping\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "d23cfbbc", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "64856b18", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:37:53.493365Z", "iopub.status.busy": "2025-03-25T08:37:53.493266Z", "iopub.status.idle": "2025-03-25T08:38:01.970519Z", "shell.execute_reply": "2025-03-25T08:38:01.970158Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Platform title found: Agilent-039494 SurePrint G3 Human GE v2 8x60K Microarray 039381 (Probe Name version)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "{'ID': ['GE_BrightCorner', 'DarkCorner', 'A_23_P117082', 'A_33_P3246448', 'A_33_P3318220', 'A_33_P3236322', 'A_33_P3319925', 'A_21_P0000509', 'A_21_P0000744', 'A_24_P215804'], 'SPOT_ID': ['CONTROL', 'CONTROL', 'A_23_P117082', 'A_33_P3246448', 'A_33_P3318220', 'A_33_P3236322', 'A_33_P3319925', 'A_21_P0000509', 'A_21_P0000744', 'A_24_P215804'], 'CONTROL_TYPE': ['pos', 'pos', 'FALSE', 'FALSE', 'FALSE', 'FALSE', 'FALSE', 'FALSE', 'FALSE', 'FALSE'], 'REFSEQ': [nan, nan, 'NM_015987', 'NM_080671', 'NM_178466', nan, 'XM_001133269', 'NR_024244', 'NR_038269', 'NM_016951'], 'GB_ACC': [nan, nan, 'NM_015987', 'NM_080671', 'NM_178466', 'AK128005', 'XM_001133269', 'NR_024244', 'NR_038269', 'NM_016951'], 'LOCUSLINK_ID': [nan, nan, 50865.0, 23704.0, 128861.0, 100129869.0, 730249.0, nan, nan, 51192.0], 'GENE_SYMBOL': [nan, nan, 'HEBP1', 'KCNE4', 'BPIFA3', 'LOC100129869', 'IRG1', 'SNAR-G2', 'LOC100506844', 'CKLF'], 'GENE_NAME': [nan, nan, 'heme binding protein 1', 'potassium voltage-gated channel, Isk-related family, member 4', 'BPI fold containing family A, member 3', 'uncharacterized LOC100129869', 'immunoresponsive 1 homolog (mouse)', 'small ILF3/NF90-associated RNA G2', 'uncharacterized LOC100506844', 'chemokine-like factor'], 'UNIGENE_ID': [nan, nan, 'Hs.642618', 'Hs.348522', 'Hs.360989', nan, 'Hs.160789', 'Hs.717308', 'Hs.90286', 'Hs.15159'], 'ENSEMBL_ID': [nan, nan, 'ENST00000014930', 'ENST00000281830', 'ENST00000375454', nan, 'ENST00000449753', nan, 'ENST00000551421', nan], 'ACCESSION_STRING': [nan, nan, 'ref|NM_015987|ens|ENST00000014930|gb|AF117615|gb|BC016277', 'ref|NM_080671|ens|ENST00000281830|tc|THC2655788', 'ref|NM_178466|ens|ENST00000375454|ens|ENST00000471233|tc|THC2478474', 'gb|AK128005|tc|THC2484382', 'ens|ENST00000449753|ens|ENST00000377462|ref|XM_001133269|ref|XM_003403661', 'ref|NR_024244', 'ref|NR_038269|ens|ENST00000551421|ens|ENST00000546580|ens|ENST00000553102', 'ref|NM_016951|ref|NM_181641|ref|NM_181640|ref|NM_016326'], 'CHROMOSOMAL_LOCATION': [nan, nan, 'chr12:13127906-13127847', 'chr2:223920197-223920256', 'chr20:31812208-31812267', 'chr20:56533874-56533815', 'chr13:77532009-77532068', 'chr19:49534993-49534934', 'chr12:58329728-58329669', 'chr16:66599900-66599959'], 'CYTOBAND': [nan, nan, 'hs|12p13.1', 'hs|2q36.1', 'hs|20q11.21', 'hs|20q13.32', 'hs|13q22.3', 'hs|19q13.33', 'hs|12q14.1', 'hs|16q21'], 'DESCRIPTION': [nan, nan, 'Homo sapiens heme binding protein 1 (HEBP1), mRNA [NM_015987]', 'Homo sapiens potassium voltage-gated channel, Isk-related family, member 4 (KCNE4), mRNA [NM_080671]', 'Homo sapiens BPI fold containing family A, member 3 (BPIFA3), transcript variant 1, mRNA [NM_178466]', 'Homo sapiens cDNA FLJ46124 fis, clone TESTI2040372. [AK128005]', 'immunoresponsive 1 homolog (mouse) [Source:HGNC Symbol;Acc:33904] [ENST00000449753]', 'Homo sapiens small ILF3/NF90-associated RNA G2 (SNAR-G2), small nuclear RNA [NR_024244]', 'Homo sapiens uncharacterized LOC100506844 (LOC100506844), non-coding RNA [NR_038269]', 'Homo sapiens chemokine-like factor (CKLF), transcript variant 1, mRNA [NM_016951]'], 'GO_ID': [nan, nan, 'GO:0005488(binding)|GO:0005576(extracellular region)|GO:0005737(cytoplasm)|GO:0005739(mitochondrion)|GO:0005829(cytosol)|GO:0007623(circadian rhythm)|GO:0020037(heme binding)', 'GO:0005244(voltage-gated ion channel activity)|GO:0005249(voltage-gated potassium channel activity)|GO:0006811(ion transport)|GO:0006813(potassium ion transport)|GO:0016020(membrane)|GO:0016021(integral to membrane)|GO:0016324(apical plasma membrane)', 'GO:0005576(extracellular region)|GO:0008289(lipid binding)', nan, 'GO:0019543(propionate catabolic process)|GO:0032496(response to lipopolysaccharide)|GO:0047547(2-methylcitrate dehydratase activity)', nan, nan, 'GO:0005576(extracellular region)|GO:0005615(extracellular space)|GO:0006935(chemotaxis)|GO:0008009(chemokine activity)|GO:0008283(cell proliferation)|GO:0016020(membrane)|GO:0016021(integral to membrane)|GO:0030593(neutrophil chemotaxis)|GO:0032940(secretion by cell)|GO:0048246(macrophage chemotaxis)|GO:0048247(lymphocyte chemotaxis)'], 'SEQUENCE': [nan, nan, 'AAGGGGGAAAATGTGATTTGTGCCTGATCTTTCATCTGTGATTCTTATAAGAGCTTTGTC', 'GCAAGTCTCTCTGCACCTATTAAAAAGTGATGTATATACTTCCTTCTTATTCTGTTGAGT', 'CATTCCATAAGGAGTGGTTCTCGGCAAATATCTCACTTGAATTTGACCTTGAATTGAGAC', 'ATTTATTTTCACAAGTGCATAGCGGCCAACACCACCAGCACTAACCAGAGTGGATTCTTG', 'AGAAGACCTAGAAGACTGTTCTGTGTTAACTACACTTCTCAAAGGACCCTCTCCACCAGA', 'AGGGGAGGGTTCGAGGGTACGAGTTCGAGGCCAACCGGGTCCACATTGGTTGAGAAAAAA', 'AGTCGTACCCTCTTGTTTTTCTCTGAGTCAGTCTTAAGGTGAAATGAAGTGTGGCCCAGT', 'AAAGAAGTTTTGTAATTTTATATTACTTTTTAGTTTGATACTAAGTATTAAACATATTTC']}\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", "# Check if there are any platforms defined in the SOFT file that might contain annotation data\n", "with gzip.open(soft_file, 'rt') as f:\n", " soft_content = f.read()\n", "\n", "# Look for platform sections in the SOFT file\n", "platform_sections = re.findall(r'^!Platform_title\\s*=\\s*(.+)$', soft_content, re.MULTILINE)\n", "if platform_sections:\n", " print(f\"Platform title found: {platform_sections[0]}\")\n", "\n", "# Try to extract more annotation data by reading directly from the SOFT file\n", "# Look for lines that might contain gene symbol mappings\n", "symbol_pattern = re.compile(r'ID_REF\\s+Symbol|ID\\s+Gene Symbol', re.IGNORECASE)\n", "annotation_lines = []\n", "with gzip.open(soft_file, 'rt') as f:\n", " for line in f:\n", " if symbol_pattern.search(line):\n", " annotation_lines.append(line)\n", " # Collect the next few lines to see the annotation structure\n", " for _ in range(10):\n", " annotation_lines.append(next(f, ''))\n", "\n", "if annotation_lines:\n", " print(\"Found potential gene symbol mappings:\")\n", " for line in annotation_lines:\n", " print(line.strip())\n", "\n", "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n", "print(\"\\nGene annotation preview:\")\n", "print(preview_df(gene_annotation, n=10))\n", "\n", "# If we need an alternative source of mapping, check if there are any other annotation files in the cohort directory\n", "cohort_files = os.listdir(in_cohort_dir)\n", "annotation_files = [f for f in cohort_files if 'annotation' in f.lower() or 'platform' in f.lower()]\n", "if annotation_files:\n", " print(\"\\nAdditional annotation files found in the cohort directory:\")\n", " for file in annotation_files:\n", " print(file)\n" ] }, { "cell_type": "markdown", "id": "ebfdd05c", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "5ae708c1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:38:01.971871Z", "iopub.status.busy": "2025-03-25T08:38:01.971756Z", "iopub.status.idle": "2025-03-25T08:38:03.101993Z", "shell.execute_reply": "2025-03-25T08:38:03.101665Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping dataframe shape: (46204, 2)\n", "First few rows of the gene mapping dataframe:\n", " ID Gene\n", "2 A_23_P117082 HEBP1\n", "3 A_33_P3246448 KCNE4\n", "4 A_33_P3318220 BPIFA3\n", "5 A_33_P3236322 LOC100129869\n", "6 A_33_P3319925 IRG1\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Transformed gene expression data shape: (20353, 68)\n", "First few gene symbols:\n", "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M', 'A2ML1', 'A2MP1', 'A4GALT',\n", " 'A4GNT', 'AA06'],\n", " dtype='object', name='Gene')\n", "After normalizing gene symbols, shape: (19847, 68)\n", "Preview of normalized gene expression data (first 5 genes, first 5 samples):\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " GSM4519184 GSM4519185 GSM4519186 GSM4519187 GSM4519188\n", "Gene \n", "A1BG 0.857412 0.183019 -1.851454 -1.841433 0.033260\n", "A1BG-AS1 0.193574 0.635310 -0.273058 0.066432 0.151078\n", "A1CF 0.951021 -0.351138 -0.663651 -0.789045 0.338096\n", "A2M -0.620814 -0.329174 -0.151582 -0.199618 -1.207462\n", "A2ML1 0.823854 -0.336316 -0.476297 -0.466115 0.673593\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Depression/gene_data/GSE149980.csv\n" ] } ], "source": [ "# 1. Identify the columns in gene_annotation that map to gene identifiers and gene symbols\n", "# Based on the preview of gene_annotation, 'ID' appears to be the gene identifier column, matching the identifiers seen in gene_data\n", "# 'GENE_SYMBOL' contains the gene symbols we want to map to\n", "\n", "# 2. Create the gene mapping dataframe using the get_gene_mapping function\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')\n", "print(f\"Gene mapping dataframe shape: {gene_mapping.shape}\")\n", "print(\"First few rows of the gene mapping dataframe:\")\n", "print(gene_mapping.head())\n", "\n", "# 3. Convert probe-level measurements to gene-level expression data\n", "# Use the apply_gene_mapping function to perform the conversion\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(f\"Transformed gene expression data shape: {gene_data.shape}\")\n", "print(\"First few gene symbols:\")\n", "print(gene_data.index[:10])\n", "\n", "# 4. Further normalize gene symbols to handle synonyms\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"After normalizing gene symbols, shape: {gene_data.shape}\")\n", "print(\"Preview of normalized gene expression data (first 5 genes, first 5 samples):\")\n", "print(gene_data.iloc[:5, :5])\n", "\n", "# 5. Save the gene expression data to the output 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": "1d8d39b1", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "49440fa8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:38:03.103387Z", "iopub.status.busy": "2025-03-25T08:38:03.103272Z", "iopub.status.idle": "2025-03-25T08:38:13.163245Z", "shell.execute_reply": "2025-03-25T08:38:13.162799Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Selected clinical data shape: (1, 68)\n", "Clinical data preview:\n", "{'GSM4519184': [1.0], 'GSM4519185': [1.0], 'GSM4519186': [1.0], 'GSM4519187': [1.0], 'GSM4519188': [1.0], 'GSM4519189': [1.0], 'GSM4519190': [1.0], 'GSM4519191': [1.0], 'GSM4519192': [1.0], 'GSM4519193': [1.0], 'GSM4519194': [1.0], 'GSM4519195': [1.0], 'GSM4519196': [1.0], 'GSM4519197': [1.0], 'GSM4519198': [1.0], 'GSM4519199': [1.0], 'GSM4519200': [1.0], 'GSM4519201': [1.0], 'GSM4519202': [0.0], 'GSM4519203': [0.0], 'GSM4519204': [0.0], 'GSM4519205': [0.0], 'GSM4519206': [0.0], 'GSM4519207': [0.0], 'GSM4519208': [0.0], 'GSM4519209': [0.0], 'GSM4519210': [0.0], 'GSM4519211': [0.0], 'GSM4519212': [0.0], 'GSM4519213': [0.0], 'GSM4519214': [0.0], 'GSM4519215': [0.0], 'GSM4519216': [0.0], 'GSM4519217': [0.0], 'GSM4519218': [1.0], 'GSM4519219': [1.0], 'GSM4519220': [1.0], 'GSM4519221': [1.0], 'GSM4519222': [1.0], 'GSM4519223': [1.0], 'GSM4519224': [1.0], 'GSM4519225': [1.0], 'GSM4519226': [1.0], 'GSM4519227': [1.0], 'GSM4519228': [1.0], 'GSM4519229': [1.0], 'GSM4519230': [1.0], 'GSM4519231': [1.0], 'GSM4519232': [1.0], 'GSM4519233': [1.0], 'GSM4519234': [1.0], 'GSM4519235': [1.0], 'GSM4519236': [0.0], 'GSM4519237': [0.0], 'GSM4519238': [0.0], 'GSM4519239': [0.0], 'GSM4519240': [0.0], 'GSM4519241': [0.0], 'GSM4519242': [0.0], 'GSM4519243': [0.0], 'GSM4519244': [0.0], 'GSM4519245': [0.0], 'GSM4519246': [0.0], 'GSM4519247': [0.0], 'GSM4519248': [0.0], 'GSM4519249': [0.0], 'GSM4519250': [0.0], 'GSM4519251': [0.0]}\n", "Clinical data saved to ../../output/preprocess/Depression/clinical_data/GSE149980.csv\n", "Linked data shape: (68, 19848)\n", "Linked data preview (first 5 rows, 5 columns):\n", " Depression A1BG A1BG-AS1 A1CF A2M\n", "GSM4519184 1.0 0.857412 0.193574 0.951021 -0.620814\n", "GSM4519185 1.0 0.183019 0.635310 -0.351138 -0.329174\n", "GSM4519186 1.0 -1.851454 -0.273058 -0.663651 -0.151582\n", "GSM4519187 1.0 -1.841433 0.066432 -0.789045 -0.199618\n", "GSM4519188 1.0 0.033260 0.151078 0.338096 -1.207462\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (68, 19848)\n", "For the feature 'Depression', the least common label is '0.0' with 32 occurrences. This represents 47.06% of the dataset.\n", "The distribution of the feature 'Depression' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Depression/GSE149980.csv\n" ] } ], "source": [ "# 1. We'll normalize gene symbols in the gene expression data\n", "# Note: We've already done this in step 6, so we can skip this part\n", "\n", "# 2. Link the clinical and genetic data\n", "# First, let's make sure we have the correct clinical data from step 2\n", "# Review the clinical data attributes from step 2\n", "def convert_trait(value: str) -> int:\n", " \"\"\"Convert depression treatment response to binary value.\"\"\"\n", " if isinstance(value, str):\n", " # Extract the part after the colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Convert to binary\n", " if \"responder\" in value.lower() and \"non\" not in value.lower():\n", " return 1 # Responder\n", " elif \"non-responder\" in value.lower():\n", " return 0 # Non-responder\n", " \n", " return None # For any other or unknown values\n", "\n", "# Get clinical data using the correct row index identified in step 2\n", "selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=0, # Using row 0 for response status as identified in step 2\n", " convert_trait=convert_trait,\n", " age_row=None, # No age data available\n", " convert_age=None,\n", " gender_row=None, # No gender data available\n", " convert_gender=None\n", ")\n", "\n", "print(f\"Selected clinical data shape: {selected_clinical_df.shape}\")\n", "print(\"Clinical data preview:\")\n", "print(preview_df(selected_clinical_df))\n", "\n", "# Save clinical data for future reference\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "selected_clinical_df.to_csv(out_clinical_data_file)\n", "print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "\n", "# Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(\"Linked data preview (first 5 rows, 5 columns):\")\n", "print(linked_data.iloc[:5, :5] if not linked_data.empty else \"Linked data is empty\")\n", "\n", "# 3. Handle missing values\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", "\n", "# 4. Check for bias in features\n", "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# 5. Validate and save 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_biased,\n", " df=linked_data,\n", " note=\"Dataset contains gene expression data from Lymphoblastoid Cell Lines of depressed patients with SSRI treatment outcomes (responders/non-responders).\"\n", ")\n", "\n", "# 6. Save the linked data if usable\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Dataset is not usable for analysis. No linked data file 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 }