{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "a1a213b0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:45.342869Z", "iopub.status.busy": "2025-03-25T03:55:45.342721Z", "iopub.status.idle": "2025-03-25T03:55:45.512456Z", "shell.execute_reply": "2025-03-25T03:55:45.512004Z" } }, "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 = \"Schizophrenia\"\n", "cohort = \"GSE120342\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Schizophrenia\"\n", "in_cohort_dir = \"../../input/GEO/Schizophrenia/GSE120342\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Schizophrenia/GSE120342.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Schizophrenia/gene_data/GSE120342.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Schizophrenia/clinical_data/GSE120342.csv\"\n", "json_path = \"../../output/preprocess/Schizophrenia/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "b6d885d2", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "ef9b0da7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:45.513915Z", "iopub.status.busy": "2025-03-25T03:55:45.513765Z", "iopub.status.idle": "2025-03-25T03:55:45.577644Z", "shell.execute_reply": "2025-03-25T03:55:45.577223Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Aberrant transcriptomes and DNA methylomes define pathways that drive pathogenesis and loss of brain laterality/asymmetry in schizophrenia and bipolar disorder\"\n", "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n", "!Series_overall_design\t\"Refer to individual Series\"\n", "Sample Characteristics Dictionary:\n", "{0: ['disease state: control', 'disease state: SCZ', 'disease state: BD(-)', 'disease state: BD(+)'], 1: ['laterality: left', 'laterality: right']}\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": "e5911ffc", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "f66f024b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:45.579084Z", "iopub.status.busy": "2025-03-25T03:55:45.578964Z", "iopub.status.idle": "2025-03-25T03:55:45.587311Z", "shell.execute_reply": "2025-03-25T03:55:45.586890Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical features preview:\n", "{'GSM3398477': [0.0], 'GSM3398478': [0.0], 'GSM3398479': [0.0], 'GSM3398480': [0.0], 'GSM3398481': [0.0], 'GSM3398482': [0.0], 'GSM3398483': [0.0], 'GSM3398484': [0.0], 'GSM3398485': [0.0], 'GSM3398486': [0.0], 'GSM3398487': [1.0], 'GSM3398488': [1.0], 'GSM3398489': [1.0], 'GSM3398490': [1.0], 'GSM3398491': [1.0], 'GSM3398492': [1.0], 'GSM3398493': [1.0], 'GSM3398494': [1.0], 'GSM3398495': [1.0], 'GSM3398496': [1.0], 'GSM3398497': [nan], 'GSM3398498': [nan], 'GSM3398499': [nan], 'GSM3398500': [nan], 'GSM3398501': [nan], 'GSM3398502': [nan], 'GSM3398503': [nan], 'GSM3398504': [nan], 'GSM3398505': [nan], 'GSM3398506': [nan]}\n", "Clinical data saved to ../../output/preprocess/Schizophrenia/clinical_data/GSE120342.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Callable, Optional, Dict, Any\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this appears to be a study about transcriptomes and DNA methylomes\n", "# in schizophrenia and bipolar disorder, so gene expression data is likely available\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# Trait (Schizophrenia) data is in row 0 (disease state)\n", "trait_row = 0\n", "# There's no age information in the sample characteristics\n", "age_row = None\n", "# There's no gender information in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert trait value to binary (0 for control, 1 for SCZ)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value part after colon if present\n", " if ':' in str(value):\n", " value = str(value).split(':', 1)[1].strip()\n", " \n", " value = str(value).lower()\n", " if 'control' in value:\n", " return 0\n", " elif 'scz' in value or 'schizophrenia' in value:\n", " return 1\n", " else:\n", " # This handles BD cases which aren't relevant for our Schizophrenia trait\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to continuous (not used in this dataset)\"\"\"\n", " # This function is not actually used since age data is not available\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender value to binary (not used in this dataset)\"\"\"\n", " # This function is not actually used since gender data is not available\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", "# Use the function to validate and save cohort info\n", "initial_validation = 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", " # Assuming clinical_data was defined in a previous step\n", " try:\n", " # Create clinical features dataframe using the library function\n", " clinical_features_df = geo_select_clinical_features(\n", " 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 resulting dataframe\n", " preview = preview_df(clinical_features_df)\n", " print(\"Clinical features preview:\")\n", " print(preview)\n", " \n", " # Ensure output directory exists\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the clinical data to CSV\n", " clinical_features_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " except NameError:\n", " print(\"Clinical data not defined in previous steps. Unable to extract clinical features.\")\n", "else:\n", " print(\"Clinical data not available. Skipping clinical feature extraction.\")\n" ] }, { "cell_type": "markdown", "id": "43ed5984", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "62787c29", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:45.588516Z", "iopub.status.busy": "2025-03-25T03:55:45.588405Z", "iopub.status.idle": "2025-03-25T03:55:45.667371Z", "shell.execute_reply": "2025-03-25T03:55:45.666825Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Schizophrenia/GSE120342/GSE120342-GPL16311_series_matrix.txt.gz\n", "Gene data shape: (19070, 30)\n", "First 20 gene/probe identifiers:\n", "Index(['100009676_at', '10000_at', '10001_at', '10002_at', '10003_at',\n", " '100048912_at', '100049716_at', '10004_at', '10005_at', '10006_at',\n", " '10007_at', '10008_at', '100093630_at', '10009_at', '1000_at',\n", " '100101467_at', '100101938_at', '10010_at', '100113407_at', '10011_at'],\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": "2c2c414b", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "64e1a766", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:45.668946Z", "iopub.status.busy": "2025-03-25T03:55:45.668823Z", "iopub.status.idle": "2025-03-25T03:55:45.671189Z", "shell.execute_reply": "2025-03-25T03:55:45.670737Z" } }, "outputs": [], "source": [ "# These identifiers with the format 'cg#####' are DNA methylation probe IDs used on methylation arrays\n", "# (likely from Illumina arrays), not gene symbols. They need to be mapped to corresponding genes.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "d2c09879", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "b4be4495", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:45.672752Z", "iopub.status.busy": "2025-03-25T03:55:45.672641Z", "iopub.status.idle": "2025-03-25T03:55:57.505737Z", "shell.execute_reply": "2025-03-25T03:55:57.505166Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'Name', 'IlmnStrand', 'AddressA_ID', 'AlleleA_ProbeSeq', 'AddressB_ID', 'AlleleB_ProbeSeq', 'GenomeBuild', 'Chr', 'MapInfo', 'Ploidy', 'Species', 'Source', 'SourceVersion', 'SourceStrand', 'SourceSeq', 'TopGenomicSeq', 'Next_Base', 'Color_Channel', 'TSS_Coordinate', 'Gene_Strand', 'Gene_ID', 'Symbol', 'Synonym', 'Accession', 'GID', 'Annotation', 'Product', 'Distance_to_TSS', 'CPG_ISLAND', 'CPG_ISLAND_LOCATIONS', 'MIR_CPG_ISLAND', 'RANGE_GB', 'RANGE_START', 'RANGE_END', 'RANGE_STRAND', 'GB_ACC', 'ORF']\n", "{'ID': ['cg00000292', 'cg00002426', 'cg00003994', 'cg00005847', 'cg00006414'], 'Name': ['cg00000292', 'cg00002426', 'cg00003994', 'cg00005847', 'cg00006414'], 'IlmnStrand': ['TOP', 'TOP', 'TOP', 'BOT', 'BOT'], 'AddressA_ID': [990370.0, 6580397.0, 7150184.0, 4850717.0, 6980731.0], 'AlleleA_ProbeSeq': ['AAACATTAATTACCAACCACTCTTCCAAAAAACACTTACCATTAAAACCA', 'AATATAATAACATTACCTTACCCATCTTATAATCAAACCAAACAAAAACA', 'AATAATAATAATACCCCCTATAATACTAACTAACAAACATACCCTCTTCA', 'TACTATAATACACCCTATATTTAAAACACTAAACTTACCCCATTAAAACA', 'CTCAAAAACCAAACAAAACAAAACCCCAATACTAATCATTAATAAAATCA'], 'AddressB_ID': [6660678.0, 6100343.0, 7150392.0, 1260113.0, 4280093.0], 'AlleleB_ProbeSeq': ['AAACATTAATTACCAACCGCTCTTCCAAAAAACACTTACCATTAAAACCG', 'AATATAATAACATTACCTTACCCGTCTTATAATCAAACCAAACGAAAACG', 'AATAATAATAATACCCCCTATAATACTAACTAACAAACATACCCTCTTCG', 'TACTATAATACACCCTATATTTAAAACACTAAACTTACCCCATTAAAACG', 'CTCGAAAACCGAACAAAACAAAACCCCAATACTAATCGTTAATAAAATCG'], 'GenomeBuild': [36.0, 36.0, 36.0, 36.0, 36.0], 'Chr': ['16', '3', '7', '2', '7'], 'MapInfo': [28797601.0, 57718583.0, 15692387.0, 176737319.0, 148453770.0], 'Ploidy': ['diploid', 'diploid', 'diploid', 'diploid', 'diploid'], 'Species': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Source': ['NCBI:RefSeq', 'NCBI:RefSeq', 'NCBI:RefSeq', 'NCBI:RefSeq', 'NCBI:RefSeq'], 'SourceVersion': [36.1, 36.1, 36.1, 36.1, 36.1], 'SourceStrand': ['TOP', 'TOP', 'BOT', 'BOT', 'BOT'], 'SourceSeq': ['CGGCCTCAATGGTAAGTGTCCCTTGGAAGAGCGGCTGGTAATTAATGCCC', 'CGCTCTCGTCTGGTTTGATCACAAGACGGGCAAGGTAATGTCACCACATT', 'GGTGGTGGTGGTGCCCCCTGTGATGCTGGCTGGCAAACATGCCCTCTTCG', 'TACTGTAATGCACCCTGTATTTAAGGCACTGGGCTTGCCCCATTAAAGCG', 'CTCGGAAACCGAGCAGGGCAAAACCCCAGTGCTGATCGTTAGTGGGATCG'], 'TopGenomicSeq': ['TGGGGTGAGTGAGACCACGGGCCTCACCCCGGACCAAGTTAAGCGGAATCTGGAGAAATA[CG]GCCTCAATGGTAAGTGTCCCTTGGAAGAGCGGCTGGTAATTAATGCCCTCCTGCACCCCC', 'CCGCTGTCGACCAGCGCAGAATAATGCCACTTTTGATTGCAAAGTGCTATCAAGGAACCA[CG]CTCTCGTCTGGTTTGATCACAAGACGGGCAAGGTAATGTCACCACATTGTCCAGCGGCAT', 'GGTGGTGGTGGTGGTGGTGGTGGTGCCCCCTGTGATGCTGGCTGGCAAACATGCCCTCTT[CG]TTGGGGTATCCCGCGATTATGCAAGATGAGGAAGAAGTAGAGAGCTCGGGGTAAGACATA', 'CAGATAACTCAATACTGTAATGCACCCTGTATTTAAGGCACTGGGCTTGCCCCATTAAAG[CG]CCATAAATTTGAAGGCCAATGATCGGTTTTCATGTAACGGGTGGTACTTCATACTGAAGT', 'GAACCGGCCCAGCTCGGAAACCGAGCAGGGCAAAACCCCAGTGCTGATCGTTAGTGGGAT[CG]CGCCTGTGAATAGCCACTGCCCTCCAGCCTGGGCAACAGCCAGACCCCGTCTGTTTAATA'], 'Next_Base': ['T', 'T', 'T', 'C', 'C'], 'Color_Channel': ['Red', 'Red', 'Red', 'Grn', 'Grn'], 'TSS_Coordinate': [28797310.0, 57718214.0, 15692819.0, 176737051.0, 148454441.0], 'Gene_Strand': ['+', '+', '-', '+', '+'], 'Gene_ID': ['GeneID:487', 'GeneID:7871', 'GeneID:4223', 'GeneID:3232', 'GeneID:57541'], 'Symbol': ['ATP2A1', 'SLMAP', 'MEOX2', 'HOXD3', 'ZNF398'], 'Synonym': ['ATP2A; SERCA1;', 'SLAP; KIAA1601;', 'GAX; MOX2;', 'HOX4; HOX1D; HOX4A; Hox-4.1; MGC10470;', 'P51; P71; ZER6; KIAA1339;'], 'Accession': ['NM_173201.2', 'NM_007159.2', 'NM_005924.3', 'NM_006898.4', 'NM_020781.2'], 'GID': ['GI:47132613', 'GI:56550042', 'GI:55956906', 'GI:23510372', 'GI:25777702'], 'Annotation': ['isoform a is encoded by transcript variant a; sarcoplasmic/endoplasmic reticulum calcium ATPase 1; calcium pump 1; SR Ca(2+)-ATPase 1; calcium-transporting ATPase sarcoplasmic reticulum type; fast twitch skeletal muscle isoform; endoplasmic reticulum class 1/2 Ca(2+) ATPase; go_component: membrane; go_component: integral to membrane; go_component: sarcoplasmic reticulum; go_component: smooth endoplasmic reticulum; go_function: ATP binding; go_function: hydrolase activity; go_function: nucleotide binding; go_function: calcium ion binding; go_function: magnesium ion binding; go_function: calcium-transporting ATPase activity; go_function: hydrolase activity; acting on acid anhydrides; catalyzing transmembrane movement of substances; go_process: metabolism; go_process: cation transport; go_process: proton transport; go_process: calcium ion transport; go_process: regulation of striated muscle contraction', 'Sarcolemmal-associated protein; go_component: integral to plasma membrane; go_component: smooth endoplasmic reticulum; go_function: unfolded protein binding; go_process: protein folding; go_process: muscle contraction', 'growth arrest-specific homeo box; go_component: nucleus; go_function: transcription factor activity; go_process: circulation; go_process: development; go_process: regulation of transcription; DNA-dependent', 'homeobox protein Hox-D3; Hox-4.1; mouse; homolog of; homeo box D3; go_component: nucleus; go_function: transcription factor activity; go_process: morphogenesis; go_process: regulation of transcription; DNA-dependent', 'isoform b is encoded by transcript variant 2; zinc finger DNA binding protein ZER6; zinc finger-estrogen receptor interaction; clone 6; zinc finger DNA binding protein p52/p71; go_component: nucleus; go_function: DNA binding; go_function: zinc ion binding; go_function: metal ion binding; go_function: transcriptional activator activity; go_process: transcription; go_process: regulation of transcription; DNA-dependent'], 'Product': ['ATPase; Ca++ transporting; fast twitch 1 isoform a', 'sarcolemma associated protein', 'mesenchyme homeo box 2', 'homeobox D3', 'zinc finger 398 isoform b'], 'Distance_to_TSS': [291.0, 369.0, 432.0, 268.0, 671.0], 'CPG_ISLAND': [True, True, True, False, True], 'CPG_ISLAND_LOCATIONS': ['16:28797486-28797825', '3:57716811-57718675', '7:15691512-15693551', nan, '7:148453584-148455804'], 'MIR_CPG_ISLAND': [nan, nan, nan, nan, nan], 'RANGE_GB': ['NC_000016.8', 'NC_000003.10', 'NC_000007.12', nan, 'NC_000007.12'], 'RANGE_START': [28797486.0, 57716811.0, 15691512.0, nan, 148453584.0], 'RANGE_END': [28797825.0, 57718675.0, 15693551.0, nan, 148455804.0], 'RANGE_STRAND': ['+', '+', '-', nan, '+'], 'GB_ACC': ['NM_173201.2', 'NM_007159.2', 'NM_005924.3', 'NM_006898.4', 'NM_020781.2'], 'ORF': [487.0, 7871.0, 4223.0, 3232.0, 57541.0]}\n", "\n", "Analyzing SPOT_ID.1 column for gene symbols:\n", "\n", "Gene data ID prefix: 100009676\n", "Column 'ID' contains values matching gene data ID pattern\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'Name' contains values matching gene data ID pattern\n", "Column 'IlmnStrand' contains values matching gene data ID pattern\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Checking for columns containing transcript or gene related terms:\n", "Column 'Name' may contain gene-related information\n", "Sample values: ['cg00000292', 'cg00002426', 'cg00003994']\n", "Column 'Gene_Strand' may contain gene-related information\n", "Sample values: ['+', '+', '-']\n", "Column 'Gene_ID' may contain gene-related information\n", "Sample values: ['GeneID:487', 'GeneID:7871', 'GeneID:4223']\n", "Column 'Symbol' may contain gene-related information\n", "Sample values: ['ATP2A1', 'SLMAP', 'MEOX2']\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. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n", "print(\"\\nGene annotation preview:\")\n", "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n", "print(preview_df(gene_annotation, n=5))\n", "\n", "# Check for gene information in the SPOT_ID.1 column which appears to contain gene names\n", "print(\"\\nAnalyzing SPOT_ID.1 column for gene symbols:\")\n", "if 'SPOT_ID.1' in gene_annotation.columns:\n", " # Extract a few sample values\n", " sample_values = gene_annotation['SPOT_ID.1'].head(3).tolist()\n", " for i, value in enumerate(sample_values):\n", " print(f\"Sample {i+1} excerpt: {value[:200]}...\") # Print first 200 chars\n", " # Test the extract_human_gene_symbols function on these values\n", " symbols = extract_human_gene_symbols(value)\n", " print(f\" Extracted gene symbols: {symbols}\")\n", "\n", "# Try to find the probe IDs in the gene annotation\n", "gene_data_id_prefix = gene_data.index[0].split('_')[0] # Get prefix of first gene ID\n", "print(f\"\\nGene data ID prefix: {gene_data_id_prefix}\")\n", "\n", "# Look for columns that might match the gene data IDs\n", "for col in gene_annotation.columns:\n", " if gene_annotation[col].astype(str).str.contains(gene_data_id_prefix).any():\n", " print(f\"Column '{col}' contains values matching gene data ID pattern\")\n", "\n", "# Check if there's any column that might contain transcript or gene IDs\n", "print(\"\\nChecking for columns containing transcript or gene related terms:\")\n", "for col in gene_annotation.columns:\n", " if any(term in col.upper() for term in ['GENE', 'TRANSCRIPT', 'SYMBOL', 'NAME', 'DESCRIPTION']):\n", " print(f\"Column '{col}' may contain gene-related information\")\n", " # Show sample values\n", " print(f\"Sample values: {gene_annotation[col].head(3).tolist()}\")\n" ] }, { "cell_type": "markdown", "id": "15b1500a", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "c5623eee", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:57.507487Z", "iopub.status.busy": "2025-03-25T03:55:57.507357Z", "iopub.status.idle": "2025-03-25T03:55:57.689457Z", "shell.execute_reply": "2025-03-25T03:55:57.688923Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping dataframe shape: (27551, 2)\n", "Gene mapping preview:\n", " ID Gene\n", "0 cg00000292 ATP2A1\n", "1 cg00002426 SLMAP\n", "2 cg00003994 MEOX2\n", "3 cg00005847 HOXD3\n", "4 cg00006414 ZNF398\n", "Transformed gene expression data shape: (0, 30)\n", "First few genes and samples:\n", "Empty DataFrame\n", "Columns: [GSM3398477, GSM3398478, GSM3398479, GSM3398480, GSM3398481]\n", "Index: []\n", "Number of genes after mapping: 0\n" ] } ], "source": [ "# 1. Identify the columns in gene_annotation for probe IDs and gene symbols\n", "# From the previous output, we can see:\n", "# - 'ID' column contains the probe identifiers (cg#####) that match the gene_data index\n", "# - 'Symbol' column contains the human gene symbols (ATP2A1, SLMAP, etc.)\n", "\n", "# 2. Get a gene mapping dataframe with the ID and Symbol columns\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n", "print(f\"Gene mapping dataframe shape: {gene_mapping.shape}\")\n", "print(\"Gene mapping preview:\")\n", "print(gene_mapping.head())\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene expression\n", "# Use the library function to handle the many-to-many relationship between probes and genes\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 genes and samples:\")\n", "print(gene_data.head(5).iloc[:, :5]) # Show first 5 genes and 5 samples\n", "\n", "# Check how many genes we have after mapping\n", "print(f\"Number of genes after mapping: {len(gene_data)}\")\n" ] }, { "cell_type": "markdown", "id": "8ab0839e", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "0a87e38c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:57.691130Z", "iopub.status.busy": "2025-03-25T03:55:57.691002Z", "iopub.status.idle": "2025-03-25T03:55:57.705047Z", "shell.execute_reply": "2025-03-25T03:55:57.704542Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape after normalization: (0, 30)\n", "Normalized gene expression data saved to ../../output/preprocess/Schizophrenia/gene_data/GSE120342.csv\n", "Selected clinical data shape: (1, 30)\n", "Clinical data preview:\n", " GSM3398477 GSM3398478 GSM3398479 GSM3398480 GSM3398481 \\\n", "Schizophrenia 0.0 0.0 0.0 0.0 0.0 \n", "\n", " GSM3398482 GSM3398483 GSM3398484 GSM3398485 GSM3398486 \\\n", "Schizophrenia 0.0 0.0 0.0 0.0 0.0 \n", "\n", " ... GSM3398497 GSM3398498 GSM3398499 GSM3398500 \\\n", "Schizophrenia ... NaN NaN NaN NaN \n", "\n", " GSM3398501 GSM3398502 GSM3398503 GSM3398504 GSM3398505 \\\n", "Schizophrenia NaN NaN NaN NaN NaN \n", "\n", " GSM3398506 \n", "Schizophrenia NaN \n", "\n", "[1 rows x 30 columns]\n", "Linked data shape: (30, 1)\n", "Linked data preview (first 5 rows, 5 columns):\n", " Schizophrenia\n", "GSM3398477 0.0\n", "GSM3398478 0.0\n", "GSM3398479 0.0\n", "GSM3398480 0.0\n", "GSM3398481 0.0\n", "Data shape after handling missing values: (0, 1)\n", "Quartiles for 'Schizophrenia':\n", " 25%: nan\n", " 50% (Median): nan\n", " 75%: nan\n", "Min: nan\n", "Max: nan\n", "The distribution of the feature 'Schizophrenia' in this dataset is fine.\n", "\n", "Data shape after removing biased features: (0, 1)\n", "Abnormality detected in the cohort: GSE120342. Preprocessing failed.\n", "Dataset is not usable for analysis. No linked data file saved.\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/media/techt/DATA/GenoAgent/tools/preprocess.py:400: FutureWarning: The behavior of DataFrame concatenation with empty or all-NA entries is deprecated. In a future version, this will no longer exclude empty or all-NA columns when determining the result dtypes. To retain the old behavior, exclude the relevant entries before the concat operation.\n", " linked_data = pd.concat([clinical_df, genetic_df], axis=0).T\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data - already done in previous step\n", "print(f\"Gene data shape after normalization: {gene_data.shape}\")\n", "\n", "# Save the normalized gene data to file - already done in previous step\n", "print(f\"Normalized gene expression data saved to {out_gene_data_file}\")\n", "\n", "# 2. Link the clinical and genetic data\n", "# Load the clinical features from the previous step\n", "selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", ")\n", "\n", "print(f\"Selected clinical data shape: {selected_clinical_df.shape}\")\n", "print(\"Clinical data preview:\")\n", "print(selected_clinical_df.head())\n", "\n", "# Link the clinical and genetic data directly using the properly encoded clinical 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])\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", "print(f\"Data shape after removing biased features: {linked_data.shape}\")\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 related to alcohol dependence but was evaluated for Schizophrenia.\"\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 }