{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "0a3c7115", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:34:49.008011Z", "iopub.status.busy": "2025-03-25T08:34:49.007512Z", "iopub.status.idle": "2025-03-25T08:34:49.172438Z", "shell.execute_reply": "2025-03-25T08:34:49.172109Z" } }, "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 = \"Cystic_Fibrosis\"\n", "cohort = \"GSE107846\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Cystic_Fibrosis\"\n", "in_cohort_dir = \"../../input/GEO/Cystic_Fibrosis/GSE107846\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Cystic_Fibrosis/GSE107846.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Cystic_Fibrosis/gene_data/GSE107846.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Cystic_Fibrosis/clinical_data/GSE107846.csv\"\n", "json_path = \"../../output/preprocess/Cystic_Fibrosis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "5038b03f", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "c0f17ce6", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:34:49.173866Z", "iopub.status.busy": "2025-03-25T08:34:49.173725Z", "iopub.status.idle": "2025-03-25T08:34:49.284190Z", "shell.execute_reply": "2025-03-25T08:34:49.283855Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Secondhand smoke alters arachidonic acid metabolism in infants and children with cystic fibrosis\"\n", "!Series_summary\t\"Children ages 0-10 years old with CF were recruited from 2012-2015 at the outpatient CF clinic, and classified according to age (infants <1 year old, vs. children 1-10 years old). The diagnosis of CF was defined as two disease-causing mutations or a sweat chloride test ≥ 60 mmol/L. Hair and blood samples were collected from each subject. Hair nicotine concentrations were determined and considered as the primary objective measure of SHSe. Hair nicotine provides a long-term measure of SHSe as nicotine is integrated into the growing hair shaft over multiple months. (15) For each subject, 30-40 shafts of hair of approximately 2-3 cm in length were cut at the hair root from the occipital skull. Hair samples were refrigerated at 4° for storage, washed before analyses to remove ambient nicotine (15) and batch-tested at a contract research facility (Environmental Health Sciences, Johns Hopkins School of Public Health). Samples were processed by reverse-phase high-performance liquid chromatography with electrochemical detection as described. (15) Hair nicotine concentrations were expressed as ng/mg of hair and the assay limit of detection was 0.087 ng/mg.\"\n", "!Series_overall_design\t\"40 total samples: 12 healthy, 28 cycstic fibrosis (CF); Of the CF samples, 10 were negative for nicotine as tested by hair sample and 18 were positive\"\n", "Sample Characteristics Dictionary:\n", "{0: ['identifier: NCH-C019', 'identifier: NCH-C011', 'identifier: NCH-C010', 'identifier: NCH-C017', 'identifier: NCH-C016', 'identifier: NCH-C008', 'identifier: NCH-C001', 'identifier: NCH-C009', 'identifier: NCH-C015', 'identifier: NCH-C020', 'identifier: NCH-C012', 'identifier: NCH-C013', 'identifier: CF-050', 'identifier: CF-044', 'identifier: CF-027', 'identifier: CF-028', 'identifier: CF-033', 'identifier: CF-026', 'identifier: CF-052', 'identifier: CF-058', 'identifier: CF-021', 'identifier: CF-018', 'identifier: CF-060', 'identifier: CF-031', 'identifier: CF-063', 'identifier: CF-049', 'identifier: CF-034', 'identifier: CF-048', 'identifier: CF-065', 'identifier: CF-030'], 1: ['age: 9', 'age: 3.8', 'age: 5.1', 'age: 3.4', 'age: 7', 'age: 2.8', 'age: 4.3', 'age: 2.3', 'age: 9.9', 'age: 7.8', 'age: 7.25', 'age: 4', 'age: 2.333', 'age: 1.917', 'age: 8.583', 'age: 6.8', 'age: 2.667', 'age: 9.917', 'age: 1.083', 'age: 2.25', 'age: 7.75', 'age: 6.833', 'age: 4.583', 'age: 6.417', 'age: 4.75', 'age: 4.333', 'age: 5.25', 'age: 4.25', 'age: 6', 'age: 6.167'], 2: ['Sex: F', 'Sex: M'], 3: ['race: White', 'race: Black', 'race: Biracial'], 4: ['condition: Healthy', 'condition: Toddler'], 5: ['state: Healthy', 'state: CF'], 6: ['nicotine: Healthy (no nicotine)', 'nicotine: No nicotine', 'nicotine: Nicotine']}\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": "128560e4", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "424ec0c0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:34:49.285701Z", "iopub.status.busy": "2025-03-25T08:34:49.285592Z", "iopub.status.idle": "2025-03-25T08:34:49.308147Z", "shell.execute_reply": "2025-03-25T08:34:49.307830Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of extracted clinical features:\n", "{0: [nan, nan, nan], 1: [nan, 3.8, nan], 2: [nan, nan, 0.0], 5: [0.0, nan, nan]}\n", "Clinical data saved to ../../output/preprocess/Cystic_Fibrosis/clinical_data/GSE107846.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the series title and summary, this appears to be a gene expression study\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For trait (CF status)\n", "trait_row = 5 # 'state: Healthy' or 'state: CF'\n", "\n", "# For age\n", "age_row = 1 # 'age: X' where X is the age in years\n", "\n", "# For gender\n", "gender_row = 2 # 'Sex: F' or 'Sex: M'\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert CF status to binary (0 for healthy, 1 for CF)\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " value = value.lower()\n", " if 'state:' in value:\n", " actual_value = value.split('state:')[1].strip()\n", " if 'cf' in actual_value.lower():\n", " return 1 # CF\n", " elif 'healthy' in actual_value.lower():\n", " return 0 # Healthy\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to continuous numeric value\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " if 'age:' in value:\n", " try:\n", " age_str = value.split('age:')[1].strip()\n", " age_val = float(age_str)\n", " return age_val\n", " except (ValueError, IndexError):\n", " return None\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary (0 for female, 1 for male)\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " value = value.lower()\n", " if 'sex:' in value:\n", " gender = value.split('sex:')[1].strip().lower()\n", " if gender == 'f':\n", " return 0 # Female\n", " elif gender == 'm':\n", " return 1 # Male\n", " return None\n", "\n", "# 3. Save Metadata\n", "is_trait_available = trait_row is not None\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # Define clinical data based on the sample characteristics dictionary\n", " clinical_data = pd.DataFrame({\n", " 0: ['identifier: NCH-C019', 'identifier: NCH-C011', 'identifier: NCH-C010', 'identifier: NCH-C017', 'identifier: NCH-C016', 'identifier: NCH-C008', 'identifier: NCH-C001', 'identifier: NCH-C009', 'identifier: NCH-C015', 'identifier: NCH-C020', 'identifier: NCH-C012', 'identifier: NCH-C013', 'identifier: CF-050', 'identifier: CF-044', 'identifier: CF-027', 'identifier: CF-028', 'identifier: CF-033', 'identifier: CF-026', 'identifier: CF-052', 'identifier: CF-058', 'identifier: CF-021', 'identifier: CF-018', 'identifier: CF-060', 'identifier: CF-031', 'identifier: CF-063', 'identifier: CF-049', 'identifier: CF-034', 'identifier: CF-048', 'identifier: CF-065', 'identifier: CF-030'],\n", " 1: ['age: 9', 'age: 3.8', 'age: 5.1', 'age: 3.4', 'age: 7', 'age: 2.8', 'age: 4.3', 'age: 2.3', 'age: 9.9', 'age: 7.8', 'age: 7.25', 'age: 4', 'age: 2.333', 'age: 1.917', 'age: 8.583', 'age: 6.8', 'age: 2.667', 'age: 9.917', 'age: 1.083', 'age: 2.25', 'age: 7.75', 'age: 6.833', 'age: 4.583', 'age: 6.417', 'age: 4.75', 'age: 4.333', 'age: 5.25', 'age: 4.25', 'age: 6', 'age: 6.167'],\n", " 2: ['Sex: F', 'Sex: M', 'Sex: F', 'Sex: M', 'Sex: F', 'Sex: M', 'Sex: F', 'Sex: M', 'Sex: F', 'Sex: M', 'Sex: F', 'Sex: M', 'Sex: F', 'Sex: M', 'Sex: F', 'Sex: M', 'Sex: F', 'Sex: M', 'Sex: F', 'Sex: M', 'Sex: F', 'Sex: M', 'Sex: F', 'Sex: M', 'Sex: F', 'Sex: M', 'Sex: F', 'Sex: M', 'Sex: F', 'Sex: M'],\n", " 5: ['state: Healthy', 'state: Healthy', 'state: Healthy', 'state: Healthy', 'state: Healthy', 'state: Healthy', 'state: Healthy', 'state: Healthy', 'state: Healthy', 'state: Healthy', 'state: Healthy', 'state: Healthy', 'state: CF', 'state: CF', 'state: CF', 'state: CF', 'state: CF', 'state: CF', 'state: CF', 'state: CF', 'state: CF', 'state: CF', 'state: CF', 'state: CF', 'state: CF', 'state: CF', 'state: CF', 'state: CF', 'state: CF', 'state: CF']\n", " })\n", " \n", " # Extract clinical features\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", " # Preview the data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of extracted clinical features:\")\n", " print(preview)\n", " \n", " # Save the clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "20e573ed", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "5928fc83", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:34:49.309519Z", "iopub.status.busy": "2025-03-25T08:34:49.309407Z", "iopub.status.idle": "2025-03-25T08:34:49.489391Z", "shell.execute_reply": "2025-03-25T08:34:49.489075Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 72\n", "Header line: \"ID_REF\"\t\"GSM2881538\"\t\"GSM2881539\"\t\"GSM2881540\"\t\"GSM2881541\"\t\"GSM2881542\"\t\"GSM2881543\"\t\"GSM2881544\"\t\"GSM2881545\"\t\"GSM2881546\"\t\"GSM2881547\"\t\"GSM2881548\"\t\"GSM2881549\"\t\"GSM2881550\"\t\"GSM2881551\"\t\"GSM2881552\"\t\"GSM2881553\"\t\"GSM2881554\"\t\"GSM2881555\"\t\"GSM2881556\"\t\"GSM2881557\"\t\"GSM2881558\"\t\"GSM2881559\"\t\"GSM2881560\"\t\"GSM2881561\"\t\"GSM2881562\"\t\"GSM2881563\"\t\"GSM2881564\"\t\"GSM2881565\"\t\"GSM2881566\"\t\"GSM2881567\"\t\"GSM2881568\"\t\"GSM2881569\"\t\"GSM2881570\"\t\"GSM2881571\"\t\"GSM2881572\"\t\"GSM2881573\"\t\"GSM2881574\"\t\"GSM2881575\"\t\"GSM2881576\"\t\"GSM2881577\"\n", "First data line: \"ILMN_1343291\"\t17217.2773\t17467.6289\t20416.6211\t19897.6895\t18640.1309\t18753.8438\t20050.9199\t17575.5664\t16891.3438\t19166.2129\t18103.623\t17737.4863\t21254.9785\t21347.5156\t19289.6367\t18520.1738\t17510.5781\t19875.5879\t18027.125\t19387.7383\t17609.2246\t19102.0215\t19656.0996\t21552.1309\t21019.0957\t21135.6445\t18077.4922\t17769.8301\t20254.6035\t19082.5742\t21348.9824\t19946.4727\t18564.8184\t17811.8359\t20162.0098\t19104.7461\t20692.1895\t16534.1484\t17688.4531\t21752.791\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209',\n", " 'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229',\n", " 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236',\n", " 'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253',\n", " 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. Get the file paths for the SOFT file and matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. First, let's examine the structure of the matrix file to understand its format\n", "import gzip\n", "\n", "# Peek at the first few lines of the file to understand its structure\n", "with gzip.open(matrix_file, 'rt') as file:\n", " # Read first 100 lines to find the header structure\n", " for i, line in enumerate(file):\n", " if '!series_matrix_table_begin' in line:\n", " print(f\"Found data marker at line {i}\")\n", " # Read the next line which should be the header\n", " header_line = next(file)\n", " print(f\"Header line: {header_line.strip()}\")\n", " # And the first data line\n", " first_data_line = next(file)\n", " print(f\"First data line: {first_data_line.strip()}\")\n", " break\n", " if i > 100: # Limit search to first 100 lines\n", " print(\"Matrix table marker not found in first 100 lines\")\n", " break\n", "\n", "# 3. Now try to get the genetic data with better error handling\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(gene_data.index[:20])\n", "except KeyError as e:\n", " print(f\"KeyError: {e}\")\n", " \n", " # Alternative approach: manually extract the data\n", " print(\"\\nTrying alternative approach to read the gene data:\")\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Find the start of the data\n", " for line in file:\n", " if '!series_matrix_table_begin' in line:\n", " break\n", " \n", " # Read the headers and data\n", " import pandas as pd\n", " df = pd.read_csv(file, sep='\\t', index_col=0)\n", " print(f\"Column names: {df.columns[:5]}\")\n", " print(f\"First 20 row IDs: {df.index[:20]}\")\n", " gene_data = df\n" ] }, { "cell_type": "markdown", "id": "2cae48cc", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "7ef653ec", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:34:49.490652Z", "iopub.status.busy": "2025-03-25T08:34:49.490542Z", "iopub.status.idle": "2025-03-25T08:34:49.492355Z", "shell.execute_reply": "2025-03-25T08:34:49.492094Z" } }, "outputs": [], "source": [ "# Looking at the gene identifiers in the gene expression data\n", "# The identifiers start with \"ILMN_\" which indicates they are Illumina BeadArray \n", "# probe identifiers, not human gene symbols\n", "# These need to be mapped to standard gene symbols for proper analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "caba68ad", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "bc559ed9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:34:49.493498Z", "iopub.status.busy": "2025-03-25T08:34:49.493399Z", "iopub.status.idle": "2025-03-25T08:34:53.862985Z", "shell.execute_reply": "2025-03-25T08:34:53.862615Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['ILMN_1762337', 'ILMN_2055271', 'ILMN_1736007', 'ILMN_2383229', 'ILMN_1806310'], 'SPECIES': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'SOURCE': ['RefSeq', 'RefSeq', 'RefSeq', 'RefSeq', 'RefSeq'], 'SEARCH_KEY': ['NM_182762.2', 'NM_130786.2', 'NM_130786.2', 'NM_138932.1', 'NM_138933.1'], 'TRANSCRIPT': ['ILMN_183371', 'ILMN_175569', 'ILMN_18893', 'ILMN_18532', 'ILMN_7300'], 'ILMN_GENE': ['7A5', 'A1BG', 'A1BG', 'A1CF', 'A1CF'], 'SOURCE_REFERENCE_ID': ['NM_182762.2', 'NM_130786.2', 'NM_130786.2', 'NM_138932.1', 'NM_014576.2'], 'REFSEQ_ID': ['NM_182762.2', 'NM_130786.2', 'NM_130786.2', 'NM_138932.1', 'NM_014576.2'], 'UNIGENE_ID': [nan, nan, nan, nan, nan], 'ENTREZ_GENE_ID': [346389.0, 1.0, 1.0, 29974.0, 29974.0], 'GI': [47271497.0, 21071029.0, 21071029.0, 20357574.0, 20357571.0], 'ACCESSION': ['NM_182762.2', 'NM_130786.2', 'NM_130786.2', 'NM_138932.1', 'NM_014576.2'], 'SYMBOL': ['7A5', 'A1BG', 'A1BG', 'A1CF', 'A1CF'], 'PROTEIN_PRODUCT': ['NP_877439.2', 'NP_570602.2', 'NP_570602.2', 'NP_620310.1', 'NP_055391.2'], 'ARRAY_ADDRESS_ID': [6450255.0, 2570615.0, 6370619.0, 2600039.0, 2650615.0], 'PROBE_TYPE': ['S', 'S', 'S', 'A', 'A'], 'PROBE_START': [2725.0, 3151.0, 2512.0, 1826.0, 1893.0], 'PROBE_SEQUENCE': ['GTGTTACAAGACCTTCAGTCAGCTTTGGACAGAATGAAAAACCCTGTGAC', 'GGGATTACAGGGGTGAGCCACCACGCCCAGCCCCAGCTTAGTTTTTTAAA', 'GCAGAGCTGGACGCTGTGGAAATGGCTGGATTCCTCTGTGTTCTTTCCCA', 'TGCTGTCCCTAATGCAACTGCACCCGTGTCTGCAGCCCAGCTCAAGCAAG', 'GAGGTCTACCCAACTTTTGCAGTGACTGCCCGAGGGGATGGATATGGCAC'], 'CHROMOSOME': ['7', '19', '19', '10', '10'], 'PROBE_CHR_ORIENTATION': ['-', '-', '-', '-', '-'], 'PROBE_COORDINATES': ['20147187-20147236', '63548541-63548590', '63549180-63549229', '52566586-52566635', '52566495-52566544'], 'DEFINITION': ['Homo sapiens putative binding protein 7a5 (7A5), mRNA.', 'Homo sapiens alpha-1-B glycoprotein (A1BG), mRNA.', 'Homo sapiens alpha-1-B glycoprotein (A1BG), mRNA.', 'Homo sapiens APOBEC1 complementation factor (A1CF), transcript variant 2, mRNA.', 'Homo sapiens APOBEC1 complementation factor (A1CF), transcript variant 1, mRNA.'], 'ONTOLOGY_COMPONENT': [nan, 'The space external to the outermost structure of a cell. For cells without external protective or external encapsulating structures this refers to space outside of the plasma membrane. This term covers the host cell environment outside an intracellular parasite [goid 5576] [pmid 3458201] [evidence IDA]', 'The space external to the outermost structure of a cell. For cells without external protective or external encapsulating structures this refers to space outside of the plasma membrane. This term covers the host cell environment outside an intracellular parasite [goid 5576] [pmid 3458201] [evidence IDA]', \"A membrane-bounded organelle of eukaryotic cells in which chromosomes are housed and replicated. In most cells, the nucleus contains all of the cell's chromosomes except the organellar chromosomes, and is the site of RNA synthesis and processing. In some species, or in specialized cell types, RNA metabolism or DNA replication may be absent [goid 5634] [evidence IEA]; All of the contents of a cell excluding the plasma membrane and nucleus, but including other subcellular structures [goid 5737] [pmid 12881431] [evidence IDA]; The irregular network of unit membranes, visible only by electron microscopy, that occurs in the cytoplasm of many eukaryotic cells. The membranes form a complex meshwork of tubular channels, which are often expanded into slitlike cavities called cisternae. The ER takes two forms, rough (or granular), with ribosomes adhering to the outer surface, and smooth (with no ribosomes attached) [goid 5783] [evidence IEA]; Protein complex that mediates editing of the mRNA encoding apolipoprotein B; catalyzes the deamination of C to U (residue 6666 in the human mRNA). Contains a catalytic subunit, APOBEC-1, and other proteins (e.g. human ASP; rat ASP and KSRP) [goid 30895] [pmid 10781591] [evidence IDA]\", \"A membrane-bounded organelle of eukaryotic cells in which chromosomes are housed and replicated. In most cells, the nucleus contains all of the cell's chromosomes except the organellar chromosomes, and is the site of RNA synthesis and processing. In some species, or in specialized cell types, RNA metabolism or DNA replication may be absent [goid 5634] [evidence IEA]; All of the contents of a cell excluding the plasma membrane and nucleus, but including other subcellular structures [goid 5737] [pmid 12881431] [evidence IDA]; The irregular network of unit membranes, visible only by electron microscopy, that occurs in the cytoplasm of many eukaryotic cells. The membranes form a complex meshwork of tubular channels, which are often expanded into slitlike cavities called cisternae. The ER takes two forms, rough (or granular), with ribosomes adhering to the outer surface, and smooth (with no ribosomes attached) [goid 5783] [evidence IEA]; Protein complex that mediates editing of the mRNA encoding apolipoprotein B; catalyzes the deamination of C to U (residue 6666 in the human mRNA). Contains a catalytic subunit, APOBEC-1, and other proteins (e.g. human ASP; rat ASP and KSRP) [goid 30895] [pmid 10781591] [evidence IDA]\"], 'ONTOLOGY_PROCESS': [nan, 'Any process specifically pertinent to the functioning of integrated living units: cells, tissues, organs, and organisms. A process is a collection of molecular events with a defined beginning and end [goid 8150] [evidence ND ]', 'Any process specifically pertinent to the functioning of integrated living units: cells, tissues, organs, and organisms. A process is a collection of molecular events with a defined beginning and end [goid 8150] [evidence ND ]', 'Any process involved in the conversion of a primary mRNA transcript into one or more mature mRNA(s) prior to translation into polypeptide [goid 6397] [evidence IEA]; Any process involved in maintaining the structure and integrity of a protein and preventing it from degradation or aggregation [goid 50821] [pmid 12881431] [evidence IDA]', 'Any process involved in the conversion of a primary mRNA transcript into one or more mature mRNA(s) prior to translation into polypeptide [goid 6397] [evidence IEA]; Any process involved in maintaining the structure and integrity of a protein and preventing it from degradation or aggregation [goid 50821] [pmid 12881431] [evidence IDA]'], 'ONTOLOGY_FUNCTION': [nan, 'Elemental activities, such as catalysis or binding, describing the actions of a gene product at the molecular level. A given gene product may exhibit one or more molecular functions [goid 3674] [evidence ND ]', 'Elemental activities, such as catalysis or binding, describing the actions of a gene product at the molecular level. A given gene product may exhibit one or more molecular functions [goid 3674] [evidence ND ]', 'Interacting selectively with a nucleotide, any compound consisting of a nucleoside that is esterified with (ortho)phosphate or an oligophosphate at any hydroxyl group on the ribose or deoxyribose moiety [goid 166] [evidence IEA]; Interacting selectively with double-stranded RNA [goid 3725] [pmid 11871661] [evidence IDA]; Interacting selectively with single-stranded RNA [goid 3727] [pmid 11871661] [evidence IDA]; Interacting selectively with any protein or protein complex (a complex of two or more proteins that may include other nonprotein molecules) [goid 5515] [pmid 12896982] [evidence IPI]; Interacting selectively with any protein or protein complex (a complex of two or more proteins that may include other nonprotein molecules) [goid 5515] [pmid 10669759] [evidence IPI]', 'Interacting selectively with a nucleotide, any compound consisting of a nucleoside that is esterified with (ortho)phosphate or an oligophosphate at any hydroxyl group on the ribose or deoxyribose moiety [goid 166] [evidence IEA]; Interacting selectively with double-stranded RNA [goid 3725] [pmid 11871661] [evidence IDA]; Interacting selectively with single-stranded RNA [goid 3727] [pmid 11871661] [evidence IDA]; Interacting selectively with any protein or protein complex (a complex of two or more proteins that may include other nonprotein molecules) [goid 5515] [pmid 12896982] [evidence IPI]; Interacting selectively with any protein or protein complex (a complex of two or more proteins that may include other nonprotein molecules) [goid 5515] [pmid 10669759] [evidence IPI]'], 'SYNONYMS': [nan, 'A1B; GAB; HYST2477; ABG; DKFZp686F0970', 'A1B; GAB; HYST2477; ABG; DKFZp686F0970', 'ASP; MGC163391; APOBEC1CF; ACF65; ACF64; ACF; RP11-564C4.2', 'ASP; APOBEC1CF; ACF65; ACF64; RP11-564C4.2; MGC163391; ACF'], 'OBSOLETE_PROBE_ID': [nan, 'A1B; GAB; HYST2477; ABG; DKFZp686F0970', 'A1B; GAB; HYST2477; ABG; DKFZp686F0970', 'ASP; APOBEC1CF; ACF65; ACF64; RP11-564C4.2; MGC163391; ACF', 'ASP; APOBEC1CF; ACF65; ACF64; RP11-564C4.2; MGC163391; ACF'], 'GB_ACC': ['NM_182762.2', 'NM_130786.2', 'NM_130786.2', 'NM_138932.1', 'NM_014576.2'], 'SPOT_ID': [nan, nan, nan, nan, nan]}\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": "ffced7bc", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "2d4b4201", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:34:53.864500Z", "iopub.status.busy": "2025-03-25T08:34:53.864372Z", "iopub.status.idle": "2025-03-25T08:34:54.532393Z", "shell.execute_reply": "2025-03-25T08:34:54.532016Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping dataframe shape: (44053, 2)\n", "Gene expression dataframe shape after mapping: (21464, 40)\n", "First 5 gene symbols: ['A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression dataframe shape after normalization: (20259, 40)\n", "First 5 normalized gene symbols: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Cystic_Fibrosis/gene_data/GSE107846.csv\n" ] } ], "source": [ "# 1. Determine the appropriate columns for mapping\n", "# Based on the gene annotation preview, we can see that:\n", "# - 'ID' column in the annotation dataframe contains the gene identifiers (ILMN_*)\n", "# - 'SYMBOL' column contains the gene symbols (e.g., A1BG)\n", "\n", "# 2. Create the gene mapping dataframe\n", "gene_mapping = get_gene_mapping(gene_annotation, 'ID', 'SYMBOL')\n", "print(f\"Gene mapping dataframe shape: {gene_mapping.shape}\")\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene-level expression\n", "gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=gene_mapping)\n", "print(f\"Gene expression dataframe shape after mapping: {gene_data.shape}\")\n", "print(f\"First 5 gene symbols: {gene_data.index[:5].tolist()}\")\n", "\n", "# Normalize gene symbols to handle synonyms\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene expression dataframe shape after normalization: {gene_data.shape}\")\n", "print(f\"First 5 normalized gene symbols: {gene_data.index[:5].tolist()}\")\n", "\n", "# Save the gene expression data\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"Gene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "2cdf5969", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "a88d4bc3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:34:54.533748Z", "iopub.status.busy": "2025-03-25T08:34:54.533630Z", "iopub.status.idle": "2025-03-25T08:35:03.909199Z", "shell.execute_reply": "2025-03-25T08:35:03.908814Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data shape: (20259, 40)\n", "First few genes with their expression values after normalization:\n", " GSM2881538 GSM2881539 GSM2881540 GSM2881541 GSM2881542 \\\n", "Gene \n", "A1BG 8.7476 21.9606 23.2725 15.6942 29.2452 \n", "A1BG-AS1 14.6337 4.9228 -4.9448 7.6773 3.3042 \n", "A1CF -14.7669 3.2132 15.3795 -1.3697 -1.3926 \n", "A2M -8.5760 -2.6491 -3.7892 -8.4301 -7.5382 \n", "A2ML1 -7.3726 -11.7410 -10.4285 -2.1618 -9.3990 \n", "\n", " GSM2881543 GSM2881544 GSM2881545 GSM2881546 GSM2881547 ... \\\n", "Gene ... \n", "A1BG 25.1912 36.4149 3.4988 7.2743 7.5244 ... \n", "A1BG-AS1 12.0664 2.6297 -0.5639 9.5417 -0.9727 ... \n", "A1CF 3.5824 2.9546 2.3193 -8.2343 10.8697 ... \n", "A2M -5.7942 -11.3958 -8.8512 -4.5680 -8.4289 ... \n", "A2ML1 -0.9402 -16.9884 -7.8979 -10.7797 -16.0183 ... \n", "\n", " GSM2881568 GSM2881569 GSM2881570 GSM2881571 GSM2881572 \\\n", "Gene \n", "A1BG 3.8675 11.0394 -4.1460 12.8334 24.5083 \n", "A1BG-AS1 -9.1909 8.5280 -7.8317 -7.2293 2.1266 \n", "A1CF -4.0794 -0.4929 -3.3018 8.4637 5.9381 \n", "A2M -5.1416 -7.3695 -11.9849 -6.3600 -16.4508 \n", "A2ML1 -7.0981 -10.2052 -12.1922 -6.3853 -11.8803 \n", "\n", " GSM2881573 GSM2881574 GSM2881575 GSM2881576 GSM2881577 \n", "Gene \n", "A1BG 11.5269 3.0649 22.3939 10.4309 -3.9459 \n", "A1BG-AS1 1.5597 -4.3375 4.1493 -1.4494 -5.9361 \n", "A1CF 3.0050 -5.7033 0.4676 5.5139 10.4620 \n", "A2M -2.0990 -3.3126 -2.6062 -3.1815 -0.8704 \n", "A2ML1 -14.3931 4.0708 -3.8137 -7.2550 -9.3725 \n", "\n", "[5 rows x 40 columns]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Cystic_Fibrosis/gene_data/GSE107846.csv\n", "Raw clinical data shape: (7, 41)\n", "Clinical features:\n", " GSM2881538 GSM2881539 GSM2881540 GSM2881541 GSM2881542 \\\n", "Cystic_Fibrosis 0.0 0.0 0.0 0.0 0.0 \n", "Age 9.0 3.8 5.1 3.4 7.0 \n", "Gender 0.0 0.0 1.0 0.0 1.0 \n", "\n", " GSM2881543 GSM2881544 GSM2881545 GSM2881546 GSM2881547 \\\n", "Cystic_Fibrosis 0.0 0.0 0.0 0.0 0.0 \n", "Age 2.8 4.3 2.3 9.9 7.8 \n", "Gender 1.0 0.0 0.0 0.0 1.0 \n", "\n", " ... GSM2881568 GSM2881569 GSM2881570 GSM2881571 \\\n", "Cystic_Fibrosis ... 1.00 1.0 1.000 1.000 \n", "Age ... 4.25 6.0 6.167 2.417 \n", "Gender ... 1.00 0.0 0.000 1.000 \n", "\n", " GSM2881572 GSM2881573 GSM2881574 GSM2881575 GSM2881576 \\\n", "Cystic_Fibrosis 1.000 1.0 1.0 1.000 1.00 \n", "Age 4.667 2.5 5.0 5.417 5.25 \n", "Gender 1.000 1.0 0.0 1.000 1.00 \n", "\n", " GSM2881577 \n", "Cystic_Fibrosis 1.0 \n", "Age 4.0 \n", "Gender 0.0 \n", "\n", "[3 rows x 40 columns]\n", "Clinical features saved to ../../output/preprocess/Cystic_Fibrosis/clinical_data/GSE107846.csv\n", "Linked data shape: (40, 20262)\n", "Linked data preview (first 5 rows, first 5 columns):\n", " Cystic_Fibrosis Age Gender A1BG A1BG-AS1\n", "GSM2881538 0.0 9.0 0.0 8.7476 14.6337\n", "GSM2881539 0.0 3.8 0.0 21.9606 4.9228\n", "GSM2881540 0.0 5.1 1.0 23.2725 -4.9448\n", "GSM2881541 0.0 3.4 0.0 15.6942 7.6773\n", "GSM2881542 0.0 7.0 1.0 29.2452 3.3042\n", "Missing values before handling:\n", " Trait (Cystic_Fibrosis) missing: 0 out of 40\n", " Age missing: 0 out of 40\n", " Gender missing: 0 out of 40\n", " Genes with >20% missing: 0\n", " Samples with >5% missing genes: 0\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (40, 20262)\n", "For the feature 'Cystic_Fibrosis', the least common label is '0.0' with 12 occurrences. This represents 30.00% of the dataset.\n", "The distribution of the feature 'Cystic_Fibrosis' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 3.25\n", " 50% (Median): 4.7085\n", " 75%: 6.80825\n", "Min: 1.083\n", "Max: 9.917\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n", "For the feature 'Gender', the least common label is '0.0' with 20 occurrences. This represents 50.00% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n", "A new JSON file was created at: ../../output/preprocess/Cystic_Fibrosis/cohort_info.json\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Cystic_Fibrosis/GSE107846.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n", "print(\"First few genes with their expression values after normalization:\")\n", "print(normalized_gene_data.head())\n", "\n", "# Save the normalized 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", "# 2. Extract clinical features directly from the matrix file\n", "try:\n", " # Get the file paths for the matrix file to extract clinical data\n", " _, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " \n", " # Get raw clinical data from the matrix file\n", " _, clinical_raw = get_background_and_clinical_data(matrix_file)\n", " \n", " # Verify clinical data structure\n", " print(\"Raw clinical data shape:\", clinical_raw.shape)\n", " \n", " # Extract clinical features using the defined conversion functions\n", " clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_raw,\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(\"Clinical features:\")\n", " print(clinical_features)\n", " \n", " # Save clinical features to file\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_features.to_csv(out_clinical_data_file)\n", " print(f\"Clinical features saved to {out_clinical_data_file}\")\n", " \n", " # 3. Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " print(\"Linked data preview (first 5 rows, first 5 columns):\")\n", " print(linked_data.iloc[:5, :5])\n", " \n", " # 4. Handle missing values\n", " print(\"Missing values before handling:\")\n", " print(f\" Trait ({trait}) missing: {linked_data[trait].isna().sum()} out of {len(linked_data)}\")\n", " if 'Age' in linked_data.columns:\n", " print(f\" Age missing: {linked_data['Age'].isna().sum()} out of {len(linked_data)}\")\n", " if 'Gender' in linked_data.columns:\n", " print(f\" Gender missing: {linked_data['Gender'].isna().sum()} out of {len(linked_data)}\")\n", " print(f\" Genes with >20% missing: {sum(linked_data.iloc[:, 1:].isna().mean() > 0.2)}\")\n", " print(f\" Samples with >5% missing genes: {sum(linked_data.iloc[:, 1:].isna().mean(axis=1) > 0.05)}\")\n", " \n", " cleaned_data = handle_missing_values(linked_data, trait)\n", " print(f\"Data shape after handling missing values: {cleaned_data.shape}\")\n", " \n", " # 5. Evaluate bias in trait and demographic features\n", " is_trait_biased = False\n", " if len(cleaned_data) > 0:\n", " trait_biased, cleaned_data = judge_and_remove_biased_features(cleaned_data, trait)\n", " is_trait_biased = trait_biased\n", " else:\n", " print(\"No data remains after handling missing values.\")\n", " is_trait_biased = True\n", " \n", " # 6. Final validation and save\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=cleaned_data,\n", " note=\"Dataset contains gene expression data comparing CFTR WT vs CFTR mutant (p.Phe508del) samples.\"\n", " )\n", " \n", " # 7. Save if usable\n", " if is_usable and len(cleaned_data) > 0:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " cleaned_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 or empty and was not saved\")\n", " \n", "except Exception as e:\n", " print(f\"Error processing data: {e}\")\n", " # Handle the error case by still recording cohort info\n", " 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, # Mark as not available due to processing issues\n", " is_biased=True, \n", " df=pd.DataFrame(), # Empty dataframe\n", " note=f\"Error processing data: {str(e)}\"\n", " )\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 }