{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "8baceca3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:31:32.694860Z", "iopub.status.busy": "2025-03-25T08:31:32.694467Z", "iopub.status.idle": "2025-03-25T08:31:32.860457Z", "shell.execute_reply": "2025-03-25T08:31:32.860126Z" } }, "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 = \"COVID-19\"\n", "cohort = \"GSE243348\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/COVID-19\"\n", "in_cohort_dir = \"../../input/GEO/COVID-19/GSE243348\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/COVID-19/GSE243348.csv\"\n", "out_gene_data_file = \"../../output/preprocess/COVID-19/gene_data/GSE243348.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/COVID-19/clinical_data/GSE243348.csv\"\n", "json_path = \"../../output/preprocess/COVID-19/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "18459c40", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "5b3217be", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:31:32.861843Z", "iopub.status.busy": "2025-03-25T08:31:32.861701Z", "iopub.status.idle": "2025-03-25T08:31:32.883906Z", "shell.execute_reply": "2025-03-25T08:31:32.883615Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Longitudinal gene expression profiling of self-collected blood samples in COVID-19+ and healthy participants\"\n", "!Series_summary\t\"Longitudinal cohort: 773 host response genes were profiled in previously vaccinated (n=16) and unvaccinated (n=14) COVID-19+ participants along with 5 healthy uninfected controls across a 2-week observational window\"\n", "!Series_summary\t\"Single timepoint cohort: 773 host response genes were profiled in 6 healthy uninfected participants\"\n", "!Series_overall_design\t\"Longitudinal cohort: 30 COVID-19+ and 5 uninfected participants were asked perform self-collection and stabilization of capillary blood using a novel technology (homeRNA) every other day for two weeks (7 longtiudinal timepoints per participant). Temporal kinetics of 773 immune genes were profiled using the nCounter direct digital counting of native mRNA.\"\n", "!Series_overall_design\t\"Single timepoint cohort: 6 healthy uninfected participants were asked perform self-collection and stabilization of capillary blood using a novel technology (homeRNA). Temporal kinetics of 773 immune genes were profiled using the nCounter direct digital counting of native mRNA.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['disease status: COVID-19+', 'disease status: Healthy uninfected'], 1: ['participant id: CB0101', 'participant id: CB0102', 'participant id: CB0104', 'participant id: CB0106', 'participant id: CB0107', 'participant id: CB0111', 'participant id: CB0112', 'participant id: CB0113', 'participant id: CB0115', 'participant id: CB0116', 'participant id: CB0117', 'participant id: CB0118', 'participant id: CB0119', 'participant id: CB0120', 'participant id: CB0121', 'participant id: CB0122', 'participant id: CB0123', 'participant id: CB0124', 'participant id: CB0125', 'participant id: CB0128', 'participant id: CB0129', 'participant id: CB0130', 'participant id: CB0131', 'participant id: CB0132', 'participant id: CB0133', 'participant id: CB0134', 'participant id: CB0135', 'participant id: CB0136', 'participant id: CB0138', 'participant id: CB0139'], 2: ['Sex: female', 'Sex: male'], 3: ['age: 44', 'age: 29', 'age: 51', 'age: 32', 'age: 27', 'age: 30', 'age: 41', 'age: 43', 'age: 34', 'age: 60', 'age: 24', 'age: 36', 'age: 33', 'age: 53', 'age: 31', 'age: 59', 'age: 40', 'age: 65', 'age: 37', 'age: 39', 'age: 58', 'age: 42', 'age: 28', 'age: 38'], 4: ['covid-19 vaccination history: unvaccinated', 'covid-19 vaccination history: vaccinated', 'covid-19 vaccination history: partial'], 5: ['day post symptom onset: 10', 'day post symptom onset: 13', 'day post symptom onset: 15', 'day post symptom onset: 17', 'day post symptom onset: 19', 'day post symptom onset: 21', 'day post symptom onset: 23', 'day post symptom onset: 9', 'day post symptom onset: 11', 'day post symptom onset: 8', 'day post symptom onset: 12', 'day post symptom onset: 14', 'day post symptom onset: 16', 'day post symptom onset: 18', 'day post symptom onset: 20', 'day post symptom onset: 27', 'day post symptom onset: 25', 'day post symptom onset: 5', 'day post symptom onset: 7', 'day post symptom onset: 6', 'day post symptom onset: 22', 'day post symptom onset: 24', 'day post symptom onset: 26', 'day post symptom onset: 28', 'study day: 1', 'study day: 3', 'study day: 5', 'study day: 7', 'study day: 9', 'study day: 11'], 6: ['study day: 1', 'study day: 4', 'study day: 6', 'study day: 8', 'study day: 10', 'study day: 12', 'study day: 14', 'study day: 3', 'study day: 5', 'study day: 9', 'study day: 11', 'study day: 13', 'study day: 7', 'study day: 15', 'ncounter host response codeset: V1.0', 'ncounter host response codeset: V1.1'], 7: ['ncounter host response codeset: V1.0', 'ncounter host response codeset: V1.1', nan]}\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": "4c297b26", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "f3d4de96", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:31:32.884964Z", "iopub.status.busy": "2025-03-25T08:31:32.884858Z", "iopub.status.idle": "2025-03-25T08:31:32.918521Z", "shell.execute_reply": "2025-03-25T08:31:32.918240Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data preview:\n", "{'sample_0': [1.0, nan, nan], 'sample_1': [0.0, nan, nan], 'sample_2': [nan, nan, nan], 'sample_3': [nan, nan, nan], 'sample_4': [nan, nan, nan], 'sample_5': [nan, nan, nan], 'sample_6': [nan, nan, nan], 'sample_7': [nan, nan, nan], 'sample_8': [nan, nan, nan], 'sample_9': [nan, nan, nan], 'sample_10': [nan, nan, nan], 'sample_11': [nan, nan, nan], 'sample_12': [nan, nan, nan], 'sample_13': [nan, nan, nan], 'sample_14': [nan, nan, nan], 'sample_15': [nan, nan, nan], 'sample_16': [nan, nan, nan], 'sample_17': [nan, nan, nan], 'sample_18': [nan, nan, nan], 'sample_19': [nan, nan, nan], 'sample_20': [nan, nan, nan], 'sample_21': [nan, nan, nan], 'sample_22': [nan, nan, nan], 'sample_23': [nan, nan, nan], 'sample_24': [nan, nan, nan], 'sample_25': [nan, nan, nan], 'sample_26': [nan, nan, nan], 'sample_27': [nan, nan, nan], 'sample_28': [nan, nan, nan], 'sample_29': [nan, nan, nan], 'sample_30': [nan, nan, nan], 'sample_31': [nan, nan, nan], 'sample_32': [nan, nan, 0.0], 'sample_33': [nan, nan, 1.0], 'sample_34': [nan, 44.0, nan], 'sample_35': [nan, 29.0, nan], 'sample_36': [nan, 51.0, nan], 'sample_37': [nan, 32.0, nan], 'sample_38': [nan, 27.0, nan], 'sample_39': [nan, 30.0, nan], 'sample_40': [nan, 41.0, nan], 'sample_41': [nan, 43.0, nan], 'sample_42': [nan, 34.0, nan], 'sample_43': [nan, 60.0, nan], 'sample_44': [nan, 24.0, nan], 'sample_45': [nan, 36.0, nan], 'sample_46': [nan, 33.0, nan], 'sample_47': [nan, 53.0, nan], 'sample_48': [nan, 31.0, nan], 'sample_49': [nan, 59.0, nan], 'sample_50': [nan, 40.0, nan], 'sample_51': [nan, 65.0, nan], 'sample_52': [nan, 37.0, nan], 'sample_53': [nan, 39.0, nan], 'sample_54': [nan, 58.0, nan], 'sample_55': [nan, 42.0, nan], 'sample_56': [nan, 28.0, nan], 'sample_57': [nan, 38.0, nan], 'sample_58': [nan, nan, nan], 'sample_59': [nan, nan, nan], 'sample_60': [nan, nan, nan], 'sample_61': [nan, nan, nan], 'sample_62': [nan, nan, nan], 'sample_63': [nan, nan, nan], 'sample_64': [nan, nan, nan], 'sample_65': [nan, nan, nan], 'sample_66': [nan, nan, nan], 'sample_67': [nan, nan, nan], 'sample_68': [nan, nan, nan], 'sample_69': [nan, nan, nan], 'sample_70': [nan, nan, nan], 'sample_71': [nan, nan, nan], 'sample_72': [nan, nan, nan], 'sample_73': [nan, nan, nan], 'sample_74': [nan, nan, nan], 'sample_75': [nan, nan, nan], 'sample_76': [nan, nan, nan], 'sample_77': [nan, nan, nan], 'sample_78': [nan, nan, nan], 'sample_79': [nan, nan, nan], 'sample_80': [nan, nan, nan], 'sample_81': [nan, nan, nan], 'sample_82': [nan, nan, nan], 'sample_83': [nan, nan, nan], 'sample_84': [nan, nan, nan], 'sample_85': [nan, nan, nan], 'sample_86': [nan, nan, nan], 'sample_87': [nan, nan, nan], 'sample_88': [nan, nan, nan], 'sample_89': [nan, nan, nan], 'sample_90': [nan, nan, nan], 'sample_91': [nan, nan, nan], 'sample_92': [nan, nan, nan], 'sample_93': [nan, nan, nan], 'sample_94': [nan, nan, nan], 'sample_95': [nan, nan, nan], 'sample_96': [nan, nan, nan], 'sample_97': [nan, nan, nan], 'sample_98': [nan, nan, nan], 'sample_99': [nan, nan, nan], 'sample_100': [nan, nan, nan], 'sample_101': [nan, nan, nan], 'sample_102': [nan, nan, nan], 'sample_103': [nan, nan, nan], 'sample_104': [nan, nan, nan], 'sample_105': [nan, nan, nan], 'sample_106': [nan, nan, nan], 'sample_107': [nan, nan, nan], 'sample_108': [nan, nan, nan], 'sample_109': [nan, nan, nan]}\n", "Clinical data saved to ../../output/preprocess/COVID-19/clinical_data/GSE243348.csv\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n", " clinical_data[col_name] = None\n", "/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n", " clinical_data[col_name] = None\n", "/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n", " clinical_data[col_name] = None\n", "/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n", " clinical_data[col_name] = None\n", "/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n", " clinical_data[col_name] = None\n", "/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n", " clinical_data[col_name] = None\n", "/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n", " clinical_data[col_name] = None\n", "/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n", " clinical_data[col_name] = None\n", "/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n", " clinical_data[col_name] = None\n", "/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n", " clinical_data[col_name] = None\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains gene expression data\n", "# \"773 host response genes were profiled using the nCounter direct digital counting of native mRNA\"\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# Trait (COVID-19 status) is in row 0\n", "trait_row = 0\n", "\n", "# Age is in row 3\n", "age_row = 3\n", "\n", "# Gender is in row 2\n", "gender_row = 2\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "def convert_trait(value: str) -> int:\n", " \"\"\"\n", " Convert COVID-19 status to binary (0 for healthy, 1 for COVID-19+)\n", " \"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " value_lower = value.lower()\n", " if 'covid-19+' in value_lower:\n", " return 1\n", " elif 'healthy' in value_lower:\n", " return 0\n", " return None\n", "\n", "def convert_age(value: str) -> float:\n", " \"\"\"\n", " Convert age values to continuous numeric values\n", " \"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " try:\n", " # Extract the number after the colon\n", " parts = value.split(': ')\n", " if len(parts) > 1:\n", " return float(parts[1])\n", " return None\n", " except:\n", " return None\n", "\n", "def convert_gender(value: str) -> int:\n", " \"\"\"\n", " Convert gender to binary (0 for female, 1 for male)\n", " \"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " value_lower = value.lower()\n", " if 'female' in value_lower:\n", " return 0\n", " elif 'male' in value_lower:\n", " return 1\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Check if trait data is available\n", "is_trait_available = trait_row is not None\n", "validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n", " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n", "\n", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # Sample characteristics were provided in the previous step\n", " # Create a properly structured DataFrame where each row is a characteristic\n", " # and columns represent different samples\n", " \n", " # First, create an empty DataFrame with the sample characteristics as rows\n", " clinical_data = pd.DataFrame(index=range(8)) # 8 rows for the characteristics\n", " \n", " # Add sample characteristics as rows\n", " sample_chars = {\n", " 0: ['disease status: COVID-19+', 'disease status: Healthy uninfected'],\n", " 1: ['participant id: CB0101', 'participant id: CB0102', 'participant id: CB0104', 'participant id: CB0106', 'participant id: CB0107', 'participant id: CB0111', 'participant id: CB0112', 'participant id: CB0113', 'participant id: CB0115', 'participant id: CB0116', 'participant id: CB0117', 'participant id: CB0118', 'participant id: CB0119', 'participant id: CB0120', 'participant id: CB0121', 'participant id: CB0122', 'participant id: CB0123', 'participant id: CB0124', 'participant id: CB0125', 'participant id: CB0128', 'participant id: CB0129', 'participant id: CB0130', 'participant id: CB0131', 'participant id: CB0132', 'participant id: CB0133', 'participant id: CB0134', 'participant id: CB0135', 'participant id: CB0136', 'participant id: CB0138', 'participant id: CB0139'],\n", " 2: ['Sex: female', 'Sex: male'],\n", " 3: ['age: 44', 'age: 29', 'age: 51', 'age: 32', 'age: 27', 'age: 30', 'age: 41', 'age: 43', 'age: 34', 'age: 60', 'age: 24', 'age: 36', 'age: 33', 'age: 53', 'age: 31', 'age: 59', 'age: 40', 'age: 65', 'age: 37', 'age: 39', 'age: 58', 'age: 42', 'age: 28', 'age: 38'],\n", " 4: ['covid-19 vaccination history: unvaccinated', 'covid-19 vaccination history: vaccinated', 'covid-19 vaccination history: partial'],\n", " 5: ['day post symptom onset: 10', 'day post symptom onset: 13', 'day post symptom onset: 15', 'day post symptom onset: 17', 'day post symptom onset: 19', 'day post symptom onset: 21', 'day post symptom onset: 23', 'day post symptom onset: 9', 'day post symptom onset: 11', 'day post symptom onset: 8', 'day post symptom onset: 12', 'day post symptom onset: 14', 'day post symptom onset: 16', 'day post symptom onset: 18', 'day post symptom onset: 20', 'day post symptom onset: 27', 'day post symptom onset: 25', 'day post symptom onset: 5', 'day post symptom onset: 7', 'day post symptom onset: 6', 'day post symptom onset: 22', 'day post symptom onset: 24', 'day post symptom onset: 26', 'day post symptom onset: 28', 'study day: 1', 'study day: 3', 'study day: 5', 'study day: 7', 'study day: 9', 'study day: 11'],\n", " 6: ['study day: 1', 'study day: 4', 'study day: 6', 'study day: 8', 'study day: 10', 'study day: 12', 'study day: 14', 'study day: 3', 'study day: 5', 'study day: 9', 'study day: 11', 'study day: 13', 'study day: 7', 'study day: 15', 'ncounter host response codeset: V1.0', 'ncounter host response codeset: V1.1'],\n", " 7: ['ncounter host response codeset: V1.0', 'ncounter host response codeset: V1.1', None]\n", " }\n", " \n", " # Populate the DataFrame with the sample characteristics\n", " for idx, values in sample_chars.items():\n", " for val in values:\n", " # Create a new column for each unique value\n", " col_name = f\"sample_{len(clinical_data.columns)}\"\n", " clinical_data[col_name] = None\n", " clinical_data.at[idx, col_name] = val\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 and save the data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Clinical data preview:\")\n", " print(preview)\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 the 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": "66110b1f", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "28a1519a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:31:32.919524Z", "iopub.status.busy": "2025-03-25T08:31:32.919425Z", "iopub.status.idle": "2025-03-25T08:31:32.957929Z", "shell.execute_reply": "2025-03-25T08:31:32.957640Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SOFT file: ../../input/GEO/COVID-19/GSE243348/GSE243348_family.soft.gz\n", "Matrix file: ../../input/GEO/COVID-19/GSE243348/GSE243348_series_matrix.txt.gz\n", "Found the matrix table marker at line 69\n", "Gene data shape: (773, 237)\n", "First 20 gene/probe identifiers:\n", "['ACE', 'ACKR2', 'ACKR3', 'ACKR4', 'ACOX1', 'ACSL1', 'ACSL3', 'ACSL4', 'ACVR1', 'ADAR', 'ADGRE5', 'ADGRG3', 'ADORA2A', 'AGT', 'AHR', 'AIF1', 'AIM2', 'AKT1', 'AKT2', 'AKT3']\n" ] } ], "source": [ "# 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", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# Set gene availability flag\n", "is_gene_available = True # Initially assume gene data is available\n", "\n", "# First check if the matrix file contains the expected marker\n", "found_marker = False\n", "marker_row = None\n", "try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " for i, line in enumerate(file):\n", " if \"!series_matrix_table_begin\" in line:\n", " found_marker = True\n", " marker_row = i\n", " print(f\"Found the matrix table marker at line {i}\")\n", " break\n", " \n", " if not found_marker:\n", " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n", " is_gene_available = False\n", " \n", " # If marker was found, try to extract gene data\n", " if is_gene_available:\n", " try:\n", " # Try using the library function\n", " gene_data = get_genetic_data(matrix_file)\n", " \n", " if gene_data.shape[0] == 0:\n", " print(\"Warning: Extracted gene data has 0 rows.\")\n", " is_gene_available = False\n", " else:\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " # Print the first 20 gene/probe identifiers\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20].tolist())\n", " except Exception as e:\n", " print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n", " is_gene_available = False\n", " \n", " # If gene data extraction failed, examine file content to diagnose\n", " if not is_gene_available:\n", " print(\"Examining file content to diagnose the issue:\")\n", " try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Print lines around the marker if found\n", " if marker_row is not None:\n", " for i, line in enumerate(file):\n", " if i >= marker_row - 2 and i <= marker_row + 10:\n", " print(f\"Line {i}: {line.strip()[:100]}...\")\n", " if i > marker_row + 10:\n", " break\n", " else:\n", " # If marker not found, print first 10 lines\n", " for i, line in enumerate(file):\n", " if i < 10:\n", " print(f\"Line {i}: {line.strip()[:100]}...\")\n", " else:\n", " break\n", " except Exception as e2:\n", " print(f\"Error examining file: {e2}\")\n", " \n", "except Exception as e:\n", " print(f\"Error processing file: {e}\")\n", " is_gene_available = False\n", "\n", "# Update validation information if gene data extraction failed\n", "if not is_gene_available:\n", " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n", " # Update the validation record since gene data isn't available\n", " is_trait_available = False # We already determined trait data isn't available in step 2\n", " validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n", " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n" ] }, { "cell_type": "markdown", "id": "0723d070", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "527c0ff2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:31:32.958909Z", "iopub.status.busy": "2025-03-25T08:31:32.958809Z", "iopub.status.idle": "2025-03-25T08:31:32.960512Z", "shell.execute_reply": "2025-03-25T08:31:32.960251Z" } }, "outputs": [], "source": [ "# Review gene identifiers\n", "# These identifiers appear to be standard human gene symbols (official gene symbols)\n", "# Examples like ACE, ACKR2, AKT1, etc. are recognized human gene symbols\n", "# No mapping is required as they are already in the correct format\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "d153c38f", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 6, "id": "57c0706f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:31:32.961470Z", "iopub.status.busy": "2025-03-25T08:31:32.961373Z", "iopub.status.idle": "2025-03-25T08:31:33.135284Z", "shell.execute_reply": "2025-03-25T08:31:33.134966Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape after normalization: (758, 237)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/COVID-19/gene_data/GSE243348.csv\n", "Loaded clinical data with shape: (3, 110)\n", "Clinical data columns: Index(['sample_0', 'sample_1', 'sample_2', 'sample_3', 'sample_4'], dtype='object') ...\n", "Clinical data sparsity: 91.52% missing values\n", "Non-NA values per clinical feature: [2, 24, 2]\n", "Cannot proceed with linking due to insufficient clinical data (mostly NaN values).\n", "Abnormality detected in the cohort: GSE243348. Preprocessing failed.\n" ] } ], "source": [ "# 1. Normalize gene symbols in gene expression data\n", "try:\n", " # Normalize 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", " # Create output directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " \n", " # Save the normalized gene data\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. Attempt to load clinical data and link with genetic data\n", " try:\n", " # Load clinical data file saved in Step 2\n", " clinical_df = pd.read_csv(out_clinical_data_file)\n", " print(f\"Loaded clinical data with shape: {clinical_df.shape}\")\n", " \n", " # Inspect the clinical data structure\n", " print(\"Clinical data columns:\", clinical_df.columns[:5], \"...\" if len(clinical_df.columns) > 5 else \"\")\n", " \n", " # Check for sparsity in clinical data\n", " sparsity = clinical_df.isna().sum().sum() / (clinical_df.shape[0] * clinical_df.shape[1])\n", " print(f\"Clinical data sparsity: {sparsity:.2%} missing values\")\n", " \n", " # Count non-NA values in each row of clinical data\n", " non_na_counts = clinical_df.notna().sum(axis=1)\n", " print(f\"Non-NA values per clinical feature: {non_na_counts.tolist()}\")\n", " \n", " # Since the clinical data has too many NaN values (as observed in Step 2),\n", " # and does not contain proper trait information, we cannot link it effectively\n", " is_trait_available = False\n", " print(\"Cannot proceed with linking due to insufficient clinical data (mostly NaN values).\")\n", " \n", " # 5. Validate and save cohort info - mark as not usable due to lack of trait data\n", " is_biased = True # Since we can't even analyze trait distribution\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=is_trait_available,\n", " is_biased=is_biased,\n", " df=pd.DataFrame(), # Empty dataframe since we don't have linked data\n", " note=\"Gene expression data available but clinical data contains too many missing values for effective linking.\"\n", " )\n", " \n", " except Exception as e:\n", " print(f\"Error processing clinical data: {e}\")\n", " is_trait_available = False\n", " \n", " # Validate with proper values for unavailable trait data\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=is_trait_available,\n", " is_biased=True,\n", " df=pd.DataFrame(),\n", " note=f\"Error processing clinical data: {str(e)}\"\n", " )\n", " \n", "except Exception as e:\n", " print(f\"Error in gene data processing: {e}\")\n", " \n", " # Log the error and mark the dataset as unusable\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=False,\n", " is_trait_available=False,\n", " is_biased=True,\n", " df=pd.DataFrame(),\n", " note=f\"Error during gene data normalization: {str(e)}\"\n", " )" ] } ], "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 }