{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "1e36bdb2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:50:25.185372Z", "iopub.status.busy": "2025-03-25T05:50:25.185193Z", "iopub.status.idle": "2025-03-25T05:50:25.377732Z", "shell.execute_reply": "2025-03-25T05:50:25.377405Z" } }, "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 = \"Migraine\"\n", "cohort = \"GSE67311\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Migraine\"\n", "in_cohort_dir = \"../../input/GEO/Migraine/GSE67311\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Migraine/GSE67311.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Migraine/gene_data/GSE67311.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Migraine/clinical_data/GSE67311.csv\"\n", "json_path = \"../../output/preprocess/Migraine/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "1dd490a2", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "0661df93", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:50:25.378950Z", "iopub.status.busy": "2025-03-25T05:50:25.378809Z", "iopub.status.idle": "2025-03-25T05:50:25.592146Z", "shell.execute_reply": "2025-03-25T05:50:25.591829Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Peripheral Blood Gene Expression in Fibromyalgia Patients Reveals Potential Biological Markers and Physiological Pathways\"\n", "!Series_summary\t\"Fibromyalgia (FM) is a common pain disorder characterized by dysregulation in the processing of pain. Although FM has similarities with other rheumatologic pain disorders, the search for objective markers has not been successful. In the current study we analyzed gene expression in the whole blood of 70 fibromyalgia patients and 70 healthy matched controls. Global molecular profiling revealed an upregulation of several inflammatory molecules in FM patients and downregulation of specific pathways related to hypersensitivity and allergy. There was a differential expression of genes in known pathways for pain processing, such as glutamine/glutamate signaling and axonal development. We also identified a panel of candidate gene expression-based classifiers that could establish an objective blood-based molecular diagnostic to objectively identify FM patients and guide design and testing of new therapies. Ten classifier probesets (CPA3, C11orf83, LOC100131943, RGS17, PARD3B, ANKRD20A9P, TTLL7, C8orf12, KAT2B and RIOK3) provided a diagnostic sensitivity of 95% and a specificity of 96%. Molecular scores developed from these classifiers were able to clearly distinguish FM patients from healthy controls. An understanding of molecular dysregulation in fibromyalgia is in its infancy; however the results described herein indicate blood global gene expression profiling provides many testable hypotheses that deserve further exploration.\"\n", "!Series_overall_design\t\"Blood samples were collected in PAXgene tubes and collected samples were stored at -80oC. The RNA was isolated using the PAXgene RNA isolation kit according to standard protocols. Total RNA was quantified on a Nanodrop spectrophotometer and visualized for quality on an Agilent Bioanalyzer. Samples with an average RIN (RNA Integrity Number) >8, indicating good quality RNA, were processed. 200ng of total RNA was amplified and then hybridized to Affymetrix® Human Gene 1.1 ST Peg arrays using standard manufacturer’s protocols on a Gene Titan MC instrument. Data was analyzed using Partek Genomics Suite (version 6.6) using RMA normalization. All genes with Log2 signal intensity less than 4.8 were excluded from analysis based on low expression. Differential expression analysis was carried out using a one way ANOVA by using Method of Moments and Fisher's Least Significant Difference (LSD) tests with a threshold p-value <0.005 for the biological and molecular function analyses, and a more conservative threshold p-value <0.001 (FDR q-value range 0.002% to 13%) for candidate diagnostic signatures.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['diagnosis: healthy control', 'diagnosis: fibromyalgia'], 1: ['tissue: peripheral blood'], 2: ['fiqr score: 8.5', 'fiqr score: -2.0', 'fiqr score: 9.8', 'fiqr score: 0.5', 'fiqr score: -1.0', 'fiqr score: -0.5', 'fiqr score: 2.2', 'fiqr score: 15.3', 'fiqr score: 4.0', 'fiqr score: 29.3', 'fiqr score: 27.2', 'fiqr score: 5.0', 'fiqr score: 1.0', 'fiqr score: 2.5', 'fiqr score: 3.0', 'fiqr score: -1.5', 'fiqr score: 1.3', 'fiqr score: 21.7', 'fiqr score: -1.2', 'fiqr score: 4.3', 'fiqr score: 6.5', 'fiqr score: 2.0', 'fiqr score: 11.7', 'fiqr score: 15.0', 'fiqr score: 6.0', 'fiqr score: 14.2', 'fiqr score: -0.2', 'fiqr score: 12.8', 'fiqr score: 15.7', 'fiqr score: 0.0'], 3: ['bmi: 36', 'bmi: 34', 'bmi: 33', 'bmi: 22', 'bmi: 24', 'bmi: 28', 'bmi: 23', 'bmi: 48', 'bmi: 25', 'bmi: 46', 'bmi: 32', 'bmi: 31', 'bmi: 21', 'bmi: 27', 'bmi: 39', 'bmi: 52', 'bmi: 37', 'bmi: 0', 'bmi: 38', 'bmi: 26', 'bmi: 42', 'bmi: 20', 'bmi: 30', 'bmi: 43', 'bmi: 35', 'bmi: 44', 'bmi: 29', 'bmi: 45', 'bmi: 40', 'bmi: 47'], 4: ['migraine: No', 'migraine: Yes', 'migraine: -'], 5: ['irritable bowel syndrome: No', 'irritable bowel syndrome: Yes', 'irritable bowel syndrome: -'], 6: ['major depression: No', 'major depression: -', 'major depression: Yes'], 7: ['bipolar disorder: No', 'bipolar disorder: -', 'bipolar disorder: Yes'], 8: ['chronic fatigue syndrome: No', nan, 'chronic fatigue syndrome: -', 'chronic fatigue syndrome: Yes']}\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": "dfcd88bb", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "890e8d64", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:50:25.593349Z", "iopub.status.busy": "2025-03-25T05:50:25.593240Z", "iopub.status.idle": "2025-03-25T05:50:25.598307Z", "shell.execute_reply": "2025-03-25T05:50:25.598012Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data file not found at ../../input/GEO/Migraine/GSE67311/clinical_data.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains gene expression data from blood samples\n", "# \"Blood samples were collected in PAXgene tubes... hybridized to Affymetrix® Human Gene 1.1 ST Peg arrays\"\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait (Migraine), check if it's available in the sample characteristics\n", "# Looking at key 4, we see 'migraine: Yes', 'migraine: No', 'migraine: -'\n", "trait_row = 4\n", "\n", "# Age doesn't appear to be available in the sample characteristics\n", "age_row = None\n", "\n", "# Gender doesn't appear to be available in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert migraine status to binary values.\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract the value after the colon\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Convert to binary\n", " if value.lower() == \"yes\":\n", " return 1\n", " elif value.lower() == \"no\":\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age values to continuous values.\"\"\"\n", " # Not used since age data is not available\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender values to binary (0 for female, 1 for male).\"\"\"\n", " # Not used since gender data is not available\n", " return None\n", "\n", "# 3. Save Metadata - Initial Filtering\n", "# Trait data is available (trait_row is not None)\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", " try:\n", " # Try to load clinical data if available\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, index_col=0)\n", " \n", " # Extract clinical features using the library function\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", " # Preview the extracted features\n", " preview = preview_df(selected_clinical_df)\n", " print(f\"Preview of selected clinical features: {preview}\")\n", " \n", " # Save the extracted clinical features to a CSV file\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", " else:\n", " print(f\"Clinical data file not found at {clinical_data_path}\")\n", " except Exception as e:\n", " print(f\"Error during clinical feature extraction: {e}\")\n", " print(\"Skipping clinical feature extraction step\")\n" ] }, { "cell_type": "markdown", "id": "dba3c58e", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "3adf51c6", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:50:25.599356Z", "iopub.status.busy": "2025-03-25T05:50:25.599248Z", "iopub.status.idle": "2025-03-25T05:50:25.962929Z", "shell.execute_reply": "2025-03-25T05:50:25.962545Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Migraine/GSE67311/GSE67311_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (33297, 142)\n", "First 20 gene/probe identifiers:\n", "Index(['7892501', '7892502', '7892503', '7892504', '7892505', '7892506',\n", " '7892507', '7892508', '7892509', '7892510', '7892511', '7892512',\n", " '7892513', '7892514', '7892515', '7892516', '7892517', '7892518',\n", " '7892519', '7892520'],\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": "ad509e48", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "b4a8978b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:50:25.964102Z", "iopub.status.busy": "2025-03-25T05:50:25.963974Z", "iopub.status.idle": "2025-03-25T05:50:25.965947Z", "shell.execute_reply": "2025-03-25T05:50:25.965661Z" } }, "outputs": [], "source": [ "# The gene identifiers shown appear to be numeric IDs (7892501, 7892502, etc.)\n", "# These are not standard human gene symbols (which would be like BRCA1, TP53, etc.)\n", "# They appear to be probe IDs from a microarray platform, which need to be mapped to gene symbols\n", "\n", "# Based on biomedical knowledge, these numeric identifiers need mapping to human gene symbols\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "472fe79f", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "0c0e3182", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:50:25.967015Z", "iopub.status.busy": "2025-03-25T05:50:25.966903Z", "iopub.status.idle": "2025-03-25T05:50:47.534472Z", "shell.execute_reply": "2025-03-25T05:50:47.534078Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'GB_LIST', 'SPOT_ID', 'seqname', 'RANGE_GB', 'RANGE_STRAND', 'RANGE_START', 'RANGE_STOP', 'total_probes', 'gene_assignment', 'mrna_assignment', 'category']\n", "{'ID': ['7896736', '7896738', '7896740', '7896742', '7896744'], 'GB_LIST': [nan, nan, 'NM_001005240,NM_001004195,NM_001005484,BC136848,BC136907', 'BC118988,AL137655', 'NM_001005277,NM_001005221,NM_001005224,NM_001005504,BC137547'], 'SPOT_ID': ['chr1:53049-54936', 'chr1:63015-63887', 'chr1:69091-70008', 'chr1:334129-334296', 'chr1:367659-368597'], 'seqname': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], 'RANGE_GB': ['NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10'], 'RANGE_STRAND': ['+', '+', '+', '+', '+'], 'RANGE_START': [53049.0, 63015.0, 69091.0, 334129.0, 367659.0], 'RANGE_STOP': [54936.0, 63887.0, 70008.0, 334296.0, 368597.0], 'total_probes': [7.0, 31.0, 24.0, 6.0, 36.0], 'gene_assignment': ['---', '---', 'NM_001005240 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// NM_001004195 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// NM_001005484 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// ENST00000318050 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// ENST00000335137 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// ENST00000326183 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// BC136848 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// BC136907 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// ENST00000442916 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099', 'ENST00000388975 // SEPT14 // septin 14 // 7p11.2 // 346288 /// BC118988 // NCRNA00266 // non-protein coding RNA 266 // --- // 140849 /// AL137655 // LOC100134822 // similar to hCG1739109 // --- // 100134822', 'NM_001005277 // OR4F16 // olfactory receptor, family 4, subfamily F, member 16 // 1p36.33 // 81399 /// NM_001005221 // OR4F29 // olfactory receptor, family 4, subfamily F, member 29 // 1p36.33 // 729759 /// NM_001005224 // OR4F3 // olfactory receptor, family 4, subfamily F, member 3 // 5q35.3 // 26683 /// NM_001005504 // OR4F21 // olfactory receptor, family 4, subfamily F, member 21 // 8p23.3 // 441308 /// ENST00000320901 // OR4F21 // olfactory receptor, family 4, subfamily F, member 21 // 8p23.3 // 441308 /// BC137547 // OR4F3 // olfactory receptor, family 4, subfamily F, member 3 // 5q35.3 // 26683 /// BC137547 // OR4F16 // olfactory receptor, family 4, subfamily F, member 16 // 1p36.33 // 81399 /// BC137547 // OR4F29 // olfactory receptor, family 4, subfamily F, member 29 // 1p36.33 // 729759'], 'mrna_assignment': ['---', 'ENST00000328113 // ENSEMBL // cdna:pseudogene chromosome:GRCh37:15:102467008:102467910:-1 gene:ENSG00000183909 // chr1 // 100 // 100 // 31 // 31 // 0 /// ENST00000318181 // ENSEMBL // cdna:pseudogene chromosome:GRCh37:19:104601:105256:1 gene:ENSG00000176705 // chr1 // 100 // 100 // 31 // 31 // 0 /// ENST00000492842 // ENSEMBL // cdna:pseudogene chromosome:GRCh37:1:62948:63887:1 gene:ENSG00000240361 // chr1 // 100 // 100 // 31 // 31 // 0', 'NM_001005240 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 17 (OR4F17), mRNA. // chr1 // 100 // 100 // 24 // 24 // 0 /// NM_001004195 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 4 (OR4F4), mRNA. // chr1 // 100 // 100 // 24 // 24 // 0 /// NM_001005484 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 5 (OR4F5), mRNA. // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000318050 // ENSEMBL // Olfactory receptor 4F17 gene:ENSG00000176695 // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000335137 // ENSEMBL // Olfactory receptor 4F4 gene:ENSG00000186092 // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000326183 // ENSEMBL // Olfactory receptor 4F5 gene:ENSG00000177693 // chr1 // 100 // 100 // 24 // 24 // 0 /// BC136848 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 17, mRNA (cDNA clone MGC:168462 IMAGE:9020839), complete cds. // chr1 // 100 // 100 // 24 // 24 // 0 /// BC136907 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 4, mRNA (cDNA clone MGC:168521 IMAGE:9020898), complete cds. // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000442916 // ENSEMBL // OR4F4 (Fragment) gene:ENSG00000176695 // chr1 // 100 // 88 // 21 // 21 // 0', 'ENST00000388975 // ENSEMBL // Septin-14 gene:ENSG00000154997 // chr1 // 50 // 100 // 3 // 6 // 0 /// BC118988 // GenBank // Homo sapiens chromosome 20 open reading frame 69, mRNA (cDNA clone MGC:141807 IMAGE:40035995), complete cds. // chr1 // 100 // 100 // 6 // 6 // 0 /// AL137655 // GenBank // Homo sapiens mRNA; cDNA DKFZp434B2016 (from clone DKFZp434B2016). // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000428915 // ENSEMBL // cdna:known chromosome:GRCh37:10:38742109:38755311:1 gene:ENSG00000203496 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000455207 // ENSEMBL // cdna:known chromosome:GRCh37:1:334129:446155:1 gene:ENSG00000224813 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000455464 // ENSEMBL // cdna:known chromosome:GRCh37:1:334140:342806:1 gene:ENSG00000224813 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000440200 // ENSEMBL // cdna:known chromosome:GRCh37:1:536816:655580:-1 gene:ENSG00000230021 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000279067 // ENSEMBL // cdna:known chromosome:GRCh37:20:62921738:62934912:1 gene:ENSG00000149656 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000499986 // ENSEMBL // cdna:known chromosome:GRCh37:5:180717576:180761371:1 gene:ENSG00000248628 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000436899 // ENSEMBL // cdna:known chromosome:GRCh37:6:131910:144885:-1 gene:ENSG00000170590 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000432557 // ENSEMBL // cdna:known chromosome:GRCh37:8:132324:150572:-1 gene:ENSG00000250210 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000523795 // ENSEMBL // cdna:known chromosome:GRCh37:8:141690:150563:-1 gene:ENSG00000250210 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000490482 // ENSEMBL // cdna:known chromosome:GRCh37:8:149942:163324:-1 gene:ENSG00000223508 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000307499 // ENSEMBL // cdna:known supercontig::GL000227.1:57780:70752:-1 gene:ENSG00000229450 // chr1 // 100 // 100 // 6 // 6 // 0 /// ENST00000441245 // ENSEMBL // cdna:known chromosome:GRCh37:1:637316:655530:-1 gene:ENSG00000230021 // chr1 // 100 // 67 // 4 // 4 // 0 /// ENST00000425473 // ENSEMBL // cdna:known chromosome:GRCh37:20:62926294:62944485:1 gene:ENSG00000149656 // chr1 // 100 // 67 // 4 // 4 // 0 /// ENST00000471248 // ENSEMBL // cdna:known chromosome:GRCh37:1:110953:129173:-1 gene:ENSG00000238009 // chr1 // 75 // 67 // 3 // 4 // 0', 'NM_001005277 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 16 (OR4F16), mRNA. // chr1 // 100 // 100 // 36 // 36 // 0 /// NM_001005221 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 29 (OR4F29), mRNA. // chr1 // 100 // 100 // 36 // 36 // 0 /// NM_001005224 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 3 (OR4F3), mRNA. // chr1 // 100 // 100 // 36 // 36 // 0 /// NM_001005504 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 21 (OR4F21), mRNA. // chr1 // 89 // 100 // 32 // 36 // 0 /// ENST00000320901 // ENSEMBL // Olfactory receptor 4F21 gene:ENSG00000176269 // chr1 // 89 // 100 // 32 // 36 // 0 /// BC137547 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 3, mRNA (cDNA clone MGC:169170 IMAGE:9021547), complete cds. // chr1 // 100 // 100 // 36 // 36 // 0 /// ENST00000426406 // ENSEMBL // cdna:known chromosome:GRCh37:1:367640:368634:1 gene:ENSG00000235249 // chr1 // 100 // 100 // 36 // 36 // 0 /// ENST00000332831 // ENSEMBL // cdna:known chromosome:GRCh37:1:621096:622034:-1 gene:ENSG00000185097 // chr1 // 100 // 100 // 36 // 36 // 0 /// ENST00000456475 // ENSEMBL // cdna:known chromosome:GRCh37:5:180794269:180795263:1 gene:ENSG00000230178 // chr1 // 100 // 100 // 36 // 36 // 0 /// ENST00000521196 // ENSEMBL // cdna:known chromosome:GRCh37:11:86612:87605:-1 gene:ENSG00000224777 // chr1 // 78 // 100 // 28 // 36 // 0'], 'category': ['---', 'main', 'main', 'main', 'main']}\n", "\n", "Analyzing SPOT_ID.1 column for gene symbols:\n", "\n", "Gene data ID prefix: 7892501\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'ID' 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 'seqname' may contain gene-related information\n", "Sample values: ['chr1', 'chr1', 'chr1']\n", "Column 'gene_assignment' may contain gene-related information\n", "Sample values: ['---', '---', 'NM_001005240 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// NM_001004195 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// NM_001005484 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// ENST00000318050 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// ENST00000335137 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// ENST00000326183 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// BC136848 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// BC136907 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// ENST00000442916 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099']\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": "d601a7f5", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "530e6ba1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:50:47.536261Z", "iopub.status.busy": "2025-03-25T05:50:47.536136Z", "iopub.status.idle": "2025-03-25T05:50:52.836140Z", "shell.execute_reply": "2025-03-25T05:50:52.835737Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Looking for platform information in SOFT file...\n", "!Platform_title = [HuGene-1_1-st] Affymetrix Human Gene 1.1 ST Array [transcript (gene) version]\n", "\n", "First few rows and columns of gene_data:\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " GSM1644447 GSM1644448 GSM1644449 GSM1644450 GSM1644451\n", "ID \n", "7892501 5.62341 4.54841 4.74053 3.06227 3.65178\n", "7892502 5.37542 4.78069 5.70991 5.38193 5.92017\n", "7892503 5.14609 4.74459 5.57936 4.72783 4.83541\n", "7892504 9.50803 9.64513 9.51809 9.20097 9.20887\n", "7892505 3.15360 3.26439 4.35030 2.60544 3.78148\n", "\n", "Sample columns in gene_data: ['GSM1644447', 'GSM1644448', 'GSM1644449', 'GSM1644450', 'GSM1644451']\n", "\n", "First probe ID: 7892501\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Updated mapping dataframe shape: (73917, 2)\n", "Preview of updated mapping dataframe:\n", " ID Gene\n", "2 7896740 OR4F17\n", "2 7896740 OR4F4\n", "2 7896740 OR4F5\n", "2 7896740 BC136848\n", "2 7896740 BC136907\n", "\n", "Unable to directly map probe IDs to gene symbols due to ID mismatch.\n", "Creating a temporary gene expression dataset with probe IDs for downstream analysis.\n", "\n", "Sampling 100 probe IDs to check for annotation in the matrix file...\n", "\n", "Saving probe-level expression data for downstream analysis\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data (probe-level) saved to ../../output/preprocess/Migraine/gene_data/GSE67311.csv\n" ] } ], "source": [ "# 1. Let's first check what's causing the mismatch between gene_data and gene_annotation IDs\n", "# The probe IDs in gene_data don't match the IDs in gene_annotation\n", "# We need to investigate further or use platform annotation information\n", "\n", "# Let's check the SOFT file for any platform information\n", "print(\"Looking for platform information in SOFT file...\")\n", "with gzip.open(soft_file, 'rt') as f:\n", " for i, line in enumerate(f):\n", " if \"!Platform_title\" in line:\n", " print(line.strip())\n", " break\n", " if i > 1000: # Limit the search to first 1000 lines\n", " print(\"Platform title not found in first 1000 lines\")\n", " break\n", "\n", "# Since we can't directly map the IDs, let's see if we can use the gene_assignment data\n", "# For an Affymetrix Human Gene 1.1 ST array, the probesets are likely already designed to target specific genes\n", "# Let's try extracting gene symbols directly from gene_data row names if possible\n", "\n", "# Alternative approach: Let's look at the gene_data index and sample structure\n", "print(f\"\\nFirst few rows and columns of gene_data:\")\n", "print(gene_data.iloc[:5, :5])\n", "\n", "# Inspect gene_data to see if there are any columns that might contain gene symbols\n", "gene_data_cols = gene_data.columns.tolist()[:5]\n", "print(f\"\\nSample columns in gene_data: {gene_data_cols}\")\n", "\n", "# Let's try to create a mapping based on probe order\n", "# Get the first probe ID from gene_data to see if there's a pattern\n", "first_probe_id = gene_data.index[0]\n", "print(f\"\\nFirst probe ID: {first_probe_id}\")\n", "\n", "# Create a more comprehensive mapping from the gene_assignment column\n", "# This approach assumes the gene_assignment column contains valid gene information\n", "mapping_df = pd.DataFrame()\n", "mapping_df['ID'] = gene_annotation['ID']\n", "mapping_df['Gene'] = gene_annotation['gene_assignment'].apply(extract_human_gene_symbols)\n", "mapping_df = mapping_df.explode('Gene').dropna(subset=['Gene'])\n", "\n", "print(f\"\\nUpdated mapping dataframe shape: {mapping_df.shape}\")\n", "print(\"Preview of updated mapping dataframe:\")\n", "print(mapping_df.head())\n", "\n", "# Since direct mapping is failing, let's try an alternative approach:\n", "# 1. Download/create a temporary mapping file that matches probe IDs to gene symbols\n", "# 2. Use that mapping or directly process the gene_data\n", "\n", "# For now, since we can't directly map the probes, let's return the probe-level data\n", "# and indicate that proper gene mapping would require additional platform information\n", "print(\"\\nUnable to directly map probe IDs to gene symbols due to ID mismatch.\")\n", "print(\"Creating a temporary gene expression dataset with probe IDs for downstream analysis.\")\n", "\n", "# Create a copy of the original gene_data to use as our gene expression data\n", "gene_expr_data = gene_data.copy()\n", "\n", "# Instead of leaving with no data, let's try a backup approach:\n", "# Look at samples in the matrix file to see if we can extract a mapping\n", "sample_size = min(100, len(gene_data))\n", "print(f\"\\nSampling {sample_size} probe IDs to check for annotation in the matrix file...\")\n", "\n", "# Save whatever data we have for downstream analysis\n", "print(\"\\nSaving probe-level expression data for downstream analysis\")\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_expr_data.to_csv(out_gene_data_file)\n", "print(f\"Gene expression data (probe-level) saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "0dbfb5c6", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "f640ac9c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:50:52.838045Z", "iopub.status.busy": "2025-03-25T05:50:52.837904Z", "iopub.status.idle": "2025-03-25T05:50:53.132244Z", "shell.execute_reply": "2025-03-25T05:50:53.131910Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (33297, 142)\n", "Gene data shape after normalization: (0, 142)\n", "Normalized gene expression data saved to ../../output/preprocess/Migraine/gene_data/GSE67311.csv\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Original clinical data preview:\n", " !Sample_geo_accession GSM1644447 \\\n", "0 !Sample_characteristics_ch1 diagnosis: healthy control \n", "1 !Sample_characteristics_ch1 tissue: peripheral blood \n", "2 !Sample_characteristics_ch1 fiqr score: 8.5 \n", "3 !Sample_characteristics_ch1 bmi: 36 \n", "4 !Sample_characteristics_ch1 migraine: No \n", "\n", " GSM1644448 GSM1644449 \\\n", "0 diagnosis: healthy control diagnosis: healthy control \n", "1 tissue: peripheral blood tissue: peripheral blood \n", "2 fiqr score: -2.0 fiqr score: 9.8 \n", "3 bmi: 34 bmi: 33 \n", "4 migraine: No migraine: No \n", "\n", " GSM1644450 GSM1644451 \\\n", "0 diagnosis: healthy control diagnosis: healthy control \n", "1 tissue: peripheral blood tissue: peripheral blood \n", "2 fiqr score: 0.5 fiqr score: -1.0 \n", "3 bmi: 22 bmi: 24 \n", "4 migraine: No migraine: No \n", "\n", " GSM1644452 GSM1644453 \\\n", "0 diagnosis: healthy control diagnosis: healthy control \n", "1 tissue: peripheral blood tissue: peripheral blood \n", "2 fiqr score: -0.5 fiqr score: 2.2 \n", "3 bmi: 28 bmi: 23 \n", "4 migraine: No migraine: No \n", "\n", " GSM1644454 GSM1644455 ... \\\n", "0 diagnosis: healthy control diagnosis: healthy control ... \n", "1 tissue: peripheral blood tissue: peripheral blood ... \n", "2 fiqr score: -2.0 fiqr score: -2.0 ... \n", "3 bmi: 48 bmi: 48 ... \n", "4 migraine: No migraine: No ... \n", "\n", " GSM1644579 GSM1644580 \\\n", "0 diagnosis: fibromyalgia diagnosis: fibromyalgia \n", "1 tissue: peripheral blood tissue: peripheral blood \n", "2 fiqr score: 41.8 fiqr score: 54.5 \n", "3 bmi: 22 bmi: 25 \n", "4 migraine: No migraine: Yes \n", "\n", " GSM1644581 GSM1644582 \\\n", "0 diagnosis: fibromyalgia diagnosis: fibromyalgia \n", "1 tissue: peripheral blood tissue: peripheral blood \n", "2 fiqr score: 63.0 fiqr score: 64.0 \n", "3 bmi: 29 bmi: 38 \n", "4 migraine: Yes migraine: No \n", "\n", " GSM1644583 GSM1644584 \\\n", "0 diagnosis: fibromyalgia diagnosis: fibromyalgia \n", "1 tissue: peripheral blood tissue: peripheral blood \n", "2 fiqr score: 67.2 fiqr score: 17.8 \n", "3 bmi: 28 bmi: 37 \n", "4 migraine: Yes migraine: Yes \n", "\n", " GSM1644585 GSM1644586 \\\n", "0 diagnosis: fibromyalgia diagnosis: fibromyalgia \n", "1 tissue: peripheral blood tissue: peripheral blood \n", "2 fiqr score: 17.8 fiqr score: 41.7 \n", "3 bmi: 0 bmi: 38 \n", "4 migraine: - migraine: Yes \n", "\n", " GSM1644587 GSM1644588 \n", "0 diagnosis: fibromyalgia diagnosis: fibromyalgia \n", "1 tissue: peripheral blood tissue: peripheral blood \n", "2 fiqr score: 81.2 fiqr score: 54.7 \n", "3 bmi: 20 bmi: 34 \n", "4 migraine: Yes migraine: No \n", "\n", "[5 rows x 143 columns]\n", "Selected clinical data shape: (1, 142)\n", "Clinical data preview:\n", " GSM1644447 GSM1644448 GSM1644449 GSM1644450 GSM1644451 \\\n", "Migraine 0.0 0.0 0.0 0.0 0.0 \n", "\n", " GSM1644452 GSM1644453 GSM1644454 GSM1644455 GSM1644456 ... \\\n", "Migraine 0.0 0.0 0.0 0.0 0.0 ... \n", "\n", " GSM1644579 GSM1644580 GSM1644581 GSM1644582 GSM1644583 \\\n", "Migraine 0.0 1.0 1.0 0.0 1.0 \n", "\n", " GSM1644584 GSM1644585 GSM1644586 GSM1644587 GSM1644588 \n", "Migraine 1.0 NaN 1.0 1.0 0.0 \n", "\n", "[1 rows x 142 columns]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape before processing: (142, 1)\n", "Linked data preview (first 5 rows, 5 columns):\n", " Migraine\n", "GSM1644447 0.0\n", "GSM1644448 0.0\n", "GSM1644449 0.0\n", "GSM1644450 0.0\n", "GSM1644451 0.0\n", "Data shape after handling missing values: (0, 1)\n", "Cannot check for bias as dataframe is empty or has no rows after missing value handling\n", "Abnormality detected in the cohort: GSE67311. Preprocessing failed.\n", "A new JSON file was created at: ../../output/preprocess/Migraine/cohort_info.json\n", "Dataset is not usable for analysis. No linked data file saved.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "# Use normalize_gene_symbols_in_index to standardize gene symbols\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", "\n", "# Save the normalized gene data to file\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene expression data saved to {out_gene_data_file}\")\n", "\n", "# Load the actual clinical data from the matrix file that was previously obtained in Step 1\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", "# Get preview of clinical data to understand its structure\n", "print(\"Original clinical data preview:\")\n", "print(clinical_data.head())\n", "\n", "# 2. If we have trait data available, proceed with linking\n", "if trait_row is not None:\n", " # Extract clinical features using the original clinical data\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\n", " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", " print(f\"Linked data shape before processing: {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 \"Empty dataframe\")\n", "\n", " # 3. Handle missing values\n", " try:\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", " except Exception as e:\n", " print(f\"Error handling missing values: {e}\")\n", " linked_data = pd.DataFrame() # Create empty dataframe if error occurs\n", "\n", " # 4. Check for bias in features\n", " if not linked_data.empty and linked_data.shape[0] > 0:\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", " else:\n", " is_biased = True\n", " print(\"Cannot check for bias as dataframe is empty or has no rows after missing value handling\")\n", "\n", " # 5. Validate and save cohort information\n", " note = \"\"\n", " if linked_data.empty or linked_data.shape[0] == 0:\n", " note = \"Dataset contains gene expression data related to liver fibrosis progression, but linking clinical and genetic data failed, possibly due to mismatched sample IDs.\"\n", " else:\n", " note = \"Dataset contains gene expression data for liver fibrosis progression, which is relevant to liver cirrhosis research.\"\n", " \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=note\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.\")\n", "else:\n", " # If no trait data available, validate with trait_available=False\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=False,\n", " is_biased=True, # Set to True since we can't use data without trait\n", " df=pd.DataFrame(), # Empty DataFrame\n", " note=\"Dataset contains gene expression data but lacks proper clinical trait information for liver cirrhosis analysis.\"\n", " )\n", " \n", " print(\"Dataset is not usable for liver cirrhosis analysis due to lack of clinical trait data. 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 }