{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "a78fb7a6", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:27:37.593176Z", "iopub.status.busy": "2025-03-25T08:27:37.593009Z", "iopub.status.idle": "2025-03-25T08:27:37.759491Z", "shell.execute_reply": "2025-03-25T08:27:37.759142Z" } }, "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 = \"Coronary_artery_disease\"\n", "cohort = \"GSE120774\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Coronary_artery_disease\"\n", "in_cohort_dir = \"../../input/GEO/Coronary_artery_disease/GSE120774\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Coronary_artery_disease/GSE120774.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Coronary_artery_disease/gene_data/GSE120774.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Coronary_artery_disease/clinical_data/GSE120774.csv\"\n", "json_path = \"../../output/preprocess/Coronary_artery_disease/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "dc882acd", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "edea0923", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:27:37.760987Z", "iopub.status.busy": "2025-03-25T08:27:37.760838Z", "iopub.status.idle": "2025-03-25T08:27:37.848713Z", "shell.execute_reply": "2025-03-25T08:27:37.848393Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Expression Data from epicardial (EAT) and subcutaneous adipose tissue (SAT) in patients with coronary artery disease\"\n", "!Series_summary\t\"We took samples of subcutaneous adipose tissue from the sternum (SAT) and epicardial adipose tissue (EAT) from a site adjacent to the right coronary artery in cases with coronary disease and controls without coronary disease.\"\n", "!Series_summary\t\"Cases had significant coronary disease and were undergoing coronary artery bypass surgery. Controls all had coronary angiograms and did not have significant coronary disease.\"\n", "!Series_overall_design\t\"Case control study\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: subcutaneous fat', 'tissue: epicardial fat'], 1: ['gender: M', 'gender: F'], 2: ['disease: None', 'disease: coronary disease']}\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": "24c5dedf", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "ac6adbf9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:27:37.849836Z", "iopub.status.busy": "2025-03-25T08:27:37.849725Z", "iopub.status.idle": "2025-03-25T08:27:37.858836Z", "shell.execute_reply": "2025-03-25T08:27:37.858539Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{'GSM3415000': [0.0, 1.0], 'GSM3415001': [0.0, 1.0], 'GSM3415002': [0.0, 1.0], 'GSM3415003': [0.0, 1.0], 'GSM3415004': [0.0, 0.0], 'GSM3415005': [0.0, 0.0], 'GSM3415006': [0.0, 1.0], 'GSM3415007': [0.0, 0.0], 'GSM3415008': [0.0, 0.0], 'GSM3415009': [1.0, 1.0], 'GSM3415010': [1.0, 1.0], 'GSM3415011': [1.0, 1.0], 'GSM3415012': [1.0, 0.0], 'GSM3415013': [1.0, 1.0], 'GSM3415014': [1.0, 0.0], 'GSM3415015': [1.0, 1.0], 'GSM3415016': [1.0, 0.0], 'GSM3415017': [0.0, 0.0], 'GSM3415018': [0.0, 1.0], 'GSM3415019': [0.0, 1.0], 'GSM3415020': [0.0, 0.0], 'GSM3415021': [0.0, 0.0], 'GSM3415022': [0.0, 0.0], 'GSM3415023': [0.0, 1.0], 'GSM3415024': [0.0, 1.0], 'GSM3415025': [0.0, 1.0], 'GSM3415026': [0.0, 0.0], 'GSM3415027': [1.0, 1.0], 'GSM3415028': [1.0, 1.0], 'GSM3415029': [1.0, 1.0], 'GSM3415030': [1.0, 1.0], 'GSM3415031': [1.0, 0.0], 'GSM3415032': [1.0, 0.0], 'GSM3415033': [1.0, 1.0], 'GSM3415034': [1.0, 1.0], 'GSM3415035': [1.0, 0.0]}\n", "Saved clinical data to ../../output/preprocess/Coronary_artery_disease/clinical_data/GSE120774.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# From the background information, this study collected tissue samples (EAT and SAT) from patients,\n", "# which suggests gene expression data is likely available.\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "\n", "# 2.1 Data Availability\n", "# Trait (Coronary artery disease) - available in row 2 with unique values \"disease: None\" and \"disease: coronary disease\"\n", "trait_row = 2\n", "\n", "# Gender - available in row 1 with unique values \"gender: M\" and \"gender: F\"\n", "gender_row = 1 \n", "\n", "# Age - not provided in the sample characteristics\n", "age_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert trait value to binary (0 for controls, 1 for cases)\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " value = value.lower()\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if \"none\" in value or \"control\" in value or \"without\" in value:\n", " return 0\n", " elif \"coronary disease\" in value or \"cad\" in value:\n", " return 1\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender value to binary (0 for female, 1 for male)\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " value = value.lower()\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if value == \"f\" or \"female\" in value:\n", " return 0\n", " elif value == \"m\" or \"male\" in value:\n", " return 1\n", " return None\n", "\n", "# Age conversion not needed as age data is not available\n", "convert_age = None\n", "\n", "# 3. Save Metadata\n", "# Check if trait data is available (trait_row is not None)\n", "is_trait_available = trait_row is not None\n", "\n", "# Initial filtering on usability and save information\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", "# Since trait_row is not None, we need to extract and save clinical features\n", "if is_trait_available:\n", " try:\n", " # Extract clinical features - using the clinical_data variable that should be \n", " # available from previous steps\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data, # Variable expected to be available from previous steps\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender,\n", " age_row=age_row,\n", " convert_age=convert_age\n", " )\n", " \n", " # Preview the dataframe\n", " print(\"Preview of selected clinical features:\")\n", " print(preview_df(selected_clinical_df))\n", " \n", " # Save the extracted clinical features\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Saved clinical data to {out_clinical_data_file}\")\n", " except Exception as e:\n", " print(f\"Error processing clinical data: {e}\")\n" ] }, { "cell_type": "markdown", "id": "07d93b24", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "08fa721a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:27:37.859759Z", "iopub.status.busy": "2025-03-25T08:27:37.859651Z", "iopub.status.idle": "2025-03-25T08:27:37.965689Z", "shell.execute_reply": "2025-03-25T08:27:37.965280Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SOFT file: ../../input/GEO/Coronary_artery_disease/GSE120774/GSE120774_family.soft.gz\n", "Matrix file: ../../input/GEO/Coronary_artery_disease/GSE120774/GSE120774_series_matrix.txt.gz\n", "Found the matrix table marker at line 63\n", "Gene data shape: (33297, 36)\n", "First 20 gene/probe identifiers:\n", "['7892501', '7892502', '7892503', '7892504', '7892505', '7892506', '7892507', '7892508', '7892509', '7892510', '7892511', '7892512', '7892513', '7892514', '7892515', '7892516', '7892517', '7892518', '7892519', '7892520']\n" ] } ], "source": [ "# 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", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# Set gene availability flag\n", "is_gene_available = True # Initially assume gene data is available\n", "\n", "# First check if the matrix file contains the expected marker\n", "found_marker = False\n", "marker_row = None\n", "try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " for i, line in enumerate(file):\n", " if \"!series_matrix_table_begin\" in line:\n", " found_marker = True\n", " marker_row = i\n", " print(f\"Found the matrix table marker at line {i}\")\n", " break\n", " \n", " if not found_marker:\n", " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n", " is_gene_available = False\n", " \n", " # If marker was found, try to extract gene data\n", " if is_gene_available:\n", " try:\n", " # Try using the library function\n", " gene_data = get_genetic_data(matrix_file)\n", " \n", " if gene_data.shape[0] == 0:\n", " print(\"Warning: Extracted gene data has 0 rows.\")\n", " is_gene_available = False\n", " else:\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " # Print the first 20 gene/probe identifiers\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20].tolist())\n", " except Exception as e:\n", " print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n", " is_gene_available = False\n", " \n", " # If gene data extraction failed, examine file content to diagnose\n", " if not is_gene_available:\n", " print(\"Examining file content to diagnose the issue:\")\n", " try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Print lines around the marker if found\n", " if marker_row is not None:\n", " for i, line in enumerate(file):\n", " if i >= marker_row - 2 and i <= marker_row + 10:\n", " print(f\"Line {i}: {line.strip()[:100]}...\")\n", " if i > marker_row + 10:\n", " break\n", " else:\n", " # If marker not found, print first 10 lines\n", " for i, line in enumerate(file):\n", " if i < 10:\n", " print(f\"Line {i}: {line.strip()[:100]}...\")\n", " else:\n", " break\n", " except Exception as e2:\n", " print(f\"Error examining file: {e2}\")\n", " \n", "except Exception as e:\n", " print(f\"Error processing file: {e}\")\n", " is_gene_available = False\n", "\n", "# Update validation information if gene data extraction failed\n", "if not is_gene_available:\n", " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n", " # Update the validation record since gene data isn't available\n", " is_trait_available = False # We already determined trait data isn't available in step 2\n", " validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n", " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n" ] }, { "cell_type": "markdown", "id": "cfc8664b", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "d889df67", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:27:37.967026Z", "iopub.status.busy": "2025-03-25T08:27:37.966905Z", "iopub.status.idle": "2025-03-25T08:27:37.968856Z", "shell.execute_reply": "2025-03-25T08:27:37.968564Z" } }, "outputs": [], "source": [ "# The gene identifiers appear to be probe IDs (numeric identifiers) rather than human gene symbols\n", "# These are likely microarray probe IDs which need to be mapped to gene symbols\n", "\n", "# Based on the format (7-digit numeric IDs), these appear to be Affymetrix or Illumina microarray probe IDs\n", "# They need to be mapped to official gene symbols for meaningful biological interpretation\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "dd8d7133", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "afdc1303", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:27:37.970044Z", "iopub.status.busy": "2025-03-25T08:27:37.969931Z", "iopub.status.idle": "2025-03-25T08:27:40.649451Z", "shell.execute_reply": "2025-03-25T08:27:40.649014Z" } }, "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'], 'GB_LIST': [nan, nan, 'NM_001004195,NM_001005240,NM_001005484,BC136848,BC136867,BC136907,BC136908'], 'SPOT_ID': ['chr1:53049-54936', 'chr1:63015-63887', 'chr1:69091-70008'], 'seqname': ['chr1', 'chr1', 'chr1'], 'RANGE_GB': ['NC_000001.10', 'NC_000001.10', 'NC_000001.10'], 'RANGE_STRAND': ['+', '+', '+'], 'RANGE_START': ['53049', '63015', '69091'], 'RANGE_STOP': ['54936', '63887', '70008'], 'total_probes': [7.0, 31.0, 24.0], 'gene_assignment': ['---', 'ENST00000328113 // OR4G2P // olfactory receptor, family 4, subfamily G, member 2 pseudogene // --- // --- /// ENST00000492842 // OR4G11P // olfactory receptor, family 4, subfamily G, member 11 pseudogene // --- // --- /// ENST00000588632 // OR4G1P // olfactory receptor, family 4, subfamily G, member 1 pseudogene // --- // ---', 'NM_001004195 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// NM_001005240 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// 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 /// ENST00000326183 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// ENST00000335137 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// ENST00000585993 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// BC136848 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 /// BC136867 // 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 /// BC136908 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682'], 'mrna_assignment': ['NONHSAT060105 // NONCODE // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 7 // 7 // 0', 'ENST00000328113 // ENSEMBL // havana:known chromosome:GRCh38:15:101926805:101927707:-1 gene:ENSG00000183909 gene_biotype:unprocessed_pseudogene transcript_biotype:unprocessed_pseudogene // chr1 // 100 // 100 // 31 // 31 // 0 /// ENST00000492842 // ENSEMBL // havana:known chromosome:GRCh38:1:62948:63887:1 gene:ENSG00000240361 gene_biotype:unprocessed_pseudogene transcript_biotype:unprocessed_pseudogene // chr1 // 100 // 100 // 31 // 31 // 0 /// ENST00000588632 // ENSEMBL // havana:known chromosome:GRCh38:19:104535:105471:1 gene:ENSG00000267310 gene_biotype:unprocessed_pseudogene transcript_biotype:unprocessed_pseudogene // chr1 // 100 // 100 // 31 // 31 // 0 /// NONHSAT000016 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 31 // 31 // 0 /// NONHSAT051704 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 31 // 31 // 0 /// NONHSAT060106 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 31 // 31 // 0', 'NM_001004195 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 4 (OR4F4), mRNA. // chr1 // 100 // 100 // 24 // 24 // 0 /// NM_001005240 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 17 (OR4F17), 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 // ensembl:known chromosome:GRCh38:19:110643:111696:1 gene:ENSG00000176695 gene_biotype:protein_coding transcript_biotype:protein_coding // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000326183 // ENSEMBL // ensembl_havana_transcript:known chromosome:GRCh38:15:101922042:101923095:-1 gene:ENSG00000177693 gene_biotype:protein_coding transcript_biotype:protein_coding // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000335137 // ENSEMBL // ensembl_havana_transcript:known chromosome:GRCh38:1:69091:70008:1 gene:ENSG00000186092 gene_biotype:protein_coding transcript_biotype:protein_coding // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000585993 // ENSEMBL // havana:known chromosome:GRCh38:19:107461:111696:1 gene:ENSG00000176695 gene_biotype:protein_coding transcript_biotype:protein_coding // 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 /// BC136867 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 17, mRNA (cDNA clone MGC:168481 IMAGE:9020858), 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 /// BC136908 // GenBank // Homo sapiens olfactory receptor, family 4, subfamily F, member 4, mRNA (cDNA clone MGC:168522 IMAGE:9020899), complete cds. // chr1 // 100 // 100 // 24 // 24 // 0 /// ENST00000618231 // ENSEMBL // havana:known chromosome:GRCh38:19:110613:111417:1 gene:ENSG00000176695 gene_biotype:protein_coding transcript_biotype:retained_intron // chr1 // 100 // 88 // 21 // 21 // 0'], 'category': ['main', 'main', 'main']}\n", "\n", "Examining 'gene_assignment' column examples:\n", "Example 1: ---\n", "Example 2: ENST00000328113 // OR4G2P // olfactory receptor, family 4, subfamily G, member 2 pseudogene // --- // --- /// ENST00000492842 // OR4G11P // olfactory receptor, family 4, subfamily G, member 11 pseudog...\n", "Example 3: NM_001004195 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 /// NM_001005240 // OR4F17 // olfactory receptor, family 4, subfamily F, member 17 // 19p13.3 // 81099 ...\n", "Example 4: NR_024437 // LOC728323 // uncharacterized LOC728323 // 2q37.3 // 728323 /// XM_006711854 // LOC101060626 // F-box only protein 25-like // --- // 101060626 /// XM_006726377 // LOC101060626 // F-box onl...\n", "Example 5: 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 ...\n", "\n", "Gene assignment column completeness: 33297/1232025 rows (2.70%)\n", "Probes without gene assignments: 8004/1232025 rows (0.65%)\n", "\n", "Columns identified for gene mapping:\n", "- 'ID': Contains probe IDs (e.g., 7896736)\n", "- 'gene_assignment': Contains gene information that needs parsing to extract gene symbols\n" ] } ], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\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=3))\n", "\n", "# Examining the gene_assignment column which appears to contain gene symbol information\n", "print(\"\\nExamining 'gene_assignment' column examples:\")\n", "if 'gene_assignment' in gene_annotation.columns:\n", " # Display a few examples of the gene_assignment column to understand its format\n", " gene_samples = gene_annotation['gene_assignment'].head(5).tolist()\n", " for i, sample in enumerate(gene_samples):\n", " print(f\"Example {i+1}: {sample[:200]}...\" if isinstance(sample, str) and len(sample) > 200 else f\"Example {i+1}: {sample}\")\n", " \n", " # Check the quality and completeness of the gene_assignment column\n", " non_null_assignments = gene_annotation['gene_assignment'].notna().sum()\n", " total_rows = len(gene_annotation)\n", " print(f\"\\nGene assignment column completeness: {non_null_assignments}/{total_rows} rows ({non_null_assignments/total_rows:.2%})\")\n", " \n", " # Check for probe IDs without gene assignments (typically '---' entries)\n", " missing_assignments = gene_annotation[gene_annotation['gene_assignment'] == '---'].shape[0]\n", " print(f\"Probes without gene assignments: {missing_assignments}/{total_rows} rows ({missing_assignments/total_rows:.2%})\")\n", " \n", " # Identify the columns needed for gene mapping\n", " print(\"\\nColumns identified for gene mapping:\")\n", " print(\"- 'ID': Contains probe IDs (e.g., 7896736)\")\n", " print(\"- 'gene_assignment': Contains gene information that needs parsing to extract gene symbols\")\n", "else:\n", " print(\"Error: 'gene_assignment' column not found in annotation data.\")\n", " print(\"Available columns:\", gene_annotation.columns.tolist())\n" ] }, { "cell_type": "markdown", "id": "b468200e", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "8bb23d73", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:27:40.651152Z", "iopub.status.busy": "2025-03-25T08:27:40.650983Z", "iopub.status.idle": "2025-03-25T08:27:46.284833Z", "shell.execute_reply": "2025-03-25T08:27:46.284429Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Example gene symbol extractions:\n", "Example 1:\n", "Original: ---\n", "Extracted symbols: []\n", "Example 2:\n", "Original: ENST00000328113 // OR4G2P // olfactory receptor, family 4, subfamily G, member 2 pseudogene // --- /...\n", "Extracted symbols: ['OR4G1P', 'OR4G2P', 'OR4G11P']\n", "Example 3:\n", "Original: NM_001004195 // OR4F4 // olfactory receptor, family 4, subfamily F, member 4 // 15q26.3 // 26682 ///...\n", "Extracted symbols: ['OR4F4', 'OR4F5', 'OR4F17']\n", "Example 4:\n", "Original: NR_024437 // LOC728323 // uncharacterized LOC728323 // 2q37.3 // 728323 /// XM_006711854 // LOC10106...\n", "Extracted symbols: ['PCMTD2', 'SEPT14']\n", "Example 5:\n", "Original: NM_001005221 // OR4F29 // olfactory receptor, family 4, subfamily F, member 29 // 1p36.33 // 729759 ...\n", "Extracted symbols: ['OR4F28P', 'OR4F16', 'OR4F29', 'OR4F8P', 'OR4F7P', 'OR4F3', 'OR4F2P', 'OR4F1P', 'OR4F21']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Total probes with valid gene symbols: 24707\n", "\n", "Gene mapping information:\n", "Total probes in expression data: 33297\n", "Probes with gene mappings: 24707\n", "Unique genes after mapping: 0\n", "\n", "WARNING: Standard mapping produced 0 genes. Attempting alternate approach...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Simplified mapping produced 25127 probe-to-gene mappings\n", "Simplified mapping produced 23139 genes\n", "After normalization: 22343 genes\n", "\n", "Preview of gene expression data:\n", "{'GSM3415000': [6.95774, 5.6657, 12.0967, 5.64055, 5.23009], 'GSM3415001': [7.61407, 5.90698, 11.7109, 6.19953, 5.92731], 'GSM3415002': [7.21409, 5.6717, 11.87, 6.11775, 5.49881], 'GSM3415003': [7.19709, 5.75878, 11.8535, 5.93999, 5.77457], 'GSM3415004': [7.12083, 5.69981, 11.9852, 5.85591, 5.55674], 'GSM3415005': [7.30062, 5.77384, 11.8517, 5.67189, 5.69931], 'GSM3415006': [7.21898, 6.0316, 11.7973, 5.74427, 5.64976], 'GSM3415007': [6.90321, 5.56953, 11.4465, 5.69886, 5.55623], 'GSM3415008': [7.16062, 5.81981, 11.7353, 5.72275, 5.76073], 'GSM3415009': [7.15482, 5.74577, 11.8572, 5.71592, 5.62793], 'GSM3415010': [7.17004, 5.74897, 11.6864, 5.74791, 6.06825], 'GSM3415011': [7.26014, 5.73882, 11.7929, 5.69294, 5.59686], 'GSM3415012': [7.21029, 5.66763, 11.8685, 5.52236, 5.54461], 'GSM3415013': [7.03885, 5.43717, 11.9798, 5.58275, 5.81155], 'GSM3415014': [7.04218, 5.9481, 11.8107, 5.75532, 5.51786], 'GSM3415015': [6.91789, 5.54417, 11.8627, 5.47699, 5.70513], 'GSM3415016': [6.87814, 5.41642, 12.0208, 5.3062, 5.67245], 'GSM3415017': [7.2027, 5.82422, 11.9105, 6.02527, 5.75729], 'GSM3415018': [7.08367, 5.43742, 11.92, 5.47316, 5.70813], 'GSM3415019': [7.02314, 5.70738, 11.9368, 5.46817, 5.51984], 'GSM3415020': [7.31375, 5.83101, 11.8874, 5.95709, 5.77285], 'GSM3415021': [7.30992, 5.87096, 11.8168, 5.86899, 5.97262], 'GSM3415022': [7.48221, 6.31212, 11.2937, 6.05602, 5.72127], 'GSM3415023': [7.50397, 6.44974, 10.7588, 5.95392, 5.92881], 'GSM3415024': [7.19449, 5.89398, 11.6325, 5.78308, 5.57504], 'GSM3415025': [6.83583, 5.4434, 11.9428, 5.34154, 5.53078], 'GSM3415026': [6.98818, 5.71285, 11.8723, 5.73145, 5.69724], 'GSM3415027': [7.09204, 5.59079, 11.9521, 5.79614, 5.4907], 'GSM3415028': [7.38096, 5.61466, 11.8476, 5.60134, 5.58501], 'GSM3415029': [7.12859, 5.47982, 12.1107, 5.68366, 5.8375], 'GSM3415030': [7.13538, 5.59825, 11.912, 5.64041, 5.93221], 'GSM3415031': [7.06929, 5.63018, 11.8708, 5.67231, 5.64413], 'GSM3415032': [7.04818, 5.67969, 11.8481, 5.62486, 5.52272], 'GSM3415033': [7.12, 5.38563, 11.9914, 5.56929, 6.03025], 'GSM3415034': [6.93669, 5.28715, 11.7417, 5.52987, 5.66853], 'GSM3415035': [6.97924, 5.27288, 11.971, 5.30301, 5.81562]}\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Saved gene expression data to ../../output/preprocess/Coronary_artery_disease/gene_data/GSE120774.csv\n" ] } ], "source": [ "# 1. From the output of previous steps, we need to map the numeric probe IDs to gene symbols\n", "# The gene annotation contains 'ID' column with probe IDs and 'gene_assignment' column with gene symbols and other info\n", "\n", "# Load gene annotation and expression data\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "gene_annotation = get_gene_annotation(soft_file)\n", "gene_data_raw = get_genetic_data(matrix_file)\n", "\n", "# 2. Extract and process the mapping between probe IDs and gene symbols \n", "# Create a custom function to extract gene symbols from the gene_assignment string\n", "def extract_gene_symbols_from_assignment(assignment_str):\n", " if not isinstance(assignment_str, str) or assignment_str == '---':\n", " return []\n", " \n", " # The format appears to be: RefSeq_ID // GENE_SYMBOL // description // location // ID\n", " # Multiple genes are separated by ///\n", " gene_symbols = []\n", " gene_entries = assignment_str.split('///')\n", " \n", " for entry in gene_entries:\n", " parts = entry.strip().split('//')\n", " if len(parts) >= 2:\n", " gene_symbol = parts[1].strip()\n", " # Some entries might have multiple symbols or additional info\n", " if gene_symbol and gene_symbol != '---':\n", " # Get the actual gene symbol without additional text\n", " # The gene symbols appear to be standard symbols like OR4F4\n", " symbols = extract_human_gene_symbols(gene_symbol)\n", " gene_symbols.extend(symbols)\n", " \n", " return list(set(gene_symbols)) # Remove duplicates\n", "\n", "# Apply the function to create a mapping dataframe\n", "gene_annotation['Gene'] = gene_annotation['gene_assignment'].apply(extract_gene_symbols_from_assignment)\n", "\n", "# Print some examples to verify extraction\n", "print(\"Example gene symbol extractions:\")\n", "for i, (assignment, symbols) in enumerate(zip(gene_annotation['gene_assignment'].head(5), gene_annotation['Gene'].head(5))):\n", " print(f\"Example {i+1}:\")\n", " print(f\"Original: {assignment[:100]}...\" if isinstance(assignment, str) and len(str(assignment)) > 100 else f\"Original: {assignment}\")\n", " print(f\"Extracted symbols: {symbols}\")\n", "\n", "# Create mapping dataframe\n", "mapping_df = gene_annotation[['ID', 'Gene']].copy()\n", "\n", "# Keep only entries with at least one gene symbol\n", "mapping_df = mapping_df[mapping_df['Gene'].apply(len) > 0]\n", "print(f\"\\nTotal probes with valid gene symbols: {len(mapping_df)}\")\n", "\n", "# 3. Convert probe-level measurements to gene expression using apply_gene_mapping\n", "# Instead of directly calling the function, we'll manually do the steps to debug\n", "try:\n", " # Apply the mapping\n", " gene_data = apply_gene_mapping(gene_data_raw, mapping_df)\n", " \n", " # Print mapping statistics\n", " print(\"\\nGene mapping information:\")\n", " print(f\"Total probes in expression data: {gene_data_raw.shape[0]}\")\n", " print(f\"Probes with gene mappings: {len(mapping_df)}\")\n", " print(f\"Unique genes after mapping: {gene_data.shape[0]}\")\n", " \n", " # If mapping still fails, try a direct approach for urgent debugging\n", " if gene_data.shape[0] == 0:\n", " print(\"\\nWARNING: Standard mapping produced 0 genes. Attempting alternate approach...\")\n", " \n", " # Fallback approach: Create a simpler mapping using only unique first symbols\n", " simplified_mapping = gene_annotation[['ID']].copy()\n", " simplified_mapping['Gene'] = gene_annotation['gene_assignment'].apply(\n", " lambda x: extract_human_gene_symbols(str(x))[0] if isinstance(x, str) and len(extract_human_gene_symbols(str(x))) > 0 else None\n", " )\n", " simplified_mapping = simplified_mapping.dropna()\n", " print(f\"Simplified mapping produced {len(simplified_mapping)} probe-to-gene mappings\")\n", " \n", " # Apply simplified mapping\n", " gene_data = apply_gene_mapping(gene_data_raw, simplified_mapping)\n", " print(f\"Simplified mapping produced {gene_data.shape[0]} genes\")\n", " \n", " # Normalize gene symbols to ensure consistency\n", " gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"After normalization: {gene_data.shape[0]} genes\")\n", " \n", " # Preview the final gene expression data\n", " print(\"\\nPreview of gene expression data:\")\n", " print(preview_df(gene_data, n=5))\n", " \n", " # Save the processed gene expression data\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\"\\nSaved gene expression data to {out_gene_data_file}\")\n", " \n", "except Exception as e:\n", " print(f\"Error during gene mapping: {e}\")\n", " \n", " # If an error occurs, try a minimal approach to extract at least some data\n", " print(\"\\nAttempting minimal approach to extract gene data...\")\n", " \n", " # Create a direct mapping using a more lenient approach\n", " direct_mapping = []\n", " for idx, row in gene_annotation.iterrows():\n", " gene_id = row['ID']\n", " if isinstance(row['gene_assignment'], str):\n", " # Extract gene symbols using regex\n", " genes = re.findall(r'//\\s+([A-Z0-9]+)\\s+//', row['gene_assignment'])\n", " if genes:\n", " for gene in genes:\n", " direct_mapping.append({'ID': gene_id, 'Gene': gene})\n", " \n", " if direct_mapping:\n", " direct_mapping_df = pd.DataFrame(direct_mapping)\n", " \n", " # Apply direct mapping\n", " gene_data = apply_gene_mapping(gene_data_raw, direct_mapping_df)\n", " \n", " # Normalize and save\n", " gene_data = normalize_gene_symbols_in_index(gene_data)\n", " gene_data.to_csv(out_gene_data_file)\n", " print(f\"Minimal approach produced {gene_data.shape[0]} genes\")\n", " print(f\"Saved gene expression data to {out_gene_data_file}\")\n", " else:\n", " print(\"Failed to extract gene data with all approaches. Cannot proceed with gene mapping.\")\n" ] }, { "cell_type": "markdown", "id": "885f3f41", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "f014c57c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:27:46.286277Z", "iopub.status.busy": "2025-03-25T08:27:46.286146Z", "iopub.status.idle": "2025-03-25T08:27:56.452190Z", "shell.execute_reply": "2025-03-25T08:27:56.451783Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Debug - trait variable: Coronary_artery_disease (type: )\n", "Gene data shape before normalization: (22343, 36)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data saved to ../../output/preprocess/Coronary_artery_disease/gene_data/GSE120774.csv\n", "Loaded clinical data shape: (2, 36)\n", "Clinical data columns: ['GSM3415000', 'GSM3415001', 'GSM3415002', 'GSM3415003', 'GSM3415004', 'GSM3415005', 'GSM3415006', 'GSM3415007', 'GSM3415008', 'GSM3415009', 'GSM3415010', 'GSM3415011', 'GSM3415012', 'GSM3415013', 'GSM3415014', 'GSM3415015', 'GSM3415016', 'GSM3415017', 'GSM3415018', 'GSM3415019', 'GSM3415020', 'GSM3415021', 'GSM3415022', 'GSM3415023', 'GSM3415024', 'GSM3415025', 'GSM3415026', 'GSM3415027', 'GSM3415028', 'GSM3415029', 'GSM3415030', 'GSM3415031', 'GSM3415032', 'GSM3415033', 'GSM3415034', 'GSM3415035']\n", "Initial linked data shape: (36, 22345)\n", "Linked data columns: [0, 1, 'A1BG', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAAS']...\n", "Using trait column name: 0\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape after handling missing values: (36, 22345)\n", "For the feature '0', the least common label is '1.0' with 17 occurrences. This represents 47.22% of the dataset.\n", "The distribution of the feature '0' in this dataset is fine.\n", "\n", "A new JSON file was created at: ../../output/preprocess/Coronary_artery_disease/cohort_info.json\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Coronary_artery_disease/GSE120774.csv\n" ] } ], "source": [ "# 1. Attempt to load gene data and handle possible issues with normalization\n", "try:\n", " # Create output directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " \n", " # Debug the trait variable and data structure\n", " print(f\"Debug - trait variable: {trait} (type: {type(trait)})\")\n", " \n", " # Check if gene_data (from previous step) has any content\n", " if 'gene_data' not in locals() or gene_data.shape[0] == 0:\n", " print(\"WARNING: Gene data is empty after normalization in previous step.\")\n", " print(\"This appears to be miRNA data rather than gene expression data.\")\n", " \n", " # Since gene_data is empty, set gene_available to False\n", " is_gene_available = False\n", " \n", " # Create an empty dataframe for metadata purposes\n", " empty_df = pd.DataFrame()\n", " \n", " # Log information about this dataset for future reference\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=True, # Based on previous steps\n", " is_biased=True, # Consider it biased as we can't use it\n", " df=empty_df,\n", " note=\"Dataset appears to contain miRNA data rather than gene expression data. Gene symbols could not be normalized.\"\n", " )\n", " \n", " print(\"Dataset marked as unusable due to lack of valid gene expression data.\")\n", " else:\n", " # If gene_data is not empty, proceed with normalization and linking\n", " print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", " \n", " # Save the gene data we have, even if it's already normalized\n", " gene_data.to_csv(out_gene_data_file)\n", " print(f\"Gene data saved to {out_gene_data_file}\")\n", " \n", " # Attempt to link clinical and gene data\n", " try:\n", " # Load clinical data\n", " clinical_features = pd.read_csv(out_clinical_data_file)\n", " print(f\"Loaded clinical data shape: {clinical_features.shape}\")\n", " print(f\"Clinical data columns: {clinical_features.columns.tolist()}\")\n", " \n", " # Set the index for clinical features if needed\n", " if 'Unnamed: 0' in clinical_features.columns:\n", " clinical_features = clinical_features.set_index('Unnamed: 0')\n", " \n", " # Link the clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n", " print(f\"Initial linked data shape: {linked_data.shape}\")\n", " print(f\"Linked data columns: {linked_data.columns[:10].tolist()}...\") # Show first 10 columns\n", " \n", " # Check which columns are available for trait\n", " if trait in linked_data.columns:\n", " trait_column = trait\n", " else:\n", " # Since clinical data only has 2 rows, and one is likely Gender, the other is the trait\n", " # Find column that's not Gender\n", " possible_trait_columns = [col for col in linked_data.columns if col != 'Gender']\n", " trait_column = possible_trait_columns[0] if possible_trait_columns else linked_data.columns[0]\n", " \n", " print(f\"Using trait column name: {trait_column}\")\n", " \n", " # Handle missing values\n", " linked_data = handle_missing_values(linked_data, trait_column)\n", " print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n", " \n", " if linked_data.shape[0] > 0:\n", " # Check for bias in trait and demographic features\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait_column)\n", " \n", " # Validate data quality and save cohort info\n", " is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=True,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=\"Successfully processed gene expression data for coronary artery disease.\"\n", " )\n", " \n", " # Save the linked data if it's 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(\"Data not usable for trait study - not saving final linked data.\")\n", " else:\n", " print(\"After handling missing values, no samples remain.\")\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=True,\n", " is_biased=True,\n", " df=pd.DataFrame(),\n", " note=\"No valid samples after handling missing values.\"\n", " )\n", " except Exception as inner_e:\n", " print(f\"Error in linking or processing data: {inner_e}\")\n", " import traceback\n", " traceback.print_exc()\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=True,\n", " is_biased=True,\n", " df=pd.DataFrame(),\n", " note=f\"Error during linking or processing: {str(inner_e)}\"\n", " )\n", "except Exception as e:\n", " print(f\"Error in data processing: {e}\")\n", " import traceback\n", " traceback.print_exc()\n", " \n", " # Log the error and mark the dataset as unusable\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=False, # Consider gene data unavailable if we had an error\n", " is_trait_available=True, # Based on previous steps\n", " is_biased=True, # Consider it biased as we can't use it\n", " df=pd.DataFrame(), # Empty dataframe for metadata\n", " note=f\"Error during normalization or linking: {str(e)}\"\n", " )" ] } ], "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 }