{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "fa335e05", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:01:27.219060Z", "iopub.status.busy": "2025-03-25T06:01:27.218869Z", "iopub.status.idle": "2025-03-25T06:01:27.379701Z", "shell.execute_reply": "2025-03-25T06:01:27.379278Z" } }, "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 = \"Osteoporosis\"\n", "cohort = \"GSE51495\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Osteoporosis\"\n", "in_cohort_dir = \"../../input/GEO/Osteoporosis/GSE51495\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Osteoporosis/GSE51495.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Osteoporosis/gene_data/GSE51495.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Osteoporosis/clinical_data/GSE51495.csv\"\n", "json_path = \"../../output/preprocess/Osteoporosis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "0f57fa35", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "09d7af00", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:01:27.381148Z", "iopub.status.busy": "2025-03-25T06:01:27.380997Z", "iopub.status.idle": "2025-03-25T06:01:27.447880Z", "shell.execute_reply": "2025-03-25T06:01:27.447484Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Peripheral blood mononuclear cell- and cortical bone-derived transcriptional profiles\"\n", "!Series_summary\t\"Large-scale transcriptional profiling has enormous potential for discovery of osteoporosis susceptibility genes and for identification of the molecular mechanisms by which these genes and associated pathways regulate bone maintenance and turnover. A potential challenge in the use of this method for the discovery of osteoporosis genes is the difficulty of obtaining bone tissue samples from large numbers of individuals. In this study, we tested the applicability of using peripheral blood mononuclear cell (PBMC)-derived transcriptional profiles as a surrogate to cortical bone transcriptional profiles to address questions of skeletal genetics. We used a well-established and genetically well-characterized nonhuman primate model for human bone maintenance and turnover. We determined that a high degree of overlap exists in gene expression of cortical bone and PBMCs and that genes in both the osteoporosis-associated RANK Osteoclast and Estrogen Receptor Signaling pathways are highly expressed in PBMCs. Genes within the Wnt Signaling pathway, also implicated in osteoporosis pathobiology, are expressed in PBMCs, albeit to a lesser extent. These results are the first in an effort to comprehensively characterize the relationship between the PBMC transcriptome and bone – knowledge that is essential for maximizing the use of PBMCs to identify genes and signaling pathways relevant to osteoporosis pathogenesis. It is also a first step in identifying genes that correlate in a predictable manner between PBMCs and cortical bone from healthy and osteoporotic individuals, potentially allowing us to identify genes that could be used to diagnose osteoporosis prior to detectible bone loss and with easily obtained PBMCs.\"\n", "!Series_overall_design\t\"Total RNA was isolated from peripheral blood mononuclear cells and cortical bone of a nonhuman primate model (Papio hamadryas ssp.) of bone maintenance and turnover. Both samples were taken from the same animal. Tissue from 15 animals was used for the study.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['gender: female', 'gender: male'], 1: ['age (yrs): 11.24', 'age (yrs): 14.15', 'age (yrs): 14.03', 'age (yrs): 19.16', 'age (yrs): 16.66', 'age (yrs): 18.26', 'age (yrs): 17.59', 'age (yrs): 12.51', 'age (yrs): 13.53', 'age (yrs): 12.06', 'age (yrs): 15.08', 'age (yrs): 14.46', 'age (yrs): 20.18', 'age (yrs): 21.95', 'age (yrs): 27.34'], 2: ['tissue: Baboon cortical bone', 'tissue: Baboon Peripheral blood mononuclear cells']}\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": "c6657262", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "121a1a96", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:01:27.448965Z", "iopub.status.busy": "2025-03-25T06:01:27.448857Z", "iopub.status.idle": "2025-03-25T06:01:27.459909Z", "shell.execute_reply": "2025-03-25T06:01:27.459533Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Available variables for this step: dict_keys(['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__builtin__', '__builtins__', '_ih', '_oh', '_dh', 'In', 'Out', 'get_ipython', 'exit', 'quit', 'open', '_', '__', '___', '_i', '_ii', '_iii', '_i1', 'sys', 'os', 'gzip', 'io', 'json', 're', 'Callable', 'Optional', 'List', 'Tuple', 'Dict', 'Union', 'Any', 'pd', 'geo_get_relevant_filepaths', 'tcga_get_relevant_filepaths', 'line_generator', 'filter_content_by_prefix', 'get_background_and_clinical_data', 'get_gene_annotation', 'get_gene_mapping', 'get_genetic_data', 'extract_human_gene_symbols', 'apply_gene_mapping', 'normalize_gene_symbols_in_index', 'get_feature_data', 'judge_binary_variable_biased', 'judge_continuous_variable_biased', 'tcga_convert_trait', 'tcga_convert_gender', 'tcga_convert_age', 'get_unique_values_by_row', 'tcga_select_clinical_features', 'geo_select_clinical_features', 'geo_link_clinical_genetic_data', 'handle_missing_values', 'judge_and_remove_biased_features', 'validate_and_save_cohort_info', 'preview_df', 'trait', 'cohort', 'in_trait_dir', 'in_cohort_dir', 'out_data_file', 'out_gene_data_file', 'out_clinical_data_file', 'json_path', '_i2', 'soft_file', 'matrix_file', 'background_prefixes', 'clinical_prefixes', 'background_info', 'clinical_data', 'sample_characteristics_dict', '_i3', 'is_gene_available', 'trait_row', 'age_row', 'gender_row', 'convert_trait', 'convert_age', 'convert_gender', 'is_trait_available'])\n", "Preview of selected clinical features:\n", "{'GSM1246535': [1.0, 11.24, 0.0], 'GSM1246536': [1.0, 14.15, 0.0], 'GSM1246537': [1.0, 14.03, 0.0], 'GSM1246538': [1.0, 19.16, 0.0], 'GSM1246539': [1.0, 16.66, 0.0], 'GSM1246540': [1.0, 18.26, 0.0], 'GSM1246541': [1.0, 17.59, 0.0], 'GSM1246542': [1.0, 12.51, 1.0], 'GSM1246543': [1.0, 13.53, 0.0], 'GSM1246544': [1.0, 12.06, 0.0], 'GSM1246545': [1.0, 15.08, 0.0], 'GSM1246546': [1.0, 14.46, 0.0], 'GSM1246547': [1.0, 20.18, 0.0], 'GSM1246548': [1.0, 21.95, 0.0], 'GSM1246549': [1.0, 27.34, 0.0], 'GSM1246550': [0.0, 11.24, 0.0], 'GSM1246551': [0.0, 14.15, 0.0], 'GSM1246552': [0.0, 14.03, 0.0], 'GSM1246553': [0.0, 19.16, 0.0], 'GSM1246554': [0.0, 16.66, 0.0], 'GSM1246555': [0.0, 18.26, 0.0], 'GSM1246556': [0.0, 17.59, 0.0], 'GSM1246557': [0.0, 12.51, 1.0], 'GSM1246558': [0.0, 13.53, 0.0], 'GSM1246559': [0.0, 12.06, 0.0], 'GSM1246560': [0.0, 15.08, 0.0], 'GSM1246561': [0.0, 14.46, 0.0], 'GSM1246562': [0.0, 20.18, 0.0], 'GSM1246563': [0.0, 21.95, 0.0], 'GSM1246564': [0.0, 27.34, 0.0]}\n", "Clinical features saved to ../../output/preprocess/Osteoporosis/clinical_data/GSE51495.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains gene expression data from PBMCs and cortical bone\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For trait (Osteoporosis): No direct trait information in the sample characteristics, but we can infer from tissue type\n", "# Row 2 contains tissue information, which can be used to distinguish bone samples from blood samples\n", "trait_row = 2\n", "\n", "# For age: Row 1 contains age information\n", "age_row = 1\n", "\n", "# For gender: Row 0 contains gender information\n", "gender_row = 0\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert tissue type to binary trait value (bone sample = 1, blood sample = 0)\"\"\"\n", " if value is None:\n", " return None\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # In this dataset, we're interested in bone samples vs. blood samples\n", " # Here we assign 1 to bone samples since they're directly related to osteoporosis\n", " if \"cortical bone\" in value.lower():\n", " return 1\n", " elif \"blood\" in value.lower() or \"pbmc\" in value.lower():\n", " return 0\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age string to floating point number\"\"\"\n", " if value is None:\n", " return None\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " try:\n", " # Extract digits from the age string\n", " age_value = float(re.search(r'\\d+\\.\\d+|\\d+', value).group())\n", " return age_value\n", " except (ValueError, AttributeError):\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender string to binary (female = 0, male = 1)\"\"\"\n", " if value is None:\n", " return None\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip().lower()\n", " \n", " if \"female\" in value:\n", " return 0\n", " elif \"male\" in value:\n", " return 1\n", " return None\n", "\n", "# 3. Save Metadata - Initial Filtering\n", "# Trait data is available based on our inference from tissue type\n", "is_trait_available = trait_row is not None\n", "\n", "# Conduct initial filtering and save metadata\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", " # Load the sample characteristics data from the parent directory\n", " # We need to access the clinical data that was extracted in a previous step\n", " try:\n", " # Assuming clinical_data is already in memory from a previous step\n", " print(\"Available variables for this step:\", locals().keys())\n", " \n", " # Since clinical_data might not be pre-loaded, let's try to import it\n", " # or construct it from available information\n", " import os\n", " import pandas as pd\n", " import re\n", " \n", " # Check if the variable 'clinical_data' is defined in the previous step\n", " if 'clinical_data' not in locals():\n", " # We need to construct clinical_data based on the sample characteristics\n", " # Using the information provided in the previous step output\n", " sample_chars = {\n", " 0: ['gender: female', 'gender: male'],\n", " 1: ['age (yrs): 11.24', 'age (yrs): 14.15', 'age (yrs): 14.03', 'age (yrs): 19.16', \n", " 'age (yrs): 16.66', 'age (yrs): 18.26', 'age (yrs): 17.59', 'age (yrs): 12.51', \n", " 'age (yrs): 13.53', 'age (yrs): 12.06', 'age (yrs): 15.08', 'age (yrs): 14.46', \n", " 'age (yrs): 20.18', 'age (yrs): 21.95', 'age (yrs): 27.34'],\n", " 2: ['tissue: Baboon cortical bone', 'tissue: Baboon Peripheral blood mononuclear cells']\n", " }\n", " \n", " # Create a DataFrame from the sample characteristics\n", " clinical_data = pd.DataFrame(sample_chars)\n", " \n", " # Extract clinical features\n", " selected_features = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the extracted features\n", " preview = preview_df(selected_features)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Save the extracted clinical features\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_features.to_csv(out_clinical_data_file)\n", " print(f\"Clinical features saved to {out_clinical_data_file}\")\n", " \n", " except Exception as e:\n", " print(f\"Error in clinical feature extraction: {e}\")\n", " print(\"Skipping clinical feature extraction due to data access issues.\")\n" ] }, { "cell_type": "markdown", "id": "506a694a", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "915da709", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:01:27.461068Z", "iopub.status.busy": "2025-03-25T06:01:27.460794Z", "iopub.status.idle": "2025-03-25T06:01:27.539501Z", "shell.execute_reply": "2025-03-25T06:01:27.538896Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Index(['ILMN_1343291', 'ILMN_1343292', 'ILMN_1343293', 'ILMN_1343294',\n", " 'ILMN_1651209', 'ILMN_1651217', 'ILMN_1651228', 'ILMN_1651229',\n", " 'ILMN_1651234', 'ILMN_1651235', 'ILMN_1651236', 'ILMN_1651237',\n", " 'ILMN_1651238', 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260',\n", " 'ILMN_1651261', 'ILMN_1651262', 'ILMN_1651268', 'ILMN_1651278'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.\n", "print(gene_data.index[:20])\n" ] }, { "cell_type": "markdown", "id": "fc76e19d", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "35d28695", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:01:27.540832Z", "iopub.status.busy": "2025-03-25T06:01:27.540718Z", "iopub.status.idle": "2025-03-25T06:01:27.542918Z", "shell.execute_reply": "2025-03-25T06:01:27.542476Z" } }, "outputs": [], "source": [ "# Examining the gene identifiers in the gene expression data\n", "# The identifiers start with \"ILMN_\" which indicates they are Illumina probe IDs\n", "# These are not standard human gene symbols and will need to be mapped to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "e6441877", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "a434ebb2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:01:27.544197Z", "iopub.status.busy": "2025-03-25T06:01:27.544097Z", "iopub.status.idle": "2025-03-25T06:01:28.899826Z", "shell.execute_reply": "2025-03-25T06:01:28.899162Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['ILMN_1698220', 'ILMN_1810835', 'ILMN_1782944', 'ILMN_1692858', 'ILMN_1668162'], 'Species': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Source': ['RefSeq', 'RefSeq', 'RefSeq', 'RefSeq', 'RefSeq'], 'Search_Key': ['ILMN_13666', 'ILMN_10478', 'ILMN_27850', 'ILMN_10309', 'ILMN_7652'], 'Transcript': ['ILMN_13666', 'ILMN_175835', 'ILMN_27850', 'ILMN_10309', 'ILMN_7652'], 'ILMN_Gene': ['PHTF2', 'SPRR3', 'GPR37L1', 'FBXO25', 'DGAT2L3'], 'Source_Reference_ID': ['NM_020432.2', 'NM_005416.1', 'NM_004767.2', 'NM_012173.3', 'NM_001013579.1'], 'RefSeq_ID': ['NM_020432.2', 'NM_005416.1', 'NM_004767.2', 'NM_012173.3', 'NM_001013579.1'], 'Entrez_Gene_ID': [57157.0, 6707.0, 9283.0, 26260.0, 158833.0], 'GI': [40254932.0, 4885606.0, 31377792.0, 34878756.0, 61888901.0], 'Accession': ['NM_020432.2', 'NM_005416.1', 'NM_004767.2', 'NM_012173.3', 'NM_001013579.1'], 'Symbol': ['PHTF2', 'SPRR3', 'GPR37L1', 'FBXO25', 'DGAT2L3'], 'Protein_Product': ['NP_065165.2', 'NP_005407.1', 'NP_004758.2', 'NP_036305.2', 'NP_001013597.1'], 'Array_Address_Id': [2900438.0, 2640692.0, 1690440.0, 1030747.0, 6480482.0], 'Probe_Type': ['S', 'S', 'S', 'A', 'S'], 'Probe_Start': [4677.0, 683.0, 2372.0, 1937.0, 782.0], 'SEQUENCE': ['CAAAGAGAATTGTGGCAGATGTTGTGTGTGAACTGTTGTTTCTTTGCCAC', 'GAAGCCAACCACCAGATGCTGGACACCCTCTTCCCATCTGTTTCTGTGTC', 'GATCCCTGGGTTGCCCTGTCCCAACCTCCTTGTTAGGTGCTTTCCCATAG', 'CTGGGGTTGGGGGCTGGTCTGTGCATAATCCTGGACTGTGATGGGAACAG', 'GTCAAGGCTCCACTGGGCTCCTGCCATACTCCAGGCCTATTGTCACTGTG'], 'Chromosome': ['7', '1', '1', '8', 'X'], 'Probe_Chr_Orientation': ['+', '+', '+', '+', '+'], 'Probe_Coordinates': ['77424374-77424423', '151242655-151242704', '200365170-200365219', '409448-409497', '69376459-69376508'], 'Definition': ['Homo sapiens putative homeodomain transcription factor 2 (PHTF2), mRNA.', 'Homo sapiens small proline-rich protein 3 (SPRR3), mRNA.', 'Homo sapiens G protein-coupled receptor 37 like 1 (GPR37L1), mRNA.', 'Homo sapiens F-box protein 25 (FBXO25), transcript variant 3, mRNA.', 'Homo sapiens diacylglycerol O-acyltransferase 2-like 3 (DGAT2L3), mRNA.'], 'Ontology_Component': ['endoplasmic reticulum [goid 5783] [pmid 11256614] [evidence IDA]', 'cornified envelope [goid 1533] [pmid 15232223] [evidence TAS]', 'membrane [goid 16020] [evidence IEA]; integral to membrane [goid 16021] [pmid 9539149] [evidence NAS]', 'ubiquitin ligase complex [goid 151] [pmid 10531035] [evidence NAS]', 'membrane [goid 16020] [evidence IEA]; integral to membrane [goid 16021] [evidence IEA]; endoplasmic reticulum [goid 5783] [evidence IEA]'], 'Ontology_Process': [nan, 'keratinocyte differentiation [goid 30216] [pmid 8325635] [evidence NAS]; wound healing [goid 42060] [pmid 10510474] [evidence TAS]; epidermis development [goid 8544] [pmid 8325635] [evidence NAS]; keratinization [goid 31424] [evidence IEA]', 'G-protein coupled receptor protein signaling pathway [goid 7186] [evidence IEA]; signal transduction [goid 7165] [evidence IEA]', 'protein ubiquitination [goid 16567] [pmid 10531035] [evidence NAS]', 'lipid biosynthesis [goid 8610] [evidence IEA]; lipid metabolism [goid 6629] [evidence IEA]'], 'Ontology_Function': [nan, 'structural molecule activity [goid 5198] [pmid 15232223] [evidence TAS]; protein binding [goid 5515] [pmid 10510474] [evidence IPI]', 'receptor activity [goid 4872] [evidence IEA]; G-protein coupled receptor activity, unknown ligand [goid 16526] [pmid 9539149] [evidence NAS]; rhodopsin-like receptor activity [goid 1584] [evidence IEA]', 'ubiquitin-protein ligase activity [goid 4842] [pmid 10531035] [evidence NAS]', 'acyltransferase activity [goid 8415] [evidence IEA]; transferase activity [goid 16740] [evidence IEA]'], 'Synonyms': ['DKFZP564F013; FLJ33324; MGC86999', nan, 'ET(B)R-LP-2; ETBR-LP-2', 'MGC51975; MGC20256; FBX25', 'AWAT1; DGA2'], 'GB_ACC': ['NM_020432.2', 'NM_005416.1', 'NM_004767.2', 'NM_012173.3', 'NM_001013579.1']}\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. Use the 'preview_df' function from the library to preview the data and print out the results.\n", "print(\"Gene annotation preview:\")\n", "print(preview_df(gene_annotation))\n" ] }, { "cell_type": "markdown", "id": "0c602d62", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "5d0b09a4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:01:28.901299Z", "iopub.status.busy": "2025-03-25T06:01:28.901167Z", "iopub.status.idle": "2025-03-25T06:01:28.993394Z", "shell.execute_reply": "2025-03-25T06:01:28.992766Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data after mapping to gene symbols:\n", "(17609, 30)\n", "Index(['A1BG', 'A2BP1', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS',\n", " 'AACS', 'AADAC', 'AADACL1', 'AADACL2', 'AADACL4', 'AADAT', 'AAK1',\n", " 'AAMP', 'AANAT', 'AARS', 'AARS2', 'AARSD1'],\n", " dtype='object', name='Gene')\n" ] } ], "source": [ "# 1. Identify the relevant columns in gene annotation for mapping\n", "# Looking at the previews from previous steps:\n", "# - Gene expression data uses 'ILMN_*' identifiers (Illumina probe IDs)\n", "# - Gene annotation dataframe has 'ID' column with same format identifiers\n", "# - 'Symbol' column contains the gene symbols we need\n", "\n", "# 2. Get the gene mapping dataframe\n", "prob_col = 'ID' # Column containing probe IDs\n", "gene_col = 'Symbol' # Column containing gene symbols\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n", "# The apply_gene_mapping function handles the many-to-many relationships correctly\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "# Preview the first few rows of the mapped gene expression data\n", "print(\"Gene expression data after mapping to gene symbols:\")\n", "print(gene_data.shape)\n", "print(gene_data.index[:20])\n" ] }, { "cell_type": "markdown", "id": "138b3d38", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "94b66995", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:01:28.994933Z", "iopub.status.busy": "2025-03-25T06:01:28.994804Z", "iopub.status.idle": "2025-03-25T06:01:35.555022Z", "shell.execute_reply": "2025-03-25T06:01:35.554161Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Osteoporosis/gene_data/GSE51495.csv\n", "Clinical data saved to ../../output/preprocess/Osteoporosis/clinical_data/GSE51495.csv\n", "Linked data shape: (30, 16994)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "For the feature 'Osteoporosis', the least common label is '1.0' with 15 occurrences. This represents 50.00% of the dataset.\n", "The distribution of the feature 'Osteoporosis' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 13.655\n", " 50% (Median): 15.08\n", " 75%: 18.935000000000002\n", "Min: 11.24\n", "Max: 27.34\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n", "For the feature 'Gender', the least common label is '1.0' with 2 occurrences. This represents 6.67% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is severely biased.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Osteoporosis/GSE51495.csv\n" ] } ], "source": [ "# 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\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", "# Create clinical features directly from clinical_data using the conversion functions defined earlier\n", "clinical_features_df = geo_select_clinical_features(\n", " 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", "# Save the clinical data\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "clinical_features_df.to_csv(out_clinical_data_file)\n", "print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "\n", "# Now link the clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_features_df, normalized_gene_data)\n", "print(\"Linked data shape:\", linked_data.shape)\n", "\n", "# Handle missing values in the linked data\n", "linked_data = handle_missing_values(linked_data, trait)\n", "\n", "# 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.\n", "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# 5. 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=unbiased_linked_data,\n", " note=\"This is an HPV-transformed keratinocyte cell line study focusing on transformation stages: 1 for anchorage independent (more advanced cancer stage), 0 for earlier stages.\"\n", ")\n", "\n", "# 6. If the linked data is usable, save it as a CSV file to 'out_data_file'.\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Data was determined to be unusable and was not 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 }