{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "df2a2950", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:40:03.746195Z", "iopub.status.busy": "2025-03-25T06:40:03.746089Z", "iopub.status.idle": "2025-03-25T06:40:03.908281Z", "shell.execute_reply": "2025-03-25T06:40:03.907921Z" } }, "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 = \"Asthma\"\n", "cohort = \"GSE123088\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Asthma\"\n", "in_cohort_dir = \"../../input/GEO/Asthma/GSE123088\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Asthma/GSE123088.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Asthma/gene_data/GSE123088.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Asthma/clinical_data/GSE123088.csv\"\n", "json_path = \"../../output/preprocess/Asthma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "b9d0f24e", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "4e4cbfc9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:40:03.909735Z", "iopub.status.busy": "2025-03-25T06:40:03.909588Z", "iopub.status.idle": "2025-03-25T06:40:04.197389Z", "shell.execute_reply": "2025-03-25T06:40:04.197017Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"A validated single-cell-based strategy to identify diagnostic and therapeutic targets in complex diseases\"\n", "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n", "!Series_overall_design\t\"Refer to individual Series\"\n", "Sample Characteristics Dictionary:\n", "{0: ['cell type: CD4+ T cells'], 1: ['primary diagnosis: ASTHMA', 'primary diagnosis: ATHEROSCLEROSIS', 'primary diagnosis: BREAST_CANCER', 'primary diagnosis: CHRONIC_LYMPHOCYTIC_LEUKEMIA', 'primary diagnosis: CROHN_DISEASE', 'primary diagnosis: ATOPIC_ECZEMA', 'primary diagnosis: HEALTHY_CONTROL', 'primary diagnosis: INFLUENZA', 'primary diagnosis: OBESITY', 'primary diagnosis: PSORIASIS', 'primary diagnosis: SEASONAL_ALLERGIC_RHINITIS', 'primary diagnosis: TYPE_1_DIABETES', 'primary diagnosis: ACUTE_TONSILLITIS', 'primary diagnosis: ULCERATIVE_COLITIS', 'primary diagnosis: Breast cancer', 'primary diagnosis: Control'], 2: ['Sex: Male', 'diagnosis2: ATOPIC_ECZEMA', 'Sex: Female', 'diagnosis2: ATHEROSCLEROSIS', 'diagnosis2: ASTHMA_OBESITY', 'diagnosis2: ASTHMA', 'diagnosis2: ASTMHA_SEASONAL_ALLERGIC_RHINITIS', 'diagnosis2: OBESITY'], 3: ['age: 56', 'Sex: Male', 'age: 20', 'age: 51', 'age: 37', 'age: 61', 'age: 31', 'age: 41', 'age: 80', 'age: 53', 'age: 73', 'age: 60', 'age: 76', 'age: 77', 'age: 74', 'age: 69', 'age: 81', 'age: 70', 'age: 82', 'age: 67', 'age: 78', 'age: 72', 'age: 66', 'age: 36', 'age: 45', 'age: 65', 'age: 48', 'age: 50', 'age: 24', 'age: 42'], 4: [nan, 'age: 63', 'age: 74', 'age: 49', 'age: 60', 'age: 68', 'age: 38', 'age: 16', 'age: 12', 'age: 27']}\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": "d376f47c", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "e1c2a70a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:40:04.198653Z", "iopub.status.busy": "2025-03-25T06:40:04.198528Z", "iopub.status.idle": "2025-03-25T06:40:04.211174Z", "shell.execute_reply": "2025-03-25T06:40:04.210857Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of clinical features:\n", "{0: [1.0, 56.0, 1.0], 1: [0.0, nan, nan], 2: [0.0, 20.0, 0.0], 3: [0.0, 51.0, nan], 4: [0.0, 37.0, nan], 5: [0.0, 61.0, nan], 6: [0.0, 31.0, nan], 7: [0.0, 41.0, nan], 8: [0.0, 80.0, nan], 9: [0.0, 53.0, nan], 10: [0.0, 73.0, nan], 11: [0.0, 60.0, nan], 12: [0.0, 76.0, nan], 13: [0.0, 77.0, nan], 14: [0.0, 74.0, nan], 15: [0.0, 69.0, nan], 16: [nan, 81.0, nan], 17: [nan, 70.0, nan], 18: [nan, 82.0, nan], 19: [nan, 67.0, nan], 20: [nan, 78.0, nan], 21: [nan, 72.0, nan], 22: [nan, 66.0, nan], 23: [nan, 36.0, nan], 24: [nan, 45.0, nan], 25: [nan, 65.0, nan], 26: [nan, 48.0, nan], 27: [nan, 50.0, nan], 28: [nan, 24.0, nan], 29: [nan, 42.0, nan]}\n", "Clinical data saved to ../../output/preprocess/Asthma/clinical_data/GSE123088.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background information, this appears to be a gene expression dataset from CD4+ T cells\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For trait (Asthma), row 1 contains 'primary diagnosis' which includes 'ASTHMA'\n", "trait_row = 1\n", "\n", "# For gender, row 2 and 3 contain 'Sex: Male' and 'Sex: Female'\n", "gender_row = 2 # This row seems to have more gender entries\n", "\n", "# For age, row 3 and 4 contain age information\n", "age_row = 3 # This row seems to have more age entries\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " if not isinstance(value, str):\n", " return None\n", " value = value.lower()\n", " if 'diagnosis' not in value:\n", " return None\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " if 'asthma' in value.lower():\n", " return 1\n", " else:\n", " return 0\n", "\n", "def convert_gender(value):\n", " if not isinstance(value, str):\n", " return None\n", " if 'sex' not in value.lower():\n", " return None\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " if 'female' in value:\n", " return 0\n", " elif 'male' in value:\n", " return 1\n", " return None\n", "\n", "def convert_age(value):\n", " if not isinstance(value, str):\n", " return None\n", " if 'age' not in value.lower():\n", " return None\n", " if ':' in value:\n", " try:\n", " age = int(value.split(':', 1)[1].strip())\n", " return age\n", " except:\n", " return None\n", " return None\n", "\n", "# 3. Save Metadata - 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. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # Create DataFrame from the sample characteristics dictionary\n", " sample_characteristics_dict = {0: ['cell type: CD4+ T cells'], \n", " 1: ['primary diagnosis: ASTHMA', 'primary diagnosis: ATHEROSCLEROSIS', 'primary diagnosis: BREAST_CANCER', \n", " 'primary diagnosis: CHRONIC_LYMPHOCYTIC_LEUKEMIA', 'primary diagnosis: CROHN_DISEASE', \n", " 'primary diagnosis: ATOPIC_ECZEMA', 'primary diagnosis: HEALTHY_CONTROL', 'primary diagnosis: INFLUENZA', \n", " 'primary diagnosis: OBESITY', 'primary diagnosis: PSORIASIS', 'primary diagnosis: SEASONAL_ALLERGIC_RHINITIS', \n", " 'primary diagnosis: TYPE_1_DIABETES', 'primary diagnosis: ACUTE_TONSILLITIS', \n", " 'primary diagnosis: ULCERATIVE_COLITIS', 'primary diagnosis: Breast cancer', 'primary diagnosis: Control'], \n", " 2: ['Sex: Male', 'diagnosis2: ATOPIC_ECZEMA', 'Sex: Female', 'diagnosis2: ATHEROSCLEROSIS', \n", " 'diagnosis2: ASTHMA_OBESITY', 'diagnosis2: ASTHMA', 'diagnosis2: ASTMHA_SEASONAL_ALLERGIC_RHINITIS', \n", " 'diagnosis2: OBESITY'], \n", " 3: ['age: 56', 'Sex: Male', 'age: 20', 'age: 51', 'age: 37', 'age: 61', 'age: 31', 'age: 41', \n", " 'age: 80', 'age: 53', 'age: 73', 'age: 60', 'age: 76', 'age: 77', 'age: 74', 'age: 69', \n", " 'age: 81', 'age: 70', 'age: 82', 'age: 67', 'age: 78', 'age: 72', 'age: 66', 'age: 36', \n", " 'age: 45', 'age: 65', 'age: 48', 'age: 50', 'age: 24', 'age: 42'], \n", " 4: [float('nan'), 'age: 63', 'age: 74', 'age: 49', 'age: 60', 'age: 68', 'age: 38', 'age: 16', \n", " 'age: 12', 'age: 27']}\n", " \n", " clinical_data = pd.DataFrame.from_dict(sample_characteristics_dict, orient='index')\n", " \n", " # Extract clinical features\n", " clinical_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 clinical features\n", " preview = preview_df(clinical_features)\n", " print(\"Preview of clinical features:\")\n", " print(preview)\n", " \n", " # Create directory if it doesn't exist and save the clinical features to a CSV file\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_features.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "e6cb6e04", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "b95d920d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:40:04.212191Z", "iopub.status.busy": "2025-03-25T06:40:04.212083Z", "iopub.status.idle": "2025-03-25T06:40:04.731481Z", "shell.execute_reply": "2025-03-25T06:40:04.731084Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Asthma/GSE123088/GSE123088_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (24166, 204)\n", "First 20 gene/probe identifiers:\n", "Index(['1', '2', '3', '9', '10', '12', '13', '14', '15', '16', '18', '19',\n", " '20', '21', '22', '23', '24', '25', '26', '27'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. Get the SOFT and matrix file paths again \n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "print(f\"Matrix file found: {matrix_file}\")\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_data\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " \n", " # 3. Print the first 20 row IDs (gene or probe identifiers)\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20])\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n" ] }, { "cell_type": "markdown", "id": "c6be56df", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "77f1652d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:40:04.732834Z", "iopub.status.busy": "2025-03-25T06:40:04.732709Z", "iopub.status.idle": "2025-03-25T06:40:04.734675Z", "shell.execute_reply": "2025-03-25T06:40:04.734391Z" } }, "outputs": [], "source": [ "# The identifiers shown are not standard human gene symbols\n", "# They appear to be numeric indices or probe IDs that would need mapping to actual gene symbols\n", "# Standard human gene symbols would typically be formatted like BRCA1, TP53, etc.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "f98ba288", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "0abd3538", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:40:04.735822Z", "iopub.status.busy": "2025-03-25T06:40:04.735716Z", "iopub.status.idle": "2025-03-25T06:40:11.917849Z", "shell.execute_reply": "2025-03-25T06:40:11.917454Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Platform title found: Agilent-039494 SurePrint G3 Human GE v2 8x60K Microarray 039381 (Entrez Gene ID version)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "{'ID': ['1', '2', '3', '9', '10', '12', '13', '14', '15', '16'], 'ENTREZ_GENE_ID': ['1', '2', '3', '9', '10', '12', '13', '14', '15', '16'], 'SPOT_ID': [1.0, 2.0, 3.0, 9.0, 10.0, 12.0, 13.0, 14.0, 15.0, 16.0]}\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", "# Check if there are any platforms defined in the SOFT file that might contain annotation data\n", "with gzip.open(soft_file, 'rt') as f:\n", " soft_content = f.read()\n", "\n", "# Look for platform sections in the SOFT file\n", "platform_sections = re.findall(r'^!Platform_title\\s*=\\s*(.+)$', soft_content, re.MULTILINE)\n", "if platform_sections:\n", " print(f\"Platform title found: {platform_sections[0]}\")\n", "\n", "# Try to extract more annotation data by reading directly from the SOFT file\n", "# Look for lines that might contain gene symbol mappings\n", "symbol_pattern = re.compile(r'ID_REF\\s+Symbol|ID\\s+Gene Symbol', re.IGNORECASE)\n", "annotation_lines = []\n", "with gzip.open(soft_file, 'rt') as f:\n", " for line in f:\n", " if symbol_pattern.search(line):\n", " annotation_lines.append(line)\n", " # Collect the next few lines to see the annotation structure\n", " for _ in range(10):\n", " annotation_lines.append(next(f, ''))\n", "\n", "if annotation_lines:\n", " print(\"Found potential gene symbol mappings:\")\n", " for line in annotation_lines:\n", " print(line.strip())\n", "\n", "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n", "print(\"\\nGene annotation preview:\")\n", "print(preview_df(gene_annotation, n=10))\n", "\n", "# If we need an alternative source of mapping, check if there are any other annotation files in the cohort directory\n", "cohort_files = os.listdir(in_cohort_dir)\n", "annotation_files = [f for f in cohort_files if 'annotation' in f.lower() or 'platform' in f.lower()]\n", "if annotation_files:\n", " print(\"\\nAdditional annotation files found in the cohort directory:\")\n", " for file in annotation_files:\n", " print(file)\n" ] }, { "cell_type": "markdown", "id": "5f50054b", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "43665388", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:40:11.919215Z", "iopub.status.busy": "2025-03-25T06:40:11.919092Z", "iopub.status.idle": "2025-03-25T06:40:20.377129Z", "shell.execute_reply": "2025-03-25T06:40:20.376780Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Using 'ID' to map to 'ENTREZ_GENE_ID'\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Mapping data shape: (4740924, 2)\n", "First few rows of mapping data:\n", " ID Gene\n", "0 1 1\n", "1 2 2\n", "2 3 3\n", "3 9 9\n", "4 10 10\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Mapped gene expression data shape: (0, 204)\n", "First few rows of gene expression data:\n", "Empty DataFrame\n", "Columns: [GSM3494884, GSM3494885, GSM3494886, GSM3494887, GSM3494888, GSM3494889, GSM3494890, GSM3494891, GSM3494892, GSM3494893, GSM3494894, GSM3494895, GSM3494896, GSM3494897, GSM3494898, GSM3494899, GSM3494900, GSM3494901, GSM3494902, GSM3494903, GSM3494904, GSM3494905, GSM3494906, GSM3494907, GSM3494908, GSM3494909, GSM3494910, GSM3494911, GSM3494912, GSM3494913, GSM3494914, GSM3494915, GSM3494916, GSM3494917, GSM3494918, GSM3494919, GSM3494920, GSM3494921, GSM3494922, GSM3494923, GSM3494924, GSM3494925, GSM3494926, GSM3494927, GSM3494928, GSM3494929, GSM3494930, GSM3494931, GSM3494932, GSM3494933, GSM3494934, GSM3494935, GSM3494936, GSM3494937, GSM3494938, GSM3494939, GSM3494940, GSM3494941, GSM3494942, GSM3494943, GSM3494944, GSM3494945, GSM3494946, GSM3494947, GSM3494948, GSM3494949, GSM3494950, GSM3494951, GSM3494952, GSM3494953, GSM3494954, GSM3494955, GSM3494956, GSM3494957, GSM3494958, GSM3494959, GSM3494960, GSM3494961, GSM3494962, GSM3494963, GSM3494964, GSM3494965, GSM3494966, GSM3494967, GSM3494968, GSM3494969, GSM3494970, GSM3494971, GSM3494972, GSM3494973, GSM3494974, GSM3494975, GSM3494976, GSM3494977, GSM3494978, GSM3494979, GSM3494980, GSM3494981, GSM3494982, GSM3494983, ...]\n", "Index: []\n", "\n", "[0 rows x 204 columns]\n", "Gene expression data saved to ../../output/preprocess/Asthma/gene_data/GSE123088.csv\n" ] } ], "source": [ "# 1. Determine which columns to use for mapping\n", "# From the previous output, I can see:\n", "# - The gene expression data uses numeric IDs as identifiers (e.g., '1', '2', '3')\n", "# - The gene annotation contains columns 'ID' and 'ENTREZ_GENE_ID'\n", "# - The annotation shows that 'ID' column contains the same identifiers seen in gene expression data\n", "# - 'ENTREZ_GENE_ID' contains gene IDs that we can use to map to gene symbols\n", "\n", "# First check if we have any additional mapping resources\n", "mapping_id_column = 'ID' # This matches the identifiers in gene_data\n", "mapping_gene_column = 'ENTREZ_GENE_ID' # We'll use this as the gene identifier\n", "\n", "print(f\"Using '{mapping_id_column}' to map to '{mapping_gene_column}'\")\n", "\n", "# 2. Extract the mapping data\n", "mapping_data = get_gene_mapping(gene_annotation, mapping_id_column, mapping_gene_column)\n", "print(f\"Mapping data shape: {mapping_data.shape}\")\n", "print(\"First few rows of mapping data:\")\n", "print(mapping_data.head())\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, mapping_data)\n", "print(f\"Mapped gene expression data shape: {gene_data.shape}\")\n", "print(\"First few rows of gene expression data:\")\n", "print(gene_data.head())\n", "\n", "# Save the mapped gene expression data to a CSV file\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}\")" ] } ], "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 }