{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "ae0392e9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:29:43.226721Z", "iopub.status.busy": "2025-03-25T08:29:43.226589Z", "iopub.status.idle": "2025-03-25T08:29:43.395364Z", "shell.execute_reply": "2025-03-25T08:29:43.395008Z" } }, "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 = \"GSE64554\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Coronary_artery_disease\"\n", "in_cohort_dir = \"../../input/GEO/Coronary_artery_disease/GSE64554\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Coronary_artery_disease/GSE64554.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Coronary_artery_disease/gene_data/GSE64554.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Coronary_artery_disease/clinical_data/GSE64554.csv\"\n", "json_path = \"../../output/preprocess/Coronary_artery_disease/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "f02e2f52", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "71f53b76", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:29:43.396825Z", "iopub.status.busy": "2025-03-25T08:29:43.396683Z", "iopub.status.idle": "2025-03-25T08:29:43.532804Z", "shell.execute_reply": "2025-03-25T08:29:43.532406Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"GE/miRNA expression profile of Human Epicardial Adipose Tissue (EAT) and Subcutaneous Adipose Tissue (SAT) in Patients with Coronary Artery Disease (CAD) vs. Controls (CTRL) - PART 1 - Genes\"\n", "!Series_summary\t\"Gene expression profiles of Human EAT vs. SAT (CTRL & CAD). The aim of the present study was to assess a gene expression chart characterizing EAT vs. SAT, and CAD vs. CTRL. Results provide the information that EAT is characterized by a differential expression of different genes when compared to its reference tissue (SAT), and that EAT is characterized by specific gene expression changes in patients with CAD.\"\n", "!Series_overall_design\t\"RNA obtained from EAT & SAT of the same patients (paired samples). Comparisons: EAT vs. SAT (paired samples) & CAD vs. CTRL\"\n", "Sample Characteristics Dictionary:\n", "{0: ['age: 76', 'age: 71', 'age: 57', 'age: 30', 'age: 81', 'age: 51', 'age: 36', 'age: 44', 'age: 52', 'age: 73', 'age: 69', 'age: 56', 'age: 70', 'age: 67', 'age: 60', 'age: 61', 'age: 86', 'age: 82'], 1: ['tissue: Subcutaneous Adipose', 'tissue: Epicardial Adipose'], 2: ['disease state: control', 'disease state: coronary artery 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": "b360499b", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "6e16f435", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:29:43.534143Z", "iopub.status.busy": "2025-03-25T08:29:43.534031Z", "iopub.status.idle": "2025-03-25T08:29:43.543696Z", "shell.execute_reply": "2025-03-25T08:29:43.543394Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of processed clinical data:\n", "{'GSM1574149': [0.0, 76.0], 'GSM1574150': [0.0, 76.0], 'GSM1574151': [0.0, 71.0], 'GSM1574152': [0.0, 71.0], 'GSM1574153': [0.0, 57.0], 'GSM1574154': [0.0, 57.0], 'GSM1574155': [0.0, 30.0], 'GSM1574156': [0.0, 30.0], 'GSM1574157': [0.0, 81.0], 'GSM1574158': [0.0, 81.0], 'GSM1574159': [0.0, 51.0], 'GSM1574160': [0.0, 51.0], 'GSM1574161': [0.0, 36.0], 'GSM1574162': [0.0, 36.0], 'GSM1574163': [0.0, 44.0], 'GSM1574164': [0.0, 44.0], 'GSM1574165': [0.0, 36.0], 'GSM1574166': [0.0, 36.0], 'GSM1574167': [0.0, 52.0], 'GSM1574168': [0.0, 52.0], 'GSM1574169': [1.0, 73.0], 'GSM1574170': [1.0, 73.0], 'GSM1574171': [1.0, 69.0], 'GSM1574172': [1.0, 69.0], 'GSM1574173': [1.0, 56.0], 'GSM1574174': [1.0, 56.0], 'GSM1574175': [1.0, 69.0], 'GSM1574176': [1.0, 69.0], 'GSM1574177': [1.0, 73.0], 'GSM1574178': [1.0, 73.0], 'GSM1574179': [1.0, 70.0], 'GSM1574180': [1.0, 70.0], 'GSM1574181': [1.0, 67.0], 'GSM1574182': [1.0, 67.0], 'GSM1574183': [1.0, 60.0], 'GSM1574184': [1.0, 60.0], 'GSM1574185': [1.0, 61.0], 'GSM1574186': [1.0, 61.0], 'GSM1574187': [1.0, 86.0], 'GSM1574188': [1.0, 86.0], 'GSM1574189': [1.0, 82.0], 'GSM1574190': [1.0, 82.0], 'GSM1574191': [1.0, 71.0], 'GSM1574192': [1.0, 71.0], 'GSM1574193': [1.0, 70.0], 'GSM1574194': [1.0, 70.0]}\n", "Processed clinical data saved to ../../output/preprocess/Coronary_artery_disease/clinical_data/GSE64554.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on Series_title, this is gene expression data from adipose tissue\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait (coronary artery disease status)\n", "# Key 2 contains \"disease state: control\" and \"disease state: coronary artery disease\"\n", "trait_row = 2\n", "\n", "# For age - available in key 0\n", "age_row = 0\n", "\n", "# For gender - not available in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert disease state to binary: 0 for control, 1 for CAD\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " else:\n", " value = value.lower().strip()\n", " \n", " if 'control' in value:\n", " return 0\n", " elif 'coronary artery disease' in value or 'cad' in value:\n", " return 1\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to continuous numeric value\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary: 0 for female, 1 for male\n", " Not used in this dataset as gender information is not available\"\"\"\n", " return None\n", "\n", "# 3. Save Metadata\n", "is_trait_available = trait_row is not None\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # Extract clinical features\n", " clinical_data_processed = 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 processed clinical data\n", " preview = preview_df(clinical_data_processed)\n", " print(\"Preview of processed clinical data:\")\n", " print(preview)\n", " \n", " # Save the processed clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_data_processed.to_csv(out_clinical_data_file)\n", " print(f\"Processed clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "accaf373", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "4906b5e4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:29:43.544868Z", "iopub.status.busy": "2025-03-25T08:29:43.544753Z", "iopub.status.idle": "2025-03-25T08:29:43.763643Z", "shell.execute_reply": "2025-03-25T08:29:43.763247Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SOFT file: ../../input/GEO/Coronary_artery_disease/GSE64554/GSE64554_family.soft.gz\n", "Matrix file: ../../input/GEO/Coronary_artery_disease/GSE64554/GSE64554_series_matrix.txt.gz\n", "Found the matrix table marker at line 56\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (48783, 46)\n", "First 20 gene/probe identifiers:\n", "['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209', 'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229', 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236', 'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253', 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262']\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": "9e86e837", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "4abad5e5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:29:43.764994Z", "iopub.status.busy": "2025-03-25T08:29:43.764876Z", "iopub.status.idle": "2025-03-25T08:29:43.766769Z", "shell.execute_reply": "2025-03-25T08:29:43.766479Z" } }, "outputs": [], "source": [ "# Analysis of gene identifiers\n", "# The identifiers starting with \"ILMN_\" are Illumina probe IDs, not human gene symbols\n", "# These are microarray probe identifiers from Illumina platform that need to be mapped to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "7588195b", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "9266c407", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:29:43.767908Z", "iopub.status.busy": "2025-03-25T08:29:43.767804Z", "iopub.status.idle": "2025-03-25T08:29:48.657042Z", "shell.execute_reply": "2025-03-25T08:29:48.656523Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'nuID', 'Species', 'Source', 'Search_Key', 'Transcript', 'ILMN_Gene', 'Source_Reference_ID', 'RefSeq_ID', 'Unigene_ID', 'Entrez_Gene_ID', 'GI', 'Accession', 'Symbol', 'Protein_Product', 'Array_Address_Id', 'Probe_Type', 'Probe_Start', 'SEQUENCE', 'Chromosome', 'Probe_Chr_Orientation', 'Probe_Coordinates', 'Cytoband', 'Definition', 'Ontology_Component', 'Ontology_Process', 'Ontology_Function', 'Synonyms', 'Obsolete_Probe_Id', 'GB_ACC']\n", "{'ID': ['ILMN_1725881', 'ILMN_1910180', 'ILMN_1804174'], 'nuID': ['rp13_p1x6D80lNLk3c', 'NEX0oqCV8.er4HVfU4', 'KyqQynMZxJcruyylEU'], 'Species': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Source': ['RefSeq', 'Unigene', 'RefSeq'], 'Search_Key': ['ILMN_44919', 'ILMN_127219', 'ILMN_139282'], 'Transcript': ['ILMN_44919', 'ILMN_127219', 'ILMN_139282'], 'ILMN_Gene': ['LOC23117', 'HS.575038', 'FCGR2B'], 'Source_Reference_ID': ['XM_933824.1', 'Hs.575038', 'XM_938851.1'], 'RefSeq_ID': ['XM_933824.1', nan, 'XM_938851.1'], 'Unigene_ID': [nan, 'Hs.575038', nan], 'Entrez_Gene_ID': [23117.0, nan, 2213.0], 'GI': [89040007.0, 10437021.0, 88952550.0], 'Accession': ['XM_933824.1', 'AK024680', 'XM_938851.1'], 'Symbol': ['LOC23117', nan, 'FCGR2B'], 'Protein_Product': ['XP_938917.1', nan, 'XP_943944.1'], 'Array_Address_Id': [1710221.0, 5900364.0, 2480717.0], 'Probe_Type': ['I', 'S', 'I'], 'Probe_Start': [122.0, 1409.0, 1643.0], 'SEQUENCE': ['GGCTCCTCTTTGGGCTCCTACTGGAATTTATCAGCCATCAGTGCATCTCT', 'ACACCTTCAGGAGGGAAGCCCTTATTTCTGGGTTGAACTCCCCTTCCATG', 'TAGGGGCAATAGGCTATACGCTACAGCCTAGGTGTGTAGTAGGCCACACC'], 'Chromosome': ['16', nan, nan], 'Probe_Chr_Orientation': ['-', nan, nan], 'Probe_Coordinates': ['21766363-21766363:21769901-21769949', nan, nan], 'Cytoband': ['16p12.2a', nan, '1q23.3b'], 'Definition': ['PREDICTED: Homo sapiens KIAA0220-like protein, transcript variant 11 (LOC23117), mRNA.', 'Homo sapiens cDNA: FLJ21027 fis, clone CAE07110', 'PREDICTED: Homo sapiens Fc fragment of IgG, low affinity IIb, receptor (CD32) (FCGR2B), mRNA.'], 'Ontology_Component': [nan, nan, nan], 'Ontology_Process': [nan, nan, nan], 'Ontology_Function': [nan, nan, nan], 'Synonyms': [nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan], 'GB_ACC': ['XM_933824.1', 'AK024680', 'XM_938851.1']}\n", "\n", "Examining ID and Symbol columns format (first 3 rows):\n", "Row 0: ID=ILMN_1725881\n", "Symbol: LOC23117\n", "Row 1: ID=ILMN_1910180\n", "Symbol: nan\n", "Row 2: ID=ILMN_1804174\n", "Symbol: FCGR2B\n", "\n", "Symbol column completeness: 36157/2293640 rows (1.58%)\n", "\n", "Attempting to extract gene symbols from the first few rows:\n", "Row 0 extracted symbols: []\n", "Row 2 extracted symbols: ['FCGR2B']\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", "# Looking at the output, the Symbol column seems to contain gene information\n", "print(\"\\nExamining ID and Symbol columns format (first 3 rows):\")\n", "if 'ID' in gene_annotation.columns and 'Symbol' in gene_annotation.columns:\n", " for i in range(min(3, len(gene_annotation))):\n", " print(f\"Row {i}: ID={gene_annotation['ID'].iloc[i]}\")\n", " print(f\"Symbol: {gene_annotation['Symbol'].iloc[i]}\")\n", "\n", " # Check the quality and completeness of the mapping\n", " non_null_symbols = gene_annotation['Symbol'].notna().sum()\n", " total_rows = len(gene_annotation)\n", " print(f\"\\nSymbol column completeness: {non_null_symbols}/{total_rows} rows ({non_null_symbols/total_rows:.2%})\")\n", " \n", " # Check if some extracted gene symbols can be found in the Symbol column\n", " print(\"\\nAttempting to extract gene symbols from the first few rows:\")\n", " for i in range(min(3, len(gene_annotation))):\n", " if pd.notna(gene_annotation['Symbol'].iloc[i]):\n", " symbols = extract_human_gene_symbols(str(gene_annotation['Symbol'].iloc[i]))\n", " print(f\"Row {i} extracted symbols: {symbols}\")\n" ] }, { "cell_type": "markdown", "id": "e0413a85", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "0ca084a5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:29:48.658562Z", "iopub.status.busy": "2025-03-25T08:29:48.658448Z", "iopub.status.idle": "2025-03-25T08:29:49.351283Z", "shell.execute_reply": "2025-03-25T08:29:49.350635Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping shape: (36157, 2)\n", "Sample of gene mapping (first 5 rows):\n", " ID Gene\n", "0 ILMN_1725881 LOC23117\n", "2 ILMN_1804174 FCGR2B\n", "3 ILMN_1796063 TRIM44\n", "4 ILMN_1811966 LOC653895\n", "5 ILMN_1668162 DGAT2L3\n", "Mapped gene data shape: (19113, 46)\n", "First few gene symbols after mapping:\n", "['A1BG', 'A1CF', 'A26A1', 'A26B1', 'A26C1B', 'A26C3', 'A2BP1', 'A2M', 'A2ML1', 'A3GALT2']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape after normalization: (18319, 46)\n", "First few normalized gene symbols:\n", "['A1BG', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS', 'AACS']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Coronary_artery_disease/gene_data/GSE64554.csv\n" ] } ], "source": [ "# Based on the observation from Step 5, the ID column in gene_annotation contains Illumina probe IDs\n", "# that match the gene expression data identifiers, and the Symbol column contains gene symbols\n", "\n", "# 1 & 2. Extract gene identifier and gene symbol columns for mapping\n", "prob_col = 'ID'\n", "gene_col = 'Symbol'\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "\n", "print(f\"Gene mapping shape: {gene_mapping.shape}\")\n", "print(\"Sample of gene mapping (first 5 rows):\")\n", "print(gene_mapping.head())\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "print(f\"Mapped gene data shape: {gene_data.shape}\")\n", "print(\"First few gene symbols after mapping:\")\n", "print(gene_data.index[:10].tolist())\n", "\n", "# Normalize gene symbols to handle synonyms and variants\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape after normalization: {gene_data.shape}\")\n", "print(\"First few normalized gene symbols:\")\n", "print(gene_data.index[:10].tolist())\n", "\n", "# Save the 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\"Gene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "57f609a1", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "80112f15", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:29:49.353217Z", "iopub.status.busy": "2025-03-25T08:29:49.353060Z", "iopub.status.idle": "2025-03-25T08:29:57.852181Z", "shell.execute_reply": "2025-03-25T08:29:57.851476Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (18319, 46)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data saved to ../../output/preprocess/Coronary_artery_disease/gene_data/GSE64554.csv\n", "Loaded clinical data shape: (2, 46)\n", "Initial linked data shape: (46, 18321)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape after handling missing values: (46, 18321)\n", "For the feature 'Coronary_artery_disease', the least common label is '0.0' with 20 occurrences. This represents 43.48% of the dataset.\n", "The distribution of the feature 'Coronary_artery_disease' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 53.0\n", " 50% (Median): 69.0\n", " 75%: 72.5\n", "Min: 30.0\n", "Max: 86.0\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Coronary_artery_disease/GSE64554.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", " # Check if gene_data (from previous step) has any content\n", " if 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=is_trait_available,\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", " if is_trait_available:\n", " # Load clinical data\n", " clinical_features = pd.read_csv(out_clinical_data_file, index_col=0)\n", " print(f\"Loaded clinical data shape: {clinical_features.shape}\")\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", " \n", " # Handle missing values\n", " linked_data = handle_missing_values(linked_data, trait)\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)\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=is_trait_available,\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=is_trait_available,\n", " is_biased=True,\n", " df=pd.DataFrame(),\n", " note=\"No valid samples after handling missing values.\"\n", " )\n", " else:\n", " # Cannot proceed with linking if trait data is missing\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=is_trait_available,\n", " is_biased=True,\n", " df=pd.DataFrame(),\n", " note=\"Cannot link data because trait information is not available.\"\n", " )\n", "except Exception as e:\n", " print(f\"Error in data processing: {e}\")\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=is_trait_available,\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 }