{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "f5cb0fca", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:28:52.488245Z", "iopub.status.busy": "2025-03-25T06:28:52.487922Z", "iopub.status.idle": "2025-03-25T06:28:52.656093Z", "shell.execute_reply": "2025-03-25T06:28:52.655662Z" } }, "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 = \"Amyotrophic_Lateral_Sclerosis\"\n", "cohort = \"GSE68607\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Amyotrophic_Lateral_Sclerosis\"\n", "in_cohort_dir = \"../../input/GEO/Amyotrophic_Lateral_Sclerosis/GSE68607\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/GSE68607.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE68607.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE68607.csv\"\n", "json_path = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "2cfffeaa", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "04956619", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:28:52.657777Z", "iopub.status.busy": "2025-03-25T06:28:52.657434Z", "iopub.status.idle": "2025-03-25T06:28:53.190226Z", "shell.execute_reply": "2025-03-25T06:28:53.189699Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"C9ORF72 GGGGCC expanded repeats produce splicing dysregulation which correlates with disease severity in amyotrophic lateral sclerosis [HuEx-1_0-st]\"\n", "!Series_summary\t\"Objective: An intronic GGGGCC-repeat expansion of C9ORF72 is the most common genetic variant of amyotrophic lateral sclerosis (ALS) and frontotemporal dementia. The mechanism of neurodegeneration is unknown, but a direct effect on RNA processing mediated by RNA foci transcribed from the repeat sequence has been proposed.\"\n", "!Series_summary\t\"Results: Gene level analysis revealed a number of differentially expressed networks and both cell types exhibited dysregulation of a network functionally enriched for genes encoding ‘RNA splicing’ proteins. There was a significant overlap of these genes with an independently generated list of GGGGCC-repeat protein binding partners. At the exon level, in lymphoblastoid cells derived from C9ORF72-ALS patients splicing consistency was lower than in lines derived from non-C9ORF72 ALS patients or controls; furthermore splicing consistency was lower in samples derived from patients with faster disease progression. Frequency of sense RNA foci showed a trend towards being higher in lymphoblastoid cells derived from patients with shorter survival, but there was no detectable correlation between disease severity and DNA expansion length.\"\n", "!Series_summary\t\"Significance: Up-regulation of genes encoding predicted binding partners of the C9ORF72 expansion is consistent with an attempted compensation for sequestration of these proteins. A number of studies have analysed changes in the transcriptome caused by C9ORF72 expansion, but to date findings have been inconsistent. As a potential explanation we suggest that dynamic sequestration of RNA processing proteins by RNA foci might lead to a loss of splicing consistency; indeed in our samples measurement of splicing consistency correlates with disease severity.\"\n", "!Series_overall_design\t\"Gene expression profiling utilised total RNA extracted from lymphoblastoid cell lines derived from human ALS patients (n=56), and controls (n=15). Thirty-one of the ALS patients had a mutation of C9ORF72.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['subject id: Control1', 'subject id: Control2', 'subject id: Control3', 'subject id: Control4', 'subject id: Control5', 'subject id: Control6', 'subject id: Control7', 'subject id: Control8', 'subject id: Control9', 'subject id: Control10', 'subject id: Control11', 'subject id: Control12', 'subject id: Control13', 'subject id: Control14', 'subject id: Control15', 'subject id: Patient1', 'subject id: Patient2', 'subject id: Patient3', 'subject id: Patient4', 'subject id: Patient5', 'subject id: Patient6', 'subject id: Patient7', 'subject id: Patient8', 'subject id: Patient9', 'subject id: Patient10', 'subject id: Patient11', 'subject id: Patient12', 'subject id: Patient13', 'subject id: Patient14', 'subject id: Patient15'], 1: ['patient group: Control', 'patient group: ALS due to mtC9ORF72', 'patient group: ALS not due to mtC9ORF72'], 2: ['cell type: Cultured lymphoblastoid 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": "76b6f7fe", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "051e509b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:28:53.191604Z", "iopub.status.busy": "2025-03-25T06:28:53.191476Z", "iopub.status.idle": "2025-03-25T06:28:53.200409Z", "shell.execute_reply": "2025-03-25T06:28:53.200017Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{0: [0.0], 1: [0.0], 2: [nan]}\n", "Clinical data saved to ../../output/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE68607.csv\n" ] } ], "source": [ "import pandas as pd\n", "from typing import Optional, Callable, Dict, Any\n", "import json\n", "import os\n", "\n", "# 1. Analyze gene expression data availability\n", "is_gene_available = True # From background info, it mentions gene expression profiling\n", "\n", "# 2.1 Identify keys for trait, age, and gender\n", "trait_row = 1 # \"patient group\" contains ALS status\n", "age_row = None # Age information is not available\n", "gender_row = None # Gender information is not available\n", "\n", "# 2.2 Define conversion functions\n", "def convert_trait(value: str) -> Optional[int]:\n", " \"\"\"Convert ALS status to binary value.\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after the colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'control' in value.lower():\n", " return 0\n", " elif 'als' in value.lower():\n", " return 1\n", " return None\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"Convert age to float, but we don't have age data.\"\"\"\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"Convert gender to binary value, but we don't have gender data.\"\"\"\n", " return None\n", "\n", "# 3. Save metadata for initial filtering\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. Extract clinical features if available\n", "if trait_row is not None:\n", " # Load the clinical data (assuming it was loaded in previous steps)\n", " clinical_data = pd.DataFrame({i: values for i, values in {0: ['subject id: Control1', 'subject id: Control2', 'subject id: Control3', 'subject id: Control4', 'subject id: Control5', 'subject id: Control6', 'subject id: Control7', 'subject id: Control8', 'subject id: Control9', 'subject id: Control10', 'subject id: Control11', 'subject id: Control12', 'subject id: Control13', 'subject id: Control14', 'subject id: Control15', 'subject id: Patient1', 'subject id: Patient2', 'subject id: Patient3', 'subject id: Patient4', 'subject id: Patient5', 'subject id: Patient6', 'subject id: Patient7', 'subject id: Patient8', 'subject id: Patient9', 'subject id: Patient10', 'subject id: Patient11', 'subject id: Patient12', 'subject id: Patient13', 'subject id: Patient14', 'subject id: Patient15'], 1: ['patient group: Control', 'patient group: Control', 'patient group: Control', 'patient group: Control', 'patient group: Control', 'patient group: Control', 'patient group: Control', 'patient group: Control', 'patient group: Control', 'patient group: Control', 'patient group: Control', 'patient group: Control', 'patient group: Control', 'patient group: Control', 'patient group: Control', 'patient group: ALS due to mtC9ORF72', 'patient group: ALS due to mtC9ORF72', 'patient group: ALS due to mtC9ORF72', 'patient group: ALS due to mtC9ORF72', 'patient group: ALS due to mtC9ORF72', 'patient group: ALS due to mtC9ORF72', 'patient group: ALS due to mtC9ORF72', 'patient group: ALS due to mtC9ORF72', 'patient group: ALS due to mtC9ORF72', 'patient group: ALS due to mtC9ORF72', 'patient group: ALS due to mtC9ORF72', 'patient group: ALS due to mtC9ORF72', 'patient group: ALS due to mtC9ORF72', 'patient group: ALS due to mtC9ORF72', 'patient group: ALS due to mtC9ORF72'], 2: ['cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells', 'cell type: Cultured lymphoblastoid cells']}.items()})\n", " \n", " # Extract and process 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 processed clinical data\n", " print(\"Preview of selected clinical features:\")\n", " print(preview_df(selected_clinical_df))\n", " \n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save clinical data\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": "0f6e09e3", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "77667edb", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:28:53.201604Z", "iopub.status.busy": "2025-03-25T06:28:53.201492Z", "iopub.status.idle": "2025-03-25T06:28:54.108831Z", "shell.execute_reply": "2025-03-25T06:28:54.108193Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "First 20 gene/probe identifiers:\n", "Index(['ENST00000000233', 'ENST00000000412', 'ENST00000000442',\n", " 'ENST00000001008', 'ENST00000001146', 'ENST00000002125',\n", " 'ENST00000002165', 'ENST00000002501', 'ENST00000002596',\n", " 'ENST00000002829', 'ENST00000003084', 'ENST00000003100',\n", " 'ENST00000003302', 'ENST00000003583', 'ENST00000003607',\n", " 'ENST00000003834', 'ENST00000003912', 'ENST00000004103',\n", " 'ENST00000004531', 'ENST00000004921'],\n", " dtype='object', name='ID')\n", "\n", "Gene data dimensions: 121741 genes × 69 samples\n" ] } ], "source": [ "# 1. Re-identify the SOFT and matrix files to ensure we have the correct paths\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Extract the gene expression 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)\n", "print(\"\\nFirst 20 gene/probe identifiers:\")\n", "print(gene_data.index[:20])\n", "\n", "# 4. Print the dimensions of the gene expression data\n", "print(f\"\\nGene data dimensions: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n", "\n", "# Note: we keep is_gene_available as True since we successfully extracted gene expression data\n", "is_gene_available = True\n" ] }, { "cell_type": "markdown", "id": "c05b7508", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "1b16a801", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:28:54.110455Z", "iopub.status.busy": "2025-03-25T06:28:54.110197Z", "iopub.status.idle": "2025-03-25T06:28:54.112530Z", "shell.execute_reply": "2025-03-25T06:28:54.112085Z" } }, "outputs": [], "source": [ "# Looking at the gene identifiers, these are ENST identifiers which represent Ensembl transcript IDs,\n", "# not standard human gene symbols. These will need to be mapped to gene symbols for consistent analysis.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "4576e048", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "4aaae4d9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:28:54.113760Z", "iopub.status.busy": "2025-03-25T06:28:54.113651Z", "iopub.status.idle": "2025-03-25T06:29:06.971229Z", "shell.execute_reply": "2025-03-25T06:29:06.970555Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['ENST00000456328', 'ENST00000450305', 'ENST00000438504', 'ENST00000423562', 'ENST00000488147'], 'transcript_symbol': ['DDX11L10-202', 'DDX11L10-201', 'WASH5P-203', 'WASH5P-201', 'WASH5P-204'], 'chromosome': ['1', '1', '1', '1', '1'], 'band': ['p36.33', 'p36.33', 'p36.33', 'p36.33', 'p36.33'], 'start_position': [11874.0, 12010.0, 14363.0, 14363.0, 14404.0], 'end_position': [14412.0, 13670.0, 29370.0, 29370.0, 29570.0], 'SPOT_ID': ['ENSG00000223972', 'ENSG00000223972', 'ENSG00000227232', 'ENSG00000227232', 'ENSG00000227232'], 'ORF': ['DDX11L10', 'DDX11L10', 'WASH5P', 'WASH5P', 'WASH5P'], 'biotype': ['protein_coding', 'protein_coding', 'protein_coding', 'protein_coding', 'protein_coding'], 'gene_description': ['DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 10 [Source:HGNC Symbol;Acc:14125]', 'DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 10 [Source:HGNC Symbol;Acc:14125]', 'WAS protein family homolog 5 pseudogene [Source:HGNC Symbol;Acc:33884]', 'WAS protein family homolog 5 pseudogene [Source:HGNC Symbol;Acc:33884]', 'WAS protein family homolog 5 pseudogene [Source:HGNC Symbol;Acc:33884]']}\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": "2986c16b", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "91c65569", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:29:06.972788Z", "iopub.status.busy": "2025-03-25T06:29:06.972655Z", "iopub.status.idle": "2025-03-25T06:29:09.133108Z", "shell.execute_reply": "2025-03-25T06:29:09.132467Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping (first few rows):\n", " ID Gene\n", "0 ENST00000456328 DDX11L10\n", "1 ENST00000450305 DDX11L10\n", "2 ENST00000438504 WASH5P\n", "3 ENST00000423562 WASH5P\n", "4 ENST00000488147 WASH5P\n", "Number of mappings: 134266\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data after mapping:\n", "Shape: 28998 genes × 69 samples\n", "First few gene symbols:\n", "Index(['A1BG', 'A1CF', 'A26C1B', 'A2BP1', 'A2LD1'], dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE68607.csv\n" ] } ], "source": [ "# 1. Based on the preview, I can see:\n", "# The gene expression data uses 'ID' column with ENST identifiers (Ensembl transcript IDs)\n", "# The gene annotation data has 'ID' column matching these transcript IDs\n", "# The 'ORF' column appears to contain gene symbols\n", "\n", "# 2. Create gene mapping dataframe\n", "gene_mapping = get_gene_mapping(gene_annotation, \"ID\", \"ORF\")\n", "print(\"Gene mapping (first few rows):\")\n", "print(gene_mapping.head())\n", "print(f\"Number of mappings: {len(gene_mapping)}\")\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene-level expression data\n", "# This handles many-to-many mappings between probes and genes\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(\"Gene expression data after mapping:\")\n", "print(f\"Shape: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n", "print(\"First few gene symbols:\")\n", "print(gene_data.index[:5])\n", "\n", "# Save processed 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": "7b29738a", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "ff795f9b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:29:09.134632Z", "iopub.status.busy": "2025-03-25T06:29:09.134503Z", "iopub.status.idle": "2025-03-25T06:29:21.528860Z", "shell.execute_reply": "2025-03-25T06:29:21.528215Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape after normalization: (19964, 69)\n", "First 5 gene symbols after normalization: Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1'], dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE68607.csv\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Sample IDs in clinical data:\n", "Index(['!Sample_geo_accession', 'GSM1677001', 'GSM1677002', 'GSM1677003',\n", " 'GSM1677004'],\n", " dtype='object') ...\n", "Sample IDs in gene expression data:\n", "Index(['GSM1677001', 'GSM1677002', 'GSM1677003', 'GSM1677004', 'GSM1677005'], dtype='object') ...\n", "Clinical data shape: (1, 69)\n", "Clinical data preview: {'GSM1677001': [0.0], 'GSM1677002': [0.0], 'GSM1677003': [0.0], 'GSM1677004': [0.0], 'GSM1677005': [0.0], 'GSM1677006': [0.0], 'GSM1677007': [0.0], 'GSM1677008': [0.0], 'GSM1677009': [0.0], 'GSM1677010': [0.0], 'GSM1677011': [0.0], 'GSM1677012': [0.0], 'GSM1677013': [0.0], 'GSM1677014': [0.0], 'GSM1677015': [0.0], 'GSM1677016': [1.0], 'GSM1677017': [1.0], 'GSM1677018': [1.0], 'GSM1677019': [1.0], 'GSM1677020': [1.0], 'GSM1677021': [1.0], 'GSM1677022': [1.0], 'GSM1677023': [1.0], 'GSM1677024': [1.0], 'GSM1677025': [1.0], 'GSM1677026': [1.0], 'GSM1677027': [1.0], 'GSM1677028': [1.0], 'GSM1677029': [1.0], 'GSM1677030': [1.0], 'GSM1677031': [1.0], 'GSM1677032': [1.0], 'GSM1677033': [1.0], 'GSM1677034': [1.0], 'GSM1677035': [1.0], 'GSM1677036': [1.0], 'GSM1677037': [1.0], 'GSM1677038': [1.0], 'GSM1677039': [1.0], 'GSM1677040': [1.0], 'GSM1677041': [1.0], 'GSM1677042': [1.0], 'GSM1677043': [1.0], 'GSM1677044': [1.0], 'GSM1677045': [1.0], 'GSM1677046': [1.0], 'GSM1677047': [1.0], 'GSM1677048': [1.0], 'GSM1677049': [1.0], 'GSM1677050': [1.0], 'GSM1677051': [1.0], 'GSM1677052': [1.0], 'GSM1677053': [1.0], 'GSM1677054': [1.0], 'GSM1677055': [1.0], 'GSM1677056': [1.0], 'GSM1677057': [1.0], 'GSM1677058': [1.0], 'GSM1677059': [1.0], 'GSM1677060': [1.0], 'GSM1677061': [1.0], 'GSM1677062': [1.0], 'GSM1677063': [1.0], 'GSM1677064': [1.0], 'GSM1677065': [1.0], 'GSM1677066': [1.0], 'GSM1677067': [1.0], 'GSM1677068': [1.0], 'GSM1677069': [1.0]}\n", "Clinical data saved to ../../output/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE68607.csv\n", "Linked data shape before handling missing values: (69, 19965)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (69, 19965)\n", "For the feature 'Amyotrophic_Lateral_Sclerosis', the least common label is '0.0' with 15 occurrences. This represents 21.74% of the dataset.\n", "The distribution of the feature 'Amyotrophic_Lateral_Sclerosis' in this dataset is fine.\n", "\n", "Data shape after removing biased features: (69, 19965)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Amyotrophic_Lateral_Sclerosis/GSE68607.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the index of gene expression data\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", "print(f\"First 5 gene symbols after normalization: {normalized_gene_data.index[:5]}\")\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. Check if clinical data was properly loaded\n", "# First, reload the clinical_data to make sure we're using the original data\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", "\n", "# Print the sample IDs to understand the data structure\n", "print(\"Sample IDs in clinical data:\")\n", "print(clinical_data.columns[:5], \"...\") # Show first 5 sample IDs\n", "\n", "# Print the sample IDs in gene expression data\n", "print(\"Sample IDs in gene expression data:\")\n", "print(normalized_gene_data.columns[:5], \"...\") # Show first 5 sample IDs\n", "\n", "# Extract clinical features using the actual sample IDs\n", "is_trait_available = trait_row is not None\n", "linked_data = None\n", "\n", "if is_trait_available:\n", " # Extract clinical features with proper sample IDs\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 if age_row is not None else None,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender if gender_row is not None else None\n", " )\n", " \n", " print(f\"Clinical data shape: {selected_clinical_df.shape}\")\n", " print(f\"Clinical data preview: {preview_df(selected_clinical_df, n=3)}\")\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", " \n", " # Link clinical and genetic data\n", " # Make sure both dataframes have compatible indices/columns\n", " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", " print(f\"Linked data shape before handling missing values: {linked_data.shape}\")\n", " \n", " if linked_data.shape[0] == 0:\n", " print(\"WARNING: No samples matched between clinical and genetic data!\")\n", " # Create a sample dataset for demonstration\n", " print(\"Using gene data with artificial trait values for demonstration\")\n", " is_trait_available = False\n", " is_biased = True\n", " linked_data = pd.DataFrame(index=normalized_gene_data.columns)\n", " linked_data[trait] = 1 # Placeholder\n", " else:\n", " # 3. Handle missing values\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", " \n", " # 4. Determine if trait and demographic features are biased\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " print(f\"Data shape after removing biased features: {linked_data.shape}\")\n", "else:\n", " print(\"Trait data was determined to be unavailable in previous steps.\")\n", " is_biased = True # Set to True since we can't evaluate without trait data\n", " linked_data = pd.DataFrame(index=normalized_gene_data.columns)\n", " linked_data[trait] = 1 # Add a placeholder trait column\n", " print(f\"Using placeholder data due to missing trait information, shape: {linked_data.shape}\")\n", "\n", "# 5. Validate and save cohort info\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=is_trait_available,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=\"Dataset contains gene expression data from multiple sclerosis patients, but there were issues linking clinical and genetic data.\"\n", ")\n", "\n", "# 6. Save linked data if usable\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Dataset deemed not usable for associational studies.\")" ] } ], "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 }