{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "09614faf", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:24:34.133638Z", "iopub.status.busy": "2025-03-25T06:24:34.133452Z", "iopub.status.idle": "2025-03-25T06:24:34.297864Z", "shell.execute_reply": "2025-03-25T06:24:34.297527Z" } }, "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 = \"Alopecia\"\n", "cohort = \"GSE18876\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Alopecia\"\n", "in_cohort_dir = \"../../input/GEO/Alopecia/GSE18876\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Alopecia/GSE18876.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Alopecia/gene_data/GSE18876.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Alopecia/clinical_data/GSE18876.csv\"\n", "json_path = \"../../output/preprocess/Alopecia/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "7ec98190", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "21f44c67", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:24:34.299091Z", "iopub.status.busy": "2025-03-25T06:24:34.298944Z", "iopub.status.idle": "2025-03-25T06:24:34.408103Z", "shell.execute_reply": "2025-03-25T06:24:34.407783Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Transcriptional Profile of Aging in Healthy Human Skin\"\n", "!Series_summary\t\"Gene expression changes were assessed from the non sun-exposed skin of the lower back of 98 healthy males aged 19-86. We show that contrary to previous thought, genome wide transcriptional activity does not display an exclusively linear correlation with ageing, but rather, in human skin, undergoes a period of significant transient change between 30 and 45 years of age. The identified transient transcriptional changes suggest a period of heightened metabolic activity and cellular damage mediated primarily through the actions of TP53 (tumour protein 53) and TNF (tumour necrosis factor). We also identified a subgroup of the population characterised by increased expression of a large group of hair follicle genes that correlates strongly with a younger age of onset and increasing severity of androgenetic alopecia.\"\n", "!Series_overall_design\t\"Skin was collected from the lower back at the level of the belt, aproximately 5cm lateral to midline from healthy males, (defined as; non-smoking, no hospital admissions in the previous 5 years, no significant medical conditions or medications). Each sample was individually hybridised to an exon 1.0 ST array.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['age: 19', 'age: 20', 'age: 21', 'age: 22', 'age: 23', 'age: 24', 'age: 25', 'age: 26', 'age: 27', 'age: 30', 'age: 31', 'age: 33', 'age: 34', 'age: 36', 'age: 38', 'age: 39', 'age: 41', 'age: 42', 'age: 43', 'age: 44', 'age: 45', 'age: 47', 'age: 49', 'age: 50', 'age: 51', 'age: 52', 'age: 53', 'age: 54', 'age: 55', 'age: 57'], 1: ['tissue: skin']}\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": "1d63f3b0", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "8f27f0ea", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:24:34.409387Z", "iopub.status.busy": "2025-03-25T06:24:34.409283Z", "iopub.status.idle": "2025-03-25T06:24:34.413299Z", "shell.execute_reply": "2025-03-25T06:24:34.413016Z" } }, "outputs": [], "source": [ "# 1. Gene Expression Data Availability \n", "# Based on the background information, this dataset contains transcriptional profiles from skin samples\n", "# hybridized to exon arrays, which indicates gene expression data is available\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# Age is available in row 0\n", "age_row = 0\n", "\n", "# Gender is not explicitly mentioned, but the background information states \"healthy males\" only,\n", "# so all subjects are male (constant). Therefore gender data is not useful for our analysis.\n", "gender_row = None\n", "\n", "# For trait (Alopecia), there's no direct mention in the sample characteristics,\n", "# but the background information mentions a \"subgroup of the population characterised by... androgenetic alopecia\"\n", "# However, we don't have this information in the sample characteristics dictionary\n", "trait_row = None \n", "\n", "# 2.2 Data Type Conversion\n", "def convert_age(age_str):\n", " \"\"\"Convert age string to numeric value.\"\"\"\n", " try:\n", " # Extract the number after the colon and space\n", " if ':' in age_str:\n", " age_val = age_str.split(': ')[1].strip()\n", " return float(age_val)\n", " else:\n", " return None\n", " except:\n", " return None\n", "\n", "def convert_trait(trait_str):\n", " \"\"\"\n", " Convert trait string to binary value.\n", " This function is defined but won't be used since trait_row is None.\n", " \"\"\"\n", " return None\n", "\n", "def convert_gender(gender_str):\n", " \"\"\"\n", " Convert gender string to binary value.\n", " This function is defined but won't be used since gender_row is None.\n", " \"\"\"\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Initial filtering and save the information\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", "# Since trait_row is None, we skip the clinical feature extraction step entirely\n", "if trait_row is not None:\n", " # This block won't execute in this case since trait_row is None\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 dataframe\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Clinical data preview:\")\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)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "1f019122", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "be9c3b27", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:24:34.414482Z", "iopub.status.busy": "2025-03-25T06:24:34.414382Z", "iopub.status.idle": "2025-03-25T06:24:34.589582Z", "shell.execute_reply": "2025-03-25T06:24:34.589269Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First 20 gene/probe identifiers:\n", "Index(['2315554', '2315633', '2315674', '2315739', '2315894', '2315918',\n", " '2315951', '2316218', '2316245', '2316379', '2316558', '2316605',\n", " '2316746', '2316905', '2316953', '2317246', '2317317', '2317434',\n", " '2317472', '2317512'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. First get the file paths again to access the matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_data from the matrix_file\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# 3. Print the first 20 row IDs (gene or probe identifiers) for future observation\n", "print(\"First 20 gene/probe identifiers:\")\n", "print(gene_data.index[:20])\n" ] }, { "cell_type": "markdown", "id": "66e2b791", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "9ebeea21", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:24:34.591382Z", "iopub.status.busy": "2025-03-25T06:24:34.591274Z", "iopub.status.idle": "2025-03-25T06:24:34.593146Z", "shell.execute_reply": "2025-03-25T06:24:34.592848Z" } }, "outputs": [], "source": [ "# Examine the gene identifiers in the given index\n", "# The identifiers appear to be numerical, which suggests they are not human gene symbols\n", "# Human gene symbols typically follow specific naming conventions (e.g., BRCA1, TP53)\n", "# These look like probe IDs that would need mapping to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "5bc10530", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "eed54af9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:24:34.594594Z", "iopub.status.busy": "2025-03-25T06:24:34.594494Z", "iopub.status.idle": "2025-03-25T06:24:38.350708Z", "shell.execute_reply": "2025-03-25T06:24:38.350343Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['2315100', '2315106', '2315109', '2315111', '2315113'], 'GB_LIST': ['NR_024005,NR_034090,NR_024004,AK093685', 'DQ786314', nan, nan, 'DQ786265'], 'SPOT_ID': ['chr1:11884-14409', 'chr1:14760-15198', 'chr1:19408-19712', 'chr1:25142-25532', 'chr1:27563-27813'], 'seqname': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], 'RANGE_GB': ['NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10'], 'RANGE_STRAND': ['+', '+', '+', '+', '+'], 'RANGE_START': ['11884', '14760', '19408', '25142', '27563'], 'RANGE_STOP': ['14409', '15198', '19712', '25532', '27813'], 'total_probes': ['20', '8', '4', '4', '4'], 'gene_assignment': ['NR_024005 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771 /// NR_034090 // DDX11L9 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 9 // 15q26.3 // 100288486 /// NR_024004 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771 /// AK093685 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771', '---', '---', '---', '---'], 'mrna_assignment': ['NR_024005 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 (DDX11L2), transcript variant 2, non-coding RNA. // chr1 // 100 // 80 // 16 // 16 // 0 /// NR_034090 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 9 (DDX11L9), non-coding RNA. // chr1 // 100 // 80 // 16 // 16 // 0 /// NR_024004 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 (DDX11L2), transcript variant 1, non-coding RNA. // chr1 // 100 // 75 // 15 // 15 // 0 /// AK093685 // GenBank // Homo sapiens cDNA FLJ36366 fis, clone THYMU2007824. // chr1 // 94 // 80 // 15 // 16 // 0 /// ENST00000513886 // ENSEMBL // cdna:known chromosome:GRCh37:16:61555:64090:1 gene:ENSG00000233614 // chr1 // 100 // 80 // 16 // 16 // 0 /// ENST00000456328 // ENSEMBL // cdna:known chromosome:GRCh37:1:11869:14409:1 gene:ENSG00000223972 // chr1 // 100 // 80 // 16 // 16 // 0 /// ENST00000518655 // ENSEMBL // cdna:known chromosome:GRCh37:1:11869:14409:1 gene:ENSG00000253101 // chr1 // 100 // 80 // 16 // 16 // 0', 'DQ786314 // GenBank // Homo sapiens clone HLS_IMAGE_811138 mRNA sequence. // chr1 // 100 // 38 // 3 // 3 // 0', '---', '---', 'DQ786265 // GenBank // Homo sapiens clone HLS_IMAGE_298685 mRNA sequence. // chr1 // 100 // 100 // 4 // 4 // 0'], 'category': ['main', 'main', '---', '---', 'main']}\n" ] } ], "source": [ "# 1. First get the file paths using geo_get_relevant_filepaths function\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. 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", "# 3. 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": "0556a9fb", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "fc870895", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:24:38.352478Z", "iopub.status.busy": "2025-03-25T06:24:38.352359Z", "iopub.status.idle": "2025-03-25T06:24:41.915337Z", "shell.execute_reply": "2025-03-25T06:24:41.914765Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First few rows of gene mapping:\n", " ID Gene\n", "0 2315100 NR_024005 // DDX11L2 // DEAD/H (Asp-Glu-Ala-As...\n", "1 2315106 ---\n", "2 2315109 ---\n", "3 2315111 ---\n", "4 2315113 ---\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "First 20 gene symbols after mapping:\n", "Index(['A-', 'A-2', 'A-52', 'A-E', 'A-I', 'A-II', 'A-IV', 'A-V', 'A0', 'A1',\n", " 'A1-', 'A10', 'A11', 'A12', 'A13', 'A14', 'A16', 'A1BG', 'A1BG-AS',\n", " 'A1CF'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data saved to ../../output/preprocess/Alopecia/gene_data/GSE18876.csv\n" ] } ], "source": [ "# 1. Identify the columns for gene identifiers and gene symbols in the gene annotation data\n", "# From the preview, 'ID' column contains the same numeric identifiers as in gene expression data\n", "# and 'gene_assignment' contains the gene symbol information\n", "\n", "# 2. Get gene mapping dataframe by extracting these columns\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='gene_assignment')\n", "\n", "# Check the first few rows of the mapping\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", "\n", "# Check the first few gene symbols in the processed data\n", "print(\"\\nFirst 20 gene symbols after mapping:\")\n", "print(gene_data.index[:20])\n", "\n", "# Save gene data to CSV\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"\\nGene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "63562ae8", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "9d8aa50b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:24:41.917153Z", "iopub.status.busy": "2025-03-25T06:24:41.916774Z", "iopub.status.idle": "2025-03-25T06:24:43.122801Z", "shell.execute_reply": "2025-03-25T06:24:43.122259Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalizing gene symbols...\n", "Gene data shape after normalization: (18418, 98)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Alopecia/gene_data/GSE18876.csv\n", "No trait data available for clinical feature extraction\n", "Empty clinical data saved to ../../output/preprocess/Alopecia/clinical_data/GSE18876.csv\n", "Creating gene data representation without clinical features...\n", "Linked data shape: (98, 18418)\n", "Dataset usability: False\n", "Dataset is not usable for trait-gene association studies due to missing trait data.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "print(\"Normalizing gene symbols...\")\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", "\n", "# Save the normalized gene data to a CSV file\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# 2. Since trait_row is None (no trait data available), we'll create an empty clinical dataframe\n", "print(\"No trait data available for clinical feature extraction\")\n", "selected_clinical_df = pd.DataFrame()\n", "\n", "# Save empty clinical data to a CSV file for consistency\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "selected_clinical_df.to_csv(out_clinical_data_file)\n", "print(f\"Empty clinical data saved to {out_clinical_data_file}\")\n", "\n", "# Create a linked dataframe with just gene data (no clinical features)\n", "print(\"Creating gene data representation without clinical features...\")\n", "linked_data = normalized_gene_data.T # Transpose to get samples as rows\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "\n", "# 3-6. Since trait data is unavailable, we'll use is_final=False in validation\n", "# We'll skip handling missing values and bias checking since they require trait data\n", "\n", "# Update the note to reflect the actual dataset\n", "note = \"Dataset contains gene expression data from skin samples of healthy males of different ages, as described in the study 'Transcriptional Profile of Aging in Healthy Human Skin'. The study mentions a subgroup with androgenetic alopecia, but this information is not available in the clinical annotations.\"\n", "\n", "# Perform validation with is_final=False since we can't evaluate bias without trait data\n", "is_usable = 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", "print(f\"Dataset usability: {is_usable}\")\n", "print(\"Dataset is not usable for trait-gene association studies due to missing trait data.\")" ] } ], "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 }