{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "0cd00443", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:27:43.463673Z", "iopub.status.busy": "2025-03-25T05:27:43.463564Z", "iopub.status.idle": "2025-03-25T05:27:43.655425Z", "shell.execute_reply": "2025-03-25T05:27:43.655084Z" } }, "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 = \"Head_and_Neck_Cancer\"\n", "cohort = \"GSE201777\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Head_and_Neck_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Head_and_Neck_Cancer/GSE201777\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Head_and_Neck_Cancer/GSE201777.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Head_and_Neck_Cancer/gene_data/GSE201777.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Head_and_Neck_Cancer/clinical_data/GSE201777.csv\"\n", "json_path = \"../../output/preprocess/Head_and_Neck_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "ad6a6dbf", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "b28cfdb3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:27:43.656838Z", "iopub.status.busy": "2025-03-25T05:27:43.656693Z", "iopub.status.idle": "2025-03-25T05:27:43.788597Z", "shell.execute_reply": "2025-03-25T05:27:43.788257Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Differentially expressed genes related to lymph node metastasis in advanced laryngeal squamous cell cancers\"\n", "!Series_summary\t\"Understanding the molecular mechanisms and gene expression in laryngeal squamous cell carcinoma (LSCC) may explain its aggressive biological behavior and regional metastasis pathways. Better understanding of the molecular mechanisms underlying LSCC metastasis and the search for possible molecular targets seems promising. Interpreting the links between the differentially expressed genes in advanced stages can lead to a search for predictive markers that can also help determine the possible treatment routes. We designed this study to detect possible genetic alterations in a homogeneous group of patients with locoregionally advanced laryngeal cancer who underwent total laryngectomy and neck dissection. Patients with and without lymph node metastasis were selected to examine the differential gene expression in the normal mucosa, tumor, and lymph node tissues of each patient. Our main purpose was to identify the possible commonly expressed genes in this homogenous group of Turkish patients with locoregionally advanced laryngeal cancer. Second, we aimed to determine the predictive role of these genes in lymph node metastasis and overall prognosis.\"\n", "!Series_overall_design\t\"A total of 16 patients who had undergone total laryngectomy with neck dissection for advanced LSCC were randomly selected from our database: eight patients had lymph node metastasis (Group 1) and the other eight patients had no metastasis (Group 2). For each patient, paraffin-embedded tissue samples were collected from non-tumoral mucosa, tumoral lesions, and lymph node tissues. These tissue samples were used to extract RNA after cDNA synthesis, and microarray analysis was subsequently performed on each sample. Genetic alterations were determined in each specimen, and Groups 1 and 2 were compared and statistically analyzed.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['patient diagnosis: laryngeal squamous cell carcinoma (LSCC)'], 1: ['tissue: Lymph node', 'tissue: Tumor', 'tissue: Mucosa'], 2: ['lymph node metastasis: negative', 'lymph node metastasis: positive', 'lymph node metastasis: positiive']}\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": "f4601487", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "69a22861", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:27:43.789791Z", "iopub.status.busy": "2025-03-25T05:27:43.789666Z", "iopub.status.idle": "2025-03-25T05:27:43.797673Z", "shell.execute_reply": "2025-03-25T05:27:43.797375Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'GSM6071161': [0.0], 'GSM6071162': [0.0], 'GSM6071163': [0.0], 'GSM6071164': [0.0], 'GSM6071165': [0.0], 'GSM6071166': [0.0], 'GSM6071167': [0.0], 'GSM6071168': [0.0], 'GSM6071169': [0.0], 'GSM6071170': [1.0], 'GSM6071171': [1.0], 'GSM6071172': [1.0], 'GSM6071173': [1.0], 'GSM6071174': [1.0], 'GSM6071175': [1.0], 'GSM6071176': [0.0], 'GSM6071177': [0.0], 'GSM6071178': [0.0], 'GSM6071179': [0.0], 'GSM6071180': [0.0], 'GSM6071181': [0.0], 'GSM6071182': [0.0], 'GSM6071183': [0.0], 'GSM6071184': [0.0], 'GSM6071185': [0.0], 'GSM6071186': [0.0], 'GSM6071187': [0.0], 'GSM6071188': [1.0], 'GSM6071189': [1.0], 'GSM6071190': [1.0], 'GSM6071191': [1.0], 'GSM6071192': [1.0], 'GSM6071193': [1.0], 'GSM6071194': [1.0], 'GSM6071195': [1.0], 'GSM6071196': [1.0], 'GSM6071197': [1.0], 'GSM6071198': [1.0], 'GSM6071199': [0.0], 'GSM6071200': [0.0], 'GSM6071201': [0.0], 'GSM6071202': [1.0], 'GSM6071203': [1.0], 'GSM6071204': [1.0], 'GSM6071205': [1.0], 'GSM6071206': [1.0], 'GSM6071207': [1.0]}\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Callable, Optional, Dict, Any\n", "\n", "# 1. Determine gene expression data availability \n", "# From background information, we can see this dataset is about gene expression related to lymph node metastasis in LSCC\n", "is_gene_available = True\n", "\n", "# 2. Identify keys for trait, age, and gender and create conversion functions\n", "# Looking at the sample characteristics, we can see:\n", "# - Index 2 contains lymph node metastasis status (can be used as trait)\n", "# - No age information available\n", "# - No gender information available\n", "\n", "# 2.1 Data availability\n", "trait_row = 2 # lymph node metastasis information is available at index 2\n", "age_row = None # No age information available\n", "gender_row = None # No gender information available\n", "\n", "# 2.2 Data type conversion functions\n", "def convert_trait(value):\n", " \"\"\"Convert trait (lymph node metastasis) value to binary (0 for negative, 1 for positive)\"\"\"\n", " if not value or 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", " # Convert to binary\n", " if value.lower() == \"negative\":\n", " return 0\n", " elif value.lower() in [\"positive\", \"positiive\"]: # Handling typo in the data\n", " return 1\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to continuous numeric\"\"\"\n", " # Not used as age data is not available, but required for function signature\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender value to binary (0 for female, 1 for male)\"\"\"\n", " # Not used as gender data is not available, but required for function signature\n", " return None\n", "\n", "# 3. Perform initial filtering and 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. If trait data is available, extract clinical features\n", "if trait_row is not None:\n", " # Assuming clinical_data is already available from a previous step\n", " # We'll continue with the processing using the existing clinical_data DataFrame\n", " \n", " # Use library function to extract clinical features\n", " clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=\"Lymph_Node_Metastasis\",\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 clinical features\n", " print(preview_df(clinical_features))\n", " \n", " # Ensure output directory exists\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the clinical features to CSV\n", " clinical_features.to_csv(out_clinical_data_file, index=False)\n" ] }, { "cell_type": "markdown", "id": "88b3281a", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "42d5c967", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:27:43.798763Z", "iopub.status.busy": "2025-03-25T05:27:43.798651Z", "iopub.status.idle": "2025-03-25T05:27:43.999354Z", "shell.execute_reply": "2025-03-25T05:27:43.999020Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Head_and_Neck_Cancer/GSE201777/GSE201777_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (49395, 47)" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "First 20 gene/probe identifiers:\n", "Index(['11715100_at', '11715101_s_at', '11715102_x_at', '11715103_x_at',\n", " '11715104_s_at', '11715105_at', '11715106_x_at', '11715107_s_at',\n", " '11715108_x_at', '11715109_at', '11715110_at', '11715111_s_at',\n", " '11715112_at', '11715113_x_at', '11715114_x_at', '11715115_s_at',\n", " '11715116_s_at', '11715117_x_at', '11715118_s_at', '11715119_s_at'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. Get the SOFT and matrix file paths again \n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "print(f\"Matrix file found: {matrix_file}\")\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_data\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " \n", " # 3. Print the first 20 row IDs (gene or probe identifiers)\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20])\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n" ] }, { "cell_type": "markdown", "id": "f7a443ce", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "5ac05257", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:27:44.000610Z", "iopub.status.busy": "2025-03-25T05:27:44.000490Z", "iopub.status.idle": "2025-03-25T05:27:44.002413Z", "shell.execute_reply": "2025-03-25T05:27:44.002128Z" } }, "outputs": [], "source": [ "# Looking at the gene identifiers, they appear to be Affymetrix probe IDs (with the \"_at\", \"_s_at\", \"_x_at\" pattern)\n", "# rather than standard human gene symbols like \"TP53\" or \"BRCA1\"\n", "# These probe IDs will need to be mapped to human gene symbols for meaningful analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "06cfdd89", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "d12e1cbe", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:27:44.003516Z", "iopub.status.busy": "2025-03-25T05:27:44.003412Z", "iopub.status.idle": "2025-03-25T05:27:51.742136Z", "shell.execute_reply": "2025-03-25T05:27:51.741773Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'GeneChip Array', 'Species Scientific Name', 'Annotation Date', 'Sequence Type', 'Sequence Source', 'Transcript ID(Array Design)', 'Target Description', 'GB_ACC', 'GI', 'Representative Public ID', 'Archival UniGene Cluster', 'UniGene ID', 'Genome Version', 'Alignments', 'Gene Title', 'Gene Symbol', 'Chromosomal Location', 'Unigene Cluster Type', 'Ensembl', 'Entrez Gene', 'SwissProt', 'EC', 'OMIM', 'RefSeq Protein ID', 'RefSeq Transcript ID', 'Gene Ontology Biological Process', 'Gene Ontology Cellular Component', 'Gene Ontology Molecular Function', 'Pathway', 'InterPro', 'Annotation Description', 'Annotation Transcript Cluster', 'Transcript Assignments', 'Annotation Notes', 'SPOT_ID']\n", "{'ID': ['11715100_at', '11715101_s_at', '11715102_x_at', '11715103_x_at', '11715104_s_at'], 'GeneChip Array': ['Human Genome PrimeView Array', 'Human Genome PrimeView Array', 'Human Genome PrimeView Array', 'Human Genome PrimeView Array', 'Human Genome PrimeView Array'], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['30-Mar-16', '30-Mar-16', '30-Mar-16', '30-Mar-16', '30-Mar-16'], 'Sequence Type': ['Consensus sequence', 'Consensus sequence', 'Consensus sequence', 'Consensus sequence', 'Consensus sequence'], 'Sequence Source': ['Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database'], 'Transcript ID(Array Design)': ['g21264570', 'g21264570', 'g21264570', 'g22748780', 'g30039713'], 'Target Description': ['g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g22748780 /TID=g22748780 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g22748780 /REP_ORG=Homo sapiens', 'g30039713 /TID=g30039713 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g30039713 /REP_ORG=Homo sapiens'], 'GB_ACC': [nan, nan, nan, nan, nan], 'GI': [21264570.0, 21264570.0, 21264570.0, 22748780.0, 30039713.0], 'Representative Public ID': ['g21264570', 'g21264570', 'g21264570', 'g22748780', 'g30039713'], 'Archival UniGene Cluster': ['---', '---', '---', '---', '---'], 'UniGene ID': ['Hs.247813', 'Hs.247813', 'Hs.247813', 'Hs.465643', 'Hs.352515'], 'Genome Version': ['February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)'], 'Alignments': ['chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr19:4639529-5145579 (+) // 48.53 // p13.3', 'chr17:72920369-72929640 (+) // 100.0 // q25.1'], 'Gene Title': ['histone cluster 1, H3g', 'histone cluster 1, H3g', 'histone cluster 1, H3g', 'tumor necrosis factor, alpha-induced protein 8-like 1', 'otopetrin 2'], 'Gene Symbol': ['HIST1H3G', 'HIST1H3G', 'HIST1H3G', 'TNFAIP8L1', 'OTOP2'], 'Chromosomal Location': ['chr6p22.2', 'chr6p22.2', 'chr6p22.2', 'chr19p13.3', 'chr17q25.1'], 'Unigene Cluster Type': ['full length', 'full length', 'full length', 'full length', 'full length'], 'Ensembl': ['ENSG00000273983 /// OTTHUMG00000014436', 'ENSG00000273983 /// OTTHUMG00000014436', 'ENSG00000273983 /// OTTHUMG00000014436', 'ENSG00000185361 /// OTTHUMG00000182013', 'ENSG00000183034 /// OTTHUMG00000179215'], 'Entrez Gene': ['8355', '8355', '8355', '126282', '92736'], 'SwissProt': ['P68431', 'P68431', 'P68431', 'Q8WVP5', 'Q7RTS6'], 'EC': ['---', '---', '---', '---', '---'], 'OMIM': ['602815', '602815', '602815', '615869', '607827'], 'RefSeq Protein ID': ['NP_003525', 'NP_003525', 'NP_003525', 'NP_001161414 /// NP_689575 /// XP_005259544 /// XP_011525982', 'NP_835454 /// XP_011523781'], 'RefSeq Transcript ID': ['NM_003534', 'NM_003534', 'NM_003534', 'NM_001167942 /// NM_152362 /// XM_005259487 /// XM_011527680', 'NM_178160 /// XM_011525479'], 'Gene Ontology Biological Process': ['0000183 // chromatin silencing at rDNA // traceable author statement /// 0002230 // positive regulation of defense response to virus by host // inferred from mutant phenotype /// 0006325 // chromatin organization // traceable author statement /// 0006334 // nucleosome assembly // inferred from direct assay /// 0006334 // nucleosome assembly // inferred from mutant phenotype /// 0006335 // DNA replication-dependent nucleosome assembly // inferred from direct assay /// 0007264 // small GTPase mediated signal transduction // traceable author statement /// 0007596 // blood coagulation // traceable author statement /// 0010467 // gene expression // traceable author statement /// 0031047 // gene silencing by RNA // traceable author statement /// 0032776 // DNA methylation on cytosine // traceable author statement /// 0040029 // regulation of gene expression, epigenetic // traceable author statement /// 0044267 // cellular protein metabolic process // traceable author statement /// 0045814 // negative regulation of gene expression, epigenetic // traceable author statement /// 0051290 // protein heterotetramerization // inferred from direct assay /// 0060968 // regulation of gene silencing // inferred from direct assay /// 0098792 // xenophagy // inferred from mutant phenotype', '0000183 // chromatin silencing at rDNA // traceable author statement /// 0002230 // positive regulation of defense response to virus by host // inferred from mutant phenotype /// 0006325 // chromatin organization // traceable author statement /// 0006334 // nucleosome assembly // inferred from direct assay /// 0006334 // nucleosome assembly // inferred from mutant phenotype /// 0006335 // DNA replication-dependent nucleosome assembly // inferred from direct assay /// 0007264 // small GTPase mediated signal transduction // traceable author statement /// 0007596 // blood coagulation // traceable author statement /// 0010467 // gene expression // traceable author statement /// 0031047 // gene silencing by RNA // traceable author statement /// 0032776 // DNA methylation on cytosine // traceable author statement /// 0040029 // regulation of gene expression, epigenetic // traceable author statement /// 0044267 // cellular protein metabolic process // traceable author statement /// 0045814 // negative regulation of gene expression, epigenetic // traceable author statement /// 0051290 // protein heterotetramerization // inferred from direct assay /// 0060968 // regulation of gene silencing // inferred from direct assay /// 0098792 // xenophagy // inferred from mutant phenotype', '0000183 // chromatin silencing at rDNA // traceable author statement /// 0002230 // positive regulation of defense response to virus by host // inferred from mutant phenotype /// 0006325 // chromatin organization // traceable author statement /// 0006334 // nucleosome assembly // inferred from direct assay /// 0006334 // nucleosome assembly // inferred from mutant phenotype /// 0006335 // DNA replication-dependent nucleosome assembly // inferred from direct assay /// 0007264 // small GTPase mediated signal transduction // traceable author statement /// 0007596 // blood coagulation // traceable author statement /// 0010467 // gene expression // traceable author statement /// 0031047 // gene silencing by RNA // traceable author statement /// 0032776 // DNA methylation on cytosine // traceable author statement /// 0040029 // regulation of gene expression, epigenetic // traceable author statement /// 0044267 // cellular protein metabolic process // traceable author statement /// 0045814 // negative regulation of gene expression, epigenetic // traceable author statement /// 0051290 // protein heterotetramerization // inferred from direct assay /// 0060968 // regulation of gene silencing // inferred from direct assay /// 0098792 // xenophagy // inferred from mutant phenotype', '0032007 // negative regulation of TOR signaling // not recorded /// 0032007 // negative regulation of TOR signaling // inferred from sequence or structural similarity', '---'], 'Gene Ontology Cellular Component': ['0000228 // nuclear chromosome // inferred from direct assay /// 0000786 // nucleosome // inferred from direct assay /// 0000788 // nuclear nucleosome // inferred from direct assay /// 0005576 // extracellular region // traceable author statement /// 0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // traceable author statement /// 0005694 // chromosome // inferred from electronic annotation /// 0016020 // membrane // inferred from direct assay /// 0043234 // protein complex // inferred from direct assay /// 0070062 // extracellular exosome // inferred from direct assay', '0000228 // nuclear chromosome // inferred from direct assay /// 0000786 // nucleosome // inferred from direct assay /// 0000788 // nuclear nucleosome // inferred from direct assay /// 0005576 // extracellular region // traceable author statement /// 0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // traceable author statement /// 0005694 // chromosome // inferred from electronic annotation /// 0016020 // membrane // inferred from direct assay /// 0043234 // protein complex // inferred from direct assay /// 0070062 // extracellular exosome // inferred from direct assay', '0000228 // nuclear chromosome // inferred from direct assay /// 0000786 // nucleosome // inferred from direct assay /// 0000788 // nuclear nucleosome // inferred from direct assay /// 0005576 // extracellular region // traceable author statement /// 0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // traceable author statement /// 0005694 // chromosome // inferred from electronic annotation /// 0016020 // membrane // inferred from direct assay /// 0043234 // protein complex // inferred from direct assay /// 0070062 // extracellular exosome // inferred from direct assay', '0005737 // cytoplasm // not recorded /// 0005737 // cytoplasm // inferred from sequence or structural similarity', '0016020 // membrane // inferred from electronic annotation /// 0016021 // integral component of membrane // inferred from electronic annotation'], 'Gene Ontology Molecular Function': ['0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0042393 // histone binding // inferred from physical interaction /// 0046982 // protein heterodimerization activity // inferred from electronic annotation', '0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0042393 // histone binding // inferred from physical interaction /// 0046982 // protein heterodimerization activity // inferred from electronic annotation', '0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0042393 // histone binding // inferred from physical interaction /// 0046982 // protein heterodimerization activity // inferred from electronic annotation', '0005515 // protein binding // inferred from physical interaction', '---'], 'Pathway': ['---', '---', '---', '---', '---'], 'InterPro': ['IPR007125 // Histone H2A/H2B/H3 // 9.3E-34 /// IPR007125 // Histone H2A/H2B/H3 // 1.7E-37', 'IPR007125 // Histone H2A/H2B/H3 // 9.3E-34 /// IPR007125 // Histone H2A/H2B/H3 // 1.7E-37', 'IPR007125 // Histone H2A/H2B/H3 // 9.3E-34 /// IPR007125 // Histone H2A/H2B/H3 // 1.7E-37', 'IPR008477 // Protein of unknown function DUF758 // 8.4E-86 /// IPR008477 // Protein of unknown function DUF758 // 6.8E-90', 'IPR004878 // Otopetrin // 9.4E-43 /// IPR004878 // Otopetrin // 9.4E-43 /// IPR004878 // Otopetrin // 9.4E-43 /// IPR004878 // Otopetrin // 3.9E-18 /// IPR004878 // Otopetrin // 3.8E-20 /// IPR004878 // Otopetrin // 5.2E-16'], 'Annotation Description': ['This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 4 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 4 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 4 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 9 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 6 transcripts. // false // Matching Probes // A'], 'Annotation Transcript Cluster': ['ENST00000614378(11),NM_003534(11),OTTHUMT00000040099(11),uc003nhi.3', 'ENST00000614378(11),NM_003534(11),OTTHUMT00000040099(11),uc003nhi.3', 'ENST00000614378(11),NM_003534(11),OTTHUMT00000040099(11),uc003nhi.3', 'BC017672(11),BC044250(9),ENST00000327473(11),ENST00000536716(11),NM_001167942(11),NM_152362(11),OTTHUMT00000458662(11),uc002max.3,uc021une.1', 'ENST00000331427(11),ENST00000580223(11),NM_178160(11),OTTHUMT00000445306(11),uc010wrp.2,XM_011525479(11)'], 'Transcript Assignments': ['ENST00000614378 // ensembl_havana_transcript:known chromosome:GRCh38:6:26269405:26271815:-1 gene:ENSG00000273983 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // --- /// OTTHUMT00000040099 // otter:known chromosome:VEGA61:6:26269405:26271815:-1 gene:OTTHUMG00000014436 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc003nhi.3 // --- // ucsc_genes // 11 // ---', 'ENST00000614378 // ensembl_havana_transcript:known chromosome:GRCh38:6:26269405:26271815:-1 gene:ENSG00000273983 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// GENSCAN00000029819 // cdna:genscan chromosome:GRCh38:6:26270974:26271384:-1 transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // --- /// OTTHUMT00000040099 // otter:known chromosome:VEGA61:6:26269405:26271815:-1 gene:OTTHUMG00000014436 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc003nhi.3 // --- // ucsc_genes // 11 // ---', 'ENST00000614378 // ensembl_havana_transcript:known chromosome:GRCh38:6:26269405:26271815:-1 gene:ENSG00000273983 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // --- /// OTTHUMT00000040099 // otter:known chromosome:VEGA61:6:26269405:26271815:-1 gene:OTTHUMG00000014436 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc003nhi.3 // --- // ucsc_genes // 11 // ---', 'BC017672 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1, mRNA (cDNA clone MGC:17791 IMAGE:3885999), complete cds. // gb // 11 // --- /// BC044250 // accn=BC044250 class=mRNAlike lncRNA name=Human lncRNA ref=JounralRNA transcriptId=673 cpcScore=-0.1526100 cnci=-0.1238602 // noncode // 9 // --- /// BC044250 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1, mRNA (cDNA clone IMAGE:5784807). // gb // 9 // --- /// ENST00000327473 // ensembl_havana_transcript:known chromosome:GRCh38:19:4639518:4655568:1 gene:ENSG00000185361 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// ENST00000536716 // ensembl:known chromosome:GRCh38:19:4640017:4655568:1 gene:ENSG00000185361 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_001167942 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1 (TNFAIP8L1), transcript variant 1, mRNA. // refseq // 11 // --- /// NM_152362 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1 (TNFAIP8L1), transcript variant 2, mRNA. // refseq // 11 // --- /// NONHSAT060631 // Non-coding transcript identified by NONCODE: Exonic // noncode // 9 // --- /// OTTHUMT00000458662 // otter:known chromosome:VEGA61:19:4639518:4655568:1 gene:OTTHUMG00000182013 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc002max.3 // --- // ucsc_genes // 11 // --- /// uc021une.1 // --- // ucsc_genes // 11 // ---', 'ENST00000331427 // ensembl:known chromosome:GRCh38:17:74924275:74933911:1 gene:ENSG00000183034 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// ENST00000580223 // havana:known chromosome:GRCh38:17:74924603:74933912:1 gene:ENSG00000183034 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// GENSCAN00000013715 // cdna:genscan chromosome:GRCh38:17:74924633:74933545:1 transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_178160 // Homo sapiens otopetrin 2 (OTOP2), mRNA. // refseq // 11 // --- /// OTTHUMT00000445306 // otter:known chromosome:VEGA61:17:74924603:74933912:1 gene:OTTHUMG00000179215 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc010wrp.2 // --- // ucsc_genes // 11 // --- /// XM_011525479 // PREDICTED: Homo sapiens otopetrin 2 (OTOP2), transcript variant X1, mRNA. // refseq // 11 // ---'], 'Annotation Notes': ['---', '---', 'GENSCAN00000029819 // ensembl // 4 // Cross Hyb Matching Probes', '---', '---'], 'SPOT_ID': [nan, nan, nan, nan, nan]}\n", "\n", "Searching for platform information in SOFT file:\n", "!Series_platform_id = GPL15207\n", "\n", "Searching for gene symbol information in SOFT file:\n", "Found references to gene symbols:\n", "#Gene Symbol =\n", "ID\tGeneChip Array\tSpecies Scientific Name\tAnnotation Date\tSequence Type\tSequence Source\tTranscript ID(Array Design)\tTarget Description\tGB_ACC\tGI\tRepresentative Public ID\tArchival UniGene Cluster\tUniGene ID\tGenome Version\tAlignments\tGene Title\tGene Symbol\tChromosomal Location\tUnigene Cluster Type\tEnsembl\tEntrez Gene\tSwissProt\tEC\tOMIM\tRefSeq Protein ID\tRefSeq Transcript ID\tGene Ontology Biological Process\tGene Ontology Cellular Component\tGene Ontology Molecular Function\tPathway\tInterPro\tAnnotation Description\tAnnotation Transcript Cluster\tTranscript Assignments\tAnnotation Notes\tSPOT_ID\n", "\n", "Checking for additional annotation files in the directory:\n", "[]\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", "# Let's look for platform information in the SOFT file to understand the annotation better\n", "print(\"\\nSearching for platform information in SOFT file:\")\n", "with gzip.open(soft_file, 'rt') as f:\n", " for i, line in enumerate(f):\n", " if '!Series_platform_id' in line:\n", " print(line.strip())\n", " break\n", " if i > 100: # Limit search to first 100 lines\n", " print(\"Platform ID not found in first 100 lines\")\n", " break\n", "\n", "# Check if the SOFT file includes any reference to gene symbols\n", "print(\"\\nSearching for gene symbol information in SOFT file:\")\n", "with gzip.open(soft_file, 'rt') as f:\n", " gene_symbol_lines = []\n", " for i, line in enumerate(f):\n", " if 'GENE_SYMBOL' in line or 'gene_symbol' in line.lower() or 'symbol' in line.lower():\n", " gene_symbol_lines.append(line.strip())\n", " if i > 1000 and len(gene_symbol_lines) > 0: # Limit search but ensure we found something\n", " break\n", " \n", " if gene_symbol_lines:\n", " print(\"Found references to gene symbols:\")\n", " for line in gene_symbol_lines[:5]: # Show just first 5 matches\n", " print(line)\n", " else:\n", " print(\"No explicit gene symbol references found in first 1000 lines\")\n", "\n", "# Look for alternative annotation files or references in the directory\n", "print(\"\\nChecking for additional annotation files in the directory:\")\n", "all_files = os.listdir(in_cohort_dir)\n", "print([f for f in all_files if 'annotation' in f.lower() or 'platform' in f.lower() or 'gpl' in f.lower()])\n" ] }, { "cell_type": "markdown", "id": "859b4d66", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "08c444b9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:27:51.743403Z", "iopub.status.busy": "2025-03-25T05:27:51.743283Z", "iopub.status.idle": "2025-03-25T05:27:52.483017Z", "shell.execute_reply": "2025-03-25T05:27:52.482678Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Determining columns for gene mapping:\n", "Gene expression data has identifiers like: Index(['11715100_at', '11715101_s_at', '11715102_x_at'], dtype='object', name='ID')\n", "Gene annotation data has 'ID' column with values like: 0 11715100_at\n", "1 11715101_s_at\n", "2 11715102_x_at\n", "Name: ID, dtype: object\n", "Gene annotation data has 'Gene Symbol' column with values like: 0 HIST1H3G\n", "1 HIST1H3G\n", "2 HIST1H3G\n", "Name: Gene Symbol, dtype: object\n", "\n", "Gene mapping dataframe shape: (49372, 2)\n", "Gene mapping sample (first 5 rows):\n", " ID Gene\n", "0 11715100_at HIST1H3G\n", "1 11715101_s_at HIST1H3G\n", "2 11715102_x_at HIST1H3G\n", "3 11715103_x_at TNFAIP8L1\n", "4 11715104_s_at OTOP2\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Mapped gene expression data shape: (19963, 47)\n", "Gene expression data sample (first 5 genes, first 3 samples):\n", " GSM6071161 GSM6071162 GSM6071163\n", "Gene \n", "A1BG 2.000830 1.656920 2.373500\n", "A1CF 3.209655 3.271378 3.212505\n", "A2M 1.958110 3.177790 2.807670\n", "A2ML1 4.446110 3.589280 4.977190\n", "A3GALT2 1.632900 1.721840 2.705260\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data saved to: ../../output/preprocess/Head_and_Neck_Cancer/gene_data/GSE201777.csv\n" ] } ], "source": [ "# 1. Observe gene annotation data to determine which columns to use for mapping\n", "print(\"\\nDetermining columns for gene mapping:\")\n", "print(f\"Gene expression data has identifiers like: {gene_data.index[0:3]}\")\n", "print(f\"Gene annotation data has 'ID' column with values like: {gene_annotation['ID'][0:3]}\")\n", "print(f\"Gene annotation data has 'Gene Symbol' column with values like: {gene_annotation['Gene Symbol'][0:3]}\")\n", "\n", "# We need to map from probe IDs (in column 'ID') to gene symbols (in column 'Gene Symbol')\n", "prob_col = 'ID'\n", "gene_col = 'Gene Symbol'\n", "\n", "# 2. Get the gene mapping dataframe by extracting relevant columns\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "print(f\"\\nGene mapping dataframe shape: {gene_mapping.shape}\")\n", "print(\"Gene mapping sample (first 5 rows):\")\n", "print(gene_mapping.head())\n", "\n", "# 3. Apply gene mapping to convert probe-level data to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(f\"\\nMapped gene expression data shape: {gene_data.shape}\")\n", "print(\"Gene expression data sample (first 5 genes, first 3 samples):\")\n", "print(gene_data.iloc[:5, :3])\n", "\n", "# Save the gene data to CSV file\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"\\nGene expression data saved to: {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "ec948849", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "aea87e60", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:27:52.484356Z", "iopub.status.busy": "2025-03-25T05:27:52.484232Z", "iopub.status.idle": "2025-03-25T05:28:04.162729Z", "shell.execute_reply": "2025-03-25T05:28:04.162351Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (19963, 47)\n", "Gene data shape after normalization: (19758, 47)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Head_and_Neck_Cancer/gene_data/GSE201777.csv\n", "Original clinical data preview:\n", " !Sample_geo_accession \\\n", "0 !Sample_characteristics_ch1 \n", "1 !Sample_characteristics_ch1 \n", "2 !Sample_characteristics_ch1 \n", "\n", " GSM6071161 \\\n", "0 patient diagnosis: laryngeal squamous cell car... \n", "1 tissue: Lymph node \n", "2 lymph node metastasis: negative \n", "\n", " GSM6071162 \\\n", "0 patient diagnosis: laryngeal squamous cell car... \n", "1 tissue: Tumor \n", "2 lymph node metastasis: negative \n", "\n", " GSM6071163 \\\n", "0 patient diagnosis: laryngeal squamous cell car... \n", "1 tissue: Mucosa \n", "2 lymph node metastasis: negative \n", "\n", " GSM6071164 \\\n", "0 patient diagnosis: laryngeal squamous cell car... \n", "1 tissue: Mucosa \n", "2 lymph node metastasis: negative \n", "\n", " GSM6071165 \\\n", "0 patient diagnosis: laryngeal squamous cell car... \n", "1 tissue: Tumor \n", "2 lymph node metastasis: negative \n", "\n", " GSM6071166 \\\n", "0 patient diagnosis: laryngeal squamous cell car... \n", "1 tissue: Lymph node \n", "2 lymph node metastasis: negative \n", "\n", " GSM6071167 \\\n", "0 patient diagnosis: laryngeal squamous cell car... \n", "1 tissue: Tumor \n", "2 lymph node metastasis: negative \n", "\n", " GSM6071168 \\\n", "0 patient diagnosis: laryngeal squamous cell car... \n", "1 tissue: Mucosa \n", "2 lymph node metastasis: negative \n", "\n", " GSM6071169 ... \\\n", "0 patient diagnosis: laryngeal squamous cell car... ... \n", "1 tissue: Lymph node ... \n", "2 lymph node metastasis: negative ... \n", "\n", " GSM6071198 \\\n", "0 patient diagnosis: laryngeal squamous cell car... \n", "1 tissue: Mucosa \n", "2 lymph node metastasis: positiive \n", "\n", " GSM6071199 \\\n", "0 patient diagnosis: laryngeal squamous cell car... \n", "1 tissue: Tumor \n", "2 lymph node metastasis: negative \n", "\n", " GSM6071200 \\\n", "0 patient diagnosis: laryngeal squamous cell car... \n", "1 tissue: Mucosa \n", "2 lymph node metastasis: negative \n", "\n", " GSM6071201 \\\n", "0 patient diagnosis: laryngeal squamous cell car... \n", "1 tissue: Lymph node \n", "2 lymph node metastasis: negative \n", "\n", " GSM6071202 \\\n", "0 patient diagnosis: laryngeal squamous cell car... \n", "1 tissue: Lymph node \n", "2 lymph node metastasis: positive \n", "\n", " GSM6071203 \\\n", "0 patient diagnosis: laryngeal squamous cell car... \n", "1 tissue: Mucosa \n", "2 lymph node metastasis: positiive \n", "\n", " GSM6071204 \\\n", "0 patient diagnosis: laryngeal squamous cell car... \n", "1 tissue: Tumor \n", "2 lymph node metastasis: positive \n", "\n", " GSM6071205 \\\n", "0 patient diagnosis: laryngeal squamous cell car... \n", "1 tissue: Tumor \n", "2 lymph node metastasis: positive \n", "\n", " GSM6071206 \\\n", "0 patient diagnosis: laryngeal squamous cell car... \n", "1 tissue: Mucosa \n", "2 lymph node metastasis: positiive \n", "\n", " GSM6071207 \n", "0 patient diagnosis: laryngeal squamous cell car... \n", "1 tissue: Lymph node \n", "2 lymph node metastasis: positive \n", "\n", "[3 rows x 48 columns]\n", "Selected clinical data shape: (1, 47)\n", "Clinical data preview:\n", " GSM6071161 GSM6071162 GSM6071163 GSM6071164 \\\n", "Head_and_Neck_Cancer 0.0 0.0 0.0 0.0 \n", "\n", " GSM6071165 GSM6071166 GSM6071167 GSM6071168 \\\n", "Head_and_Neck_Cancer 0.0 0.0 0.0 0.0 \n", "\n", " GSM6071169 GSM6071170 ... GSM6071198 GSM6071199 \\\n", "Head_and_Neck_Cancer 0.0 1.0 ... 1.0 0.0 \n", "\n", " GSM6071200 GSM6071201 GSM6071202 GSM6071203 \\\n", "Head_and_Neck_Cancer 0.0 0.0 1.0 1.0 \n", "\n", " GSM6071204 GSM6071205 GSM6071206 GSM6071207 \n", "Head_and_Neck_Cancer 1.0 1.0 1.0 1.0 \n", "\n", "[1 rows x 47 columns]\n", "Linked data shape before processing: (47, 19759)\n", "Linked data preview (first 5 rows, 5 columns):\n", " Head_and_Neck_Cancer A1BG A1CF A2M A2ML1\n", "GSM6071161 0.0 2.00083 3.209655 1.95811 4.44611\n", "GSM6071162 0.0 1.65692 3.271378 3.17779 3.58928\n", "GSM6071163 0.0 2.37350 3.212505 2.80767 4.97719\n", "GSM6071164 0.0 1.88955 3.690160 2.93707 4.57414\n", "GSM6071165 0.0 1.45547 2.275280 1.97822 3.96406\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (47, 19759)\n", "For the feature 'Head_and_Neck_Cancer', the least common label is '1.0' with 23 occurrences. This represents 48.94% of the dataset.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Head_and_Neck_Cancer/GSE201777.csv\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", " # Check if trait is biased\n", " trait_type = 'binary' if len(linked_data[trait].unique()) <= 2 else 'continuous'\n", " if trait_type == \"binary\":\n", " is_biased = judge_binary_variable_biased(linked_data, trait)\n", " else:\n", " is_biased = judge_continuous_variable_biased(linked_data, trait)\n", " \n", " # Remove biased demographic features\n", " if \"Age\" in linked_data.columns:\n", " age_biased = judge_continuous_variable_biased(linked_data, 'Age')\n", " if age_biased:\n", " linked_data = linked_data.drop(columns='Age')\n", " \n", " if \"Gender\" in linked_data.columns:\n", " gender_biased = judge_binary_variable_biased(linked_data, 'Gender')\n", " if gender_biased:\n", " linked_data = linked_data.drop(columns='Gender')\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 Randall's plaque tissue, but linking clinical and genetic data failed, possibly due to mismatched sample IDs.\"\n", " else:\n", " note = \"Dataset contains gene expression data from Randall's plaque tissue associated with kidney stones.\"\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 kidney stones analysis.\"\n", " )\n", " \n", " print(\"Dataset is not usable for kidney stones 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 }