{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "998ebfc5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:20.904976Z", "iopub.status.busy": "2025-03-25T04:08:20.904875Z", "iopub.status.idle": "2025-03-25T04:08:21.070157Z", "shell.execute_reply": "2025-03-25T04:08:21.069779Z" } }, "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 = \"Telomere_Length\"\n", "cohort = \"GSE16058\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Telomere_Length\"\n", "in_cohort_dir = \"../../input/GEO/Telomere_Length/GSE16058\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Telomere_Length/GSE16058.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Telomere_Length/gene_data/GSE16058.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Telomere_Length/clinical_data/GSE16058.csv\"\n", "json_path = \"../../output/preprocess/Telomere_Length/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "0622eba1", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "e74ae778", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:21.071795Z", "iopub.status.busy": "2025-03-25T04:08:21.071629Z", "iopub.status.idle": "2025-03-25T04:08:21.165424Z", "shell.execute_reply": "2025-03-25T04:08:21.165091Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the cohort directory:\n", "['GSE16058_family.soft.gz', 'GSE16058_series_matrix.txt.gz']\n", "Identified SOFT files: ['GSE16058_family.soft.gz']\n", "Identified matrix files: ['GSE16058_series_matrix.txt.gz']\n", "\n", "Background Information:\n", "!Series_title\t\"Distinctions between the stasis and telomere attrition senescence barriers in cultured human mammary epithelial cells\"\n", "!Series_summary\t\"Molecular distinctions between the stasis and telomere attrition senescence barriers in cultured human mammary epithelial cells\"\n", "!Series_summary\t\"\"\n", "!Series_summary\t\"Normal human epithelial cells in culture have generally shown a limited proliferative potential of ~10-40 population doublings before encountering a stress-associated senescence barrier (stasis) associated with elevated levels of cyclin-dependent kinase inhibitors p16 and/or p21. We now show that simple changes in media composition can expand the proliferative potential of human mammary epithelial cells (HMEC) initiated as primary cultures to 50-60 population doublings, followed by p16(+), senescence-associated b-galactosidase(+) stasis. We compared the properties of growing and senescent pre-stasis HMEC with growing and senescent post-selection HMEC, i.e., cells grown in a serum-free medium that overcame stasis via silencing of p16 expression and that display senescence associated with telomere dysfunction. Cultured pre-stasis populations contained cells expressing markers associated with luminal and myoepithelial HMEC lineages in vivo, in contrast to the basal-like phenotype of the post-selection HMEC. Gene transcript and protein expression, DNA damage-associated markers, mean TRF length, and genomic stability, differed significantly between HMEC populations at the stasis vs. telomere attrition senescence barriers. Senescent isogenic fibroblasts showed greater similarity to HMEC at stasis than at telomere attrition, although their gene transcript profile was distinct from HMEC at both senescence barriers. These studies support our model of the senescence barriers encountered by cultured HMEC in which the first barrier, stasis, is Rb-mediated and independent of telomere length, while a second barrier (agonescence or crisis) results from telomere attrition leading to telomere dysfunction. Additionally, the ability to maintain long-term growth of genomically stable multi-lineage pre-stasis HMEC populations can greatly enhance experimentation with normal HMEC.\"\n", "!Series_overall_design\t\"48 samples from Human Mammary Epithelial cells which includes samples from four different individuals at different passage levels which includes prestasis,intermediate,post selection and agonesence stages of cell cycle.\"\n", "\n", "Sample Characteristics Dictionary:\n", "{0: ['cell type: mammary epithelial cell', 'cell type: mammary fibroblast cell'], 1: ['individual: 184', 'individual: 48', 'individual: 240L', 'individual: 250MK'], 2: ['passage: 2p', 'passage: 4p', 'passage: 6p', 'passage: 9p', 'passage: 11p', 'passage: 14p', 'passage: 8p', 'passage: 22p', 'passage: 12p', 'passage: 3p', 'passage: 5p', 'passage: 10p', 'passage: 15p', 'passage: 16p', 'passage: 7p', 'passage: 21p'], 3: ['growth status: Growing-Prestasis', 'growth status: Intermediate-Prestasis', 'growth status: Stasis', 'growth status: Prestasis', 'growth status: PostSelection', 'growth status: Agonesence-Postselection', 'growth status: Growing-Postselection', 'growth status: Growing', 'growth status: Senescent']}\n" ] } ], "source": [ "# 1. Let's first list the directory contents to understand what files are available\n", "import os\n", "\n", "print(\"Files in the cohort directory:\")\n", "files = os.listdir(in_cohort_dir)\n", "print(files)\n", "\n", "# Adapt file identification to handle different naming patterns\n", "soft_files = [f for f in files if 'soft' in f.lower() or '.soft' in f.lower() or '_soft' in f.lower()]\n", "matrix_files = [f for f in files if 'matrix' in f.lower() or '.matrix' in f.lower() or '_matrix' in f.lower()]\n", "\n", "# If no files with these patterns are found, look for alternative file types\n", "if not soft_files:\n", " soft_files = [f for f in files if f.endswith('.txt') or f.endswith('.gz')]\n", "if not matrix_files:\n", " matrix_files = [f for f in files if f.endswith('.txt') or f.endswith('.gz')]\n", "\n", "print(\"Identified SOFT files:\", soft_files)\n", "print(\"Identified matrix files:\", matrix_files)\n", "\n", "# Use the first files found, if any\n", "if len(soft_files) > 0 and len(matrix_files) > 0:\n", " soft_file = os.path.join(in_cohort_dir, soft_files[0])\n", " matrix_file = os.path.join(in_cohort_dir, matrix_files[0])\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(\"\\nBackground Information:\")\n", " print(background_info)\n", " print(\"\\nSample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", "else:\n", " print(\"No appropriate files found in the directory.\")\n" ] }, { "cell_type": "markdown", "id": "e2af7919", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "2f5b38d6", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:21.166797Z", "iopub.status.busy": "2025-03-25T04:08:21.166681Z", "iopub.status.idle": "2025-03-25T04:08:21.174454Z", "shell.execute_reply": "2025-03-25T04:08:21.174155Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical Data Preview:\n", "{'GSM402192': [0.0], 'GSM402193': [0.0], 'GSM402194': [0.0], 'GSM402195': [0.0], 'GSM402196': [0.0], 'GSM402197': [0.0], 'GSM402198': [0.0], 'GSM402199': [0.0], 'GSM402200': [0.0], 'GSM402201': [0.0], 'GSM402202': [0.0], 'GSM402203': [1.0], 'GSM402204': [0.0], 'GSM402205': [0.0], 'GSM402206': [1.0], 'GSM402207': [1.0], 'GSM402208': [1.0], 'GSM402209': [1.0], 'GSM402210': [0.0], 'GSM402211': [0.0], 'GSM402212': [0.0], 'GSM402213': [0.0], 'GSM402214': [0.0], 'GSM402215': [0.0], 'GSM402216': [0.0], 'GSM402217': [0.0], 'GSM402218': [0.0], 'GSM402219': [0.0], 'GSM402220': [0.0], 'GSM402221': [0.0], 'GSM402222': [0.0], 'GSM402223': [0.0], 'GSM402224': [0.0], 'GSM402225': [0.0], 'GSM402226': [0.0], 'GSM402227': [0.0], 'GSM402228': [1.0], 'GSM402229': [1.0], 'GSM402230': [0.0], 'GSM402231': [0.0], 'GSM402232': [1.0], 'GSM402233': [1.0], 'GSM402234': [0.0], 'GSM402235': [0.0], 'GSM402236': [1.0], 'GSM402237': [1.0], 'GSM402238': [0.0], 'GSM402239': [0.0]}\n", "Clinical data saved to ../../output/preprocess/Telomere_Length/clinical_data/GSE16058.csv\n" ] } ], "source": [ "# 1. Is gene expression data available?\n", "is_gene_available = True # Based on the summary and title, this dataset contains data about human mammary epithelial cells gene expression\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "trait_row = 3 # 'growth status' can be considered a proxy for telomere length\n", "age_row = None # No age information is available\n", "gender_row = None # No gender information is available\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert telomere length-related growth status to a binary value.\n", " 0: Short telomeres (Agonescence, Stasis, Senescent states)\n", " 1: Normal telomeres (Growing states)\n", " \"\"\"\n", " if value is None or ':' not in value:\n", " return None\n", " \n", " status = value.split(':', 1)[1].strip().lower()\n", " \n", " # States associated with telomere attrition or senescence (shorter telomeres)\n", " if 'agonesence' in status or 'stasis' in status or 'senescent' in status:\n", " return 0\n", " # States associated with normal growth (normal telomeres)\n", " elif 'growing' in status or 'prestasis' in status or 'postselection' in status:\n", " return 1\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " # Not needed as age data is not available\n", " return None\n", "\n", "def convert_gender(value):\n", " # Not needed as gender data 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 (only if trait_row is not None)\n", "if trait_row is not None:\n", " # Extract clinical features\n", " clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the dataframe\n", " print(\"Clinical Data Preview:\")\n", " print(preview_df(clinical_df))\n", " \n", " # Save clinical data to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_df.to_csv(out_clinical_data_file, index=True)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "38d12a14", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "6f972b73", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:21.175631Z", "iopub.status.busy": "2025-03-25T04:08:21.175519Z", "iopub.status.idle": "2025-03-25T04:08:21.309837Z", "shell.execute_reply": "2025-03-25T04:08:21.309453Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First 20 gene/probe identifiers:\n", "Index(['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at', '1294_at',\n", " '1316_at', '1320_at', '1405_i_at', '1431_at', '1438_at', '1487_at',\n", " '1494_f_at', '1598_g_at', '160020_at', '1729_at', '1773_at', '177_at',\n", " '179_at', '1861_at'],\n", " dtype='object', name='ID')\n", "\n", "Gene expression data shape: (22277, 48)\n" ] } ], "source": [ "# Use the helper function to get the proper file paths\n", "soft_file_path, matrix_file_path = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# Extract gene expression data\n", "try:\n", " gene_data = get_genetic_data(matrix_file_path)\n", " \n", " # Print the first 20 row IDs (gene or probe identifiers)\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20])\n", " \n", " # Print shape to understand the dataset dimensions\n", " print(f\"\\nGene expression data shape: {gene_data.shape}\")\n", " \n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n" ] }, { "cell_type": "markdown", "id": "185e86f5", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "84881644", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:21.311393Z", "iopub.status.busy": "2025-03-25T04:08:21.311276Z", "iopub.status.idle": "2025-03-25T04:08:21.313132Z", "shell.execute_reply": "2025-03-25T04:08:21.312842Z" } }, "outputs": [], "source": [ "# These identifiers (like '1007_s_at', '1053_at', etc.) are probe IDs from Affymetrix microarrays,\n", "# not standard human gene symbols. They need to be mapped to official gene symbols.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "9e5c7db0", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "94460b85", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:21.314285Z", "iopub.status.busy": "2025-03-25T04:08:21.314185Z", "iopub.status.idle": "2025-03-25T04:08:23.324192Z", "shell.execute_reply": "2025-03-25T04:08:23.323826Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at'], 'GB_ACC': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'SPOT_ID': [nan, nan, nan, nan, nan], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['Mar 8, 2007', 'Mar 8, 2007', 'Mar 8, 2007', 'Mar 8, 2007', 'Mar 8, 2007'], 'Sequence Type': ['Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence'], 'Sequence Source': [nan, nan, nan, nan, nan], 'Target Description': ['U48705 /FEATURE=mRNA /DEFINITION=HSU48705 Human receptor tyrosine kinase DDR gene, complete cds', 'M87338 /FEATURE= /DEFINITION=HUMA1SBU Human replication factor C, 40-kDa subunit (A1) mRNA, complete cds', \"X51757 /FEATURE=cds /DEFINITION=HSP70B Human heat-shock protein HSP70B' gene\", 'X69699 /FEATURE= /DEFINITION=HSPAX8A H.sapiens Pax8 mRNA', 'L36861 /FEATURE=expanded_cds /DEFINITION=HUMGCAPB Homo sapiens guanylate cyclase activating protein (GCAP) gene exons 1-4, complete cds'], 'Representative Public ID': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'Gene Title': ['discoidin domain receptor family, member 1', 'replication factor C (activator 1) 2, 40kDa', \"heat shock 70kDa protein 6 (HSP70B')\", 'paired box gene 8', 'guanylate cyclase activator 1A (retina)'], 'Gene Symbol': ['DDR1', 'RFC2', 'HSPA6', 'PAX8', 'GUCA1A'], 'ENTREZ_GENE_ID': ['780', '5982', '3310', '7849', '2978'], 'RefSeq Transcript ID': ['NM_001954 /// NM_013993 /// NM_013994', 'NM_002914 /// NM_181471', 'NM_002155 /// XM_001134322', 'NM_003466 /// NM_013951 /// NM_013952 /// NM_013953 /// NM_013992', 'NM_000409'], 'Gene Ontology Biological Process': ['0006468 // protein amino acid phosphorylation // inferred from electronic annotation /// 0007155 // cell adhesion // inferred from electronic annotation /// 0007155 // cell adhesion // traceable author statement /// 0007169 // transmembrane receptor protein tyrosine kinase signaling pathway // inferred from electronic annotation', '0006260 // DNA replication // inferred from electronic annotation', '0006457 // protein folding // inferred from electronic annotation /// 0006986 // response to unfolded protein // traceable author statement /// 0006986 // response to unfolded protein // inferred from electronic annotation', '0001656 // metanephros development // inferred from electronic annotation /// 0006183 // GTP biosynthesis // inferred from electronic annotation /// 0006228 // UTP biosynthesis // inferred from electronic annotation /// 0006241 // CTP biosynthesis // inferred from electronic annotation /// 0006350 // transcription // inferred from electronic annotation /// 0009887 // organ morphogenesis // inferred from electronic annotation /// 0030154 // cell differentiation // inferred from electronic annotation /// 0045893 // positive regulation of transcription, DNA-dependent // inferred from sequence or structural similarity /// 0006355 // regulation of transcription, DNA-dependent // inferred from electronic annotation /// 0007275 // development // inferred from electronic annotation /// 0009653 // morphogenesis // traceable author statement', '0007165 // signal transduction // non-traceable author statement /// 0007601 // visual perception // traceable author statement /// 0050896 // response to stimulus // inferred from electronic annotation /// 0007601 // visual perception // inferred from electronic annotation'], 'Gene Ontology Cellular Component': ['0005615 // extracellular space // inferred from electronic annotation /// 0005887 // integral to plasma membrane // traceable author statement /// 0016020 // membrane // inferred from electronic annotation /// 0016021 // integral to membrane // inferred from electronic annotation', '0005634 // nucleus // inferred from electronic annotation /// 0005663 // DNA replication factor C complex // traceable author statement /// 0005663 // DNA replication factor C complex // inferred from electronic annotation', nan, '0005634 // nucleus // inferred from electronic annotation /// 0005654 // nucleoplasm // inferred from sequence or structural similarity /// 0005667 // transcription factor complex // inferred from electronic annotation', nan], 'Gene Ontology Molecular Function': ['0000166 // nucleotide binding // inferred from electronic annotation /// 0004674 // protein serine/threonine kinase activity // inferred from electronic annotation /// 0004713 // protein-tyrosine kinase activity // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // traceable author statement /// 0004872 // receptor activity // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation /// 0016740 // transferase activity // inferred from electronic annotation /// 0004672 // protein kinase activity // inferred from electronic annotation /// 0016301 // kinase activity // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0005524 // ATP binding // traceable author statement /// 0017111 // nucleoside-triphosphatase activity // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation', '0003700 // transcription factor activity // traceable author statement /// 0004550 // nucleoside diphosphate kinase activity // inferred from electronic annotation /// 0004996 // thyroid-stimulating hormone receptor activity // traceable author statement /// 0005515 // protein binding // inferred from sequence or structural similarity /// 0005524 // ATP binding // inferred from electronic annotation /// 0016563 // transcriptional activator activity // inferred from sequence or structural similarity /// 0003677 // DNA binding // inferred from electronic annotation', '0005509 // calcium ion binding // inferred from electronic annotation /// 0008048 // calcium sensitive guanylate cyclase activator activity // traceable author statement']}\n" ] } ], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "try:\n", " # Use the correct variable name from previous steps\n", " gene_annotation = get_gene_annotation(soft_file_path)\n", " \n", " # 2. Preview the gene annotation dataframe\n", " print(\"Gene annotation preview:\")\n", " print(preview_df(gene_annotation))\n", " \n", "except UnicodeDecodeError as e:\n", " print(f\"Unicode decoding error: {e}\")\n", " print(\"Trying alternative approach...\")\n", " \n", " # Read the file with Latin-1 encoding which is more permissive\n", " import gzip\n", " import pandas as pd\n", " \n", " # Manually read the file line by line with error handling\n", " data_lines = []\n", " with gzip.open(soft_file_path, 'rb') as f:\n", " for line in f:\n", " # Skip lines starting with prefixes we want to filter out\n", " line_str = line.decode('latin-1')\n", " if not line_str.startswith('^') and not line_str.startswith('!') and not line_str.startswith('#'):\n", " data_lines.append(line_str)\n", " \n", " # Create dataframe from collected lines\n", " if data_lines:\n", " gene_data_str = '\\n'.join(data_lines)\n", " gene_annotation = pd.read_csv(pd.io.common.StringIO(gene_data_str), sep='\\t', low_memory=False)\n", " print(\"Gene annotation preview (alternative method):\")\n", " print(preview_df(gene_annotation))\n", " else:\n", " print(\"No valid gene annotation data found after filtering.\")\n", " gene_annotation = pd.DataFrame()\n", " \n", "except Exception as e:\n", " print(f\"Error extracting gene annotation data: {e}\")\n", " gene_annotation = pd.DataFrame()\n" ] }, { "cell_type": "markdown", "id": "c4ee6ea9", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "5011c7b2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:23.325603Z", "iopub.status.busy": "2025-03-25T04:08:23.325490Z", "iopub.status.idle": "2025-03-25T04:08:23.456035Z", "shell.execute_reply": "2025-03-25T04:08:23.455686Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Mapping from probe column 'ID' to gene symbol column 'Gene Symbol'\n", "Created gene mapping dataframe with shape: (21248, 2)\n", "First few rows of gene mapping:\n", " ID Gene\n", "0 1007_s_at DDR1\n", "1 1053_at RFC2\n", "2 117_at HSPA6\n", "3 121_at PAX8\n", "4 1255_g_at GUCA1A\n", "Converted gene expression data shape: (13046, 48)\n", "First few genes:\n", "Index(['A2BP1', 'A2M', 'A4GALT', 'A4GNT', 'AAAS', 'AACS', 'AADAC', 'AAK1',\n", " 'AAMP', 'AANAT'],\n", " dtype='object', name='Gene')\n", "\n", "Preview of gene expression data (first 3 genes, first 3 samples):\n", " GSM402192 GSM402193 GSM402194\n", "Gene \n", "A2BP1 6.238140 6.330799 6.347286\n", "A2M 7.105478 5.999013 5.652930\n", "A4GALT 5.835901 5.981849 5.896369\n" ] } ], "source": [ "# 1. Identify columns containing gene identifiers and gene symbols\n", "probe_col = \"ID\" # Column in annotation that matches the gene expression data index\n", "gene_col = \"Gene Symbol\" # Column containing gene symbols\n", "\n", "print(f\"Mapping from probe column '{probe_col}' to gene symbol column '{gene_col}'\")\n", "\n", "# 2. Create gene mapping dataframe using the library function\n", "gene_mapping = get_gene_mapping(gene_annotation, probe_col, gene_col)\n", "print(f\"Created gene mapping dataframe with shape: {gene_mapping.shape}\")\n", "print(\"First few rows of gene mapping:\")\n", "print(gene_mapping.head())\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene-level expression\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(f\"Converted gene expression data shape: {gene_data.shape}\")\n", "print(\"First few genes:\")\n", "print(gene_data.index[:10])\n", "\n", "# Optional: Preview a small subset of the gene expression data\n", "print(\"\\nPreview of gene expression data (first 3 genes, first 3 samples):\")\n", "if not gene_data.empty:\n", " print(gene_data.iloc[:3, :3])\n" ] }, { "cell_type": "markdown", "id": "fe5523e9", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "4c276144", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:23.457419Z", "iopub.status.busy": "2025-03-25T04:08:23.457290Z", "iopub.status.idle": "2025-03-25T04:08:28.683577Z", "shell.execute_reply": "2025-03-25T04:08:28.683195Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data shape: (12700, 48)\n", "First few normalized gene symbols: ['A2M', 'A4GALT', 'A4GNT', 'AAAS', 'AACS', 'AADAC', 'AAK1', 'AAMDC', 'AAMP', 'AANAT']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Telomere_Length/gene_data/GSE16058.csv\n", "Loaded clinical data with shape: (1, 48)\n", "Linked data shape: (48, 12701)\n", "Linked data column count: 12701\n", "First few columns of linked data: ['Telomere_Length', 'A2M', 'A4GALT', 'A4GNT', 'AAAS', 'AACS', 'AADAC', 'AAK1', 'AAMDC', 'AAMP']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape after handling missing values: (48, 12701)\n", "For the feature 'Telomere_Length', the least common label is '1.0' with 11 occurrences. This represents 22.92% of the dataset.\n", "The distribution of the feature 'Telomere_Length' in this dataset is fine.\n", "\n", "Is trait biased: False\n", "Linked data shape after removing biased features: (48, 12701)\n", "A new JSON file was created at: ../../output/preprocess/Telomere_Length/cohort_info.json\n", "Data quality check result: Usable\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Telomere_Length/GSE16058.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the obtained gene expression data using the provided function\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n", "print(f\"First few normalized gene symbols: {list(normalized_gene_data.index[:10])}\")\n", "\n", "# Save the normalized gene data to CSV\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 data saved to {out_gene_data_file}\")\n", "\n", "# 2. Load the clinical data that was already extracted and saved in a previous step\n", "try:\n", " clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)\n", " print(f\"Loaded clinical data with shape: {clinical_df.shape}\")\n", "except FileNotFoundError:\n", " print(\"Clinical data file not found. Using data from previous steps.\")\n", " # Get the clinical data from a previous step if we can't load it\n", " clinical_df = clinical_data \n", "\n", "# 3. Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_df, normalized_gene_data)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(f\"Linked data column count: {len(linked_data.columns)}\")\n", "print(f\"First few columns of linked data: {linked_data.columns[:10].tolist()}\")\n", "\n", "# 4. 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", "# 5. Determine whether the trait and demographic features are biased\n", "is_trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "print(f\"Is trait biased: {is_trait_biased}\")\n", "print(f\"Linked data shape after removing biased features: {linked_data.shape}\")\n", "\n", "# 6. Conduct quality check and save the cohort information\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True, \n", " cohort=cohort, \n", " info_path=json_path, \n", " is_gene_available=True, \n", " is_trait_available=True,\n", " is_biased=is_trait_biased, \n", " df=linked_data,\n", " note=\"Dataset contains gene expression from mammary epithelial cells at different passage levels including prestasis, intermediate, post selection and agonesence stages. Telomere length is inferred from growth status.\"\n", ")\n", "\n", "# 7. Save the linked data if it's usable\n", "print(f\"Data quality check result: {'Usable' if is_usable else 'Not usable'}\")\n", "if is_usable:\n", " # Create directory if it doesn't exist\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(f\"Data not saved due to quality issues.\")" ] } ], "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 }