{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "ee37d9e6", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:08:33.225742Z", "iopub.status.busy": "2025-03-25T06:08:33.225637Z", "iopub.status.idle": "2025-03-25T06:08:33.388863Z", "shell.execute_reply": "2025-03-25T06:08:33.388542Z" } }, "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 = \"Parkinsons_Disease\"\n", "cohort = \"GSE49126\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Parkinsons_Disease\"\n", "in_cohort_dir = \"../../input/GEO/Parkinsons_Disease/GSE49126\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Parkinsons_Disease/GSE49126.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Parkinsons_Disease/gene_data/GSE49126.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Parkinsons_Disease/clinical_data/GSE49126.csv\"\n", "json_path = \"../../output/preprocess/Parkinsons_Disease/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "1f6afe81", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "ada710e8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:08:33.390300Z", "iopub.status.busy": "2025-03-25T06:08:33.390153Z", "iopub.status.idle": "2025-03-25T06:08:33.553101Z", "shell.execute_reply": "2025-03-25T06:08:33.552749Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Transcriptomic profiling of peripheral blood mononuclear cells from patients with Parkinson's disease and control subjects\"\n", "!Series_summary\t\"To get insight into systemic molecular events associated with Parkinson's disease (PD), an age-related neurodegenerative disorder, we compared gene expression patterns of peripheral blood mononuclear cells (PBMC) derived from elderly healhy controls and from PD patients.\"\n", "!Series_overall_design\t\"Transcriptomic profiling of patients with Parkinson's disease and control subjects. RNA were extracted from peripheral mononuclear blood cells and were hybridized on 4x44k Agilent expression microarrays.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['disease state: control', \"disease state: Parkinson's disease\"], 1: ['cell type: peripheral blood mononuclear 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": "d2d2ed8f", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "64ad1650", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:08:33.554477Z", "iopub.status.busy": "2025-03-25T06:08:33.554364Z", "iopub.status.idle": "2025-03-25T06:08:33.561848Z", "shell.execute_reply": "2025-03-25T06:08:33.561531Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{0: [0.0]}\n", "Clinical data saved to ../../output/preprocess/Parkinsons_Disease/clinical_data/GSE49126.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Yes, the background information suggests this dataset contains gene expression data from Agilent microarrays\n", "is_gene_available = True\n", "\n", "# 2. Variables Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For Parkinson's Disease (trait)\n", "# From sample characteristics, the first row (index 0) contains disease state (control vs. Parkinson's disease)\n", "trait_row = 0 \n", "\n", "# No age information available in the characteristics dictionary\n", "age_row = None \n", "\n", "# No gender information available in the characteristics dictionary\n", "gender_row = None \n", "\n", "# 2.2 Data Type Conversion\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert trait value to binary: 1 for Parkinson's disease, 0 for control.\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to binary\n", " if \"parkinson\" in value.lower():\n", " return 1\n", " elif \"control\" in value.lower():\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to continuous numeric.\"\"\"\n", " # Not used since age data is not available\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender value to binary: 0 for female, 1 for male.\"\"\"\n", " # Not used since gender data is not available\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " value = value.lower()\n", " if 'female' in value or 'f' in value:\n", " return 0\n", " elif 'male' in value or 'm' in value:\n", " return 1\n", " else:\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 of dataset usability\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 a DataFrame from the sample characteristics dictionary\n", " # The sample characteristics dictionary only contains the information about available variables\n", " # We need to construct clinical_data DataFrame in a format compatible with geo_select_clinical_features\n", " \n", " # For this dataset, we need to create a DataFrame with the disease state information\n", " sample_characteristics = {0: ['disease state: control', \"disease state: Parkinson's disease\"]}\n", " \n", " # Create a DataFrame from the sample characteristics\n", " clinical_data = pd.DataFrame(sample_characteristics)\n", " \n", " # Extract clinical features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the resulting DataFrame\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Save clinical data to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "c6d07bbb", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "8872f063", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:08:33.562881Z", "iopub.status.busy": "2025-03-25T06:08:33.562771Z", "iopub.status.idle": "2025-03-25T06:08:33.817046Z", "shell.execute_reply": "2025-03-25T06:08:33.816660Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First 20 gene/probe identifiers:\n", "Index(['12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23',\n", " '24', '25', '26', '27', '28', '29', '30', '31'],\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": "7bce6ff2", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "464e4eeb", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:08:33.818206Z", "iopub.status.busy": "2025-03-25T06:08:33.818093Z", "iopub.status.idle": "2025-03-25T06:08:33.819972Z", "shell.execute_reply": "2025-03-25T06:08:33.819698Z" } }, "outputs": [], "source": [ "# Analyzing gene identifiers from the previous step output\n", "# These identifiers appear to be numeric values rather than gene symbols\n", "# Human gene symbols typically follow nomenclature patterns like BRCA1, TP53, etc.\n", "# The numeric identifiers (12, 13, 14, etc.) likely need to be mapped to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "e904956f", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "438af9fb", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:08:33.820968Z", "iopub.status.busy": "2025-03-25T06:08:33.820866Z", "iopub.status.idle": "2025-03-25T06:08:38.187101Z", "shell.execute_reply": "2025-03-25T06:08:38.186603Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['1', '2', '3', '4', '5'], 'COL': ['266', '266', '266', '266', '266'], 'ROW': [170.0, 168.0, 166.0, 164.0, 162.0], 'NAME': ['GE_BrightCorner', 'DarkCorner', 'DarkCorner', 'DarkCorner', 'DarkCorner'], 'SPOT_ID': ['GE_BrightCorner', 'DarkCorner', 'DarkCorner', 'DarkCorner', 'DarkCorner'], 'CONTROL_TYPE': ['pos', 'pos', 'pos', 'pos', 'pos'], 'REFSEQ': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan], 'GENE': [nan, nan, nan, nan, nan], 'GENE_SYMBOL': [nan, nan, nan, nan, nan], 'GENE_NAME': [nan, nan, nan, nan, nan], 'UNIGENE_ID': [nan, nan, nan, nan, nan], 'ENSEMBL_ID': [nan, nan, nan, nan, nan], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': [nan, nan, nan, nan, nan], 'CHROMOSOMAL_LOCATION': [nan, nan, nan, nan, nan], 'CYTOBAND': [nan, nan, nan, nan, nan], 'DESCRIPTION': [nan, nan, nan, nan, nan], 'GO_ID': [nan, nan, nan, nan, nan], 'SEQUENCE': [nan, nan, nan, nan, nan], 'SPOT_ID.1': [nan, nan, nan, nan, nan], 'ORDER': [1.0, 2.0, 3.0, 4.0, 5.0]}\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": "3afffa13", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "6edfa8de", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:08:38.188644Z", "iopub.status.busy": "2025-03-25T06:08:38.188518Z", "iopub.status.idle": "2025-03-25T06:08:38.516733Z", "shell.execute_reply": "2025-03-25T06:08:38.516343Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First few rows of gene annotation with non-null gene symbols:\n", " ID GENE_SYMBOL\n", "11 12 APOBEC3B\n", "13 14 ATP11B\n", "14 15 LOC100132006\n", "15 16 DNAJA1\n", "17 18 EHMT2\n", "Preview of mapping data:\n", " ID Gene\n", "11 12 APOBEC3B\n", "13 14 ATP11B\n", "14 15 LOC100132006\n", "15 16 DNAJA1\n", "17 18 EHMT2\n", "Number of mappings: 32696\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Preview of gene expression data after mapping:\n", "Number of genes after mapping: 18379\n", " GSM1194062 GSM1194063 GSM1194064 GSM1194065 GSM1194066 \\\n", "Gene \n", "A1BG 1346.496358 1630.091552 2081.789469 1796.719663 2008.200069 \n", "A1CF 4.538759 5.038548 3.803502 8.955622 3.817977 \n", "A2BP1 9.909301 9.704206 7.470562 8.859836 7.333760 \n", "A2LD1 669.066900 548.872900 403.105000 463.760900 319.830400 \n", "A2M 42.052910 38.886210 23.065940 43.597190 26.161890 \n", "\n", " GSM1194067 GSM1194068 GSM1194069 GSM1194070 GSM1194071 ... \\\n", "Gene ... \n", "A1BG 1522.559963 1009.084895 1341.158950 2027.324354 2003.861906 ... \n", "A1CF 5.237851 3.216614 3.457880 4.237291 5.366957 ... \n", "A2BP1 9.685222 16.132344 6.926038 8.215888 9.822340 ... \n", "A2LD1 443.100900 438.633900 248.013200 469.619600 454.442200 ... \n", "A2M 30.920590 28.413580 15.422110 57.794280 43.735720 ... \n", "\n", " GSM1194102 GSM1194103 GSM1194104 GSM1194105 GSM1194106 \\\n", "Gene \n", "A1BG 1749.987044 1385.016852 2304.430180 2092.178360 1663.14074 \n", "A1CF 3.578176 6.867698 10.412570 8.163887 12.59161 \n", "A2BP1 8.951356 12.970842 20.853829 15.223017 24.24613 \n", "A2LD1 425.331700 902.101400 329.947800 904.598200 740.07340 \n", "A2M 23.917930 43.075670 55.747480 67.217300 60.45679 \n", "\n", " GSM1194107 GSM1194108 GSM1194109 GSM1194110 GSM1194111 \n", "Gene \n", "A1BG 1721.694577 1592.98306 1607.190855 2017.009250 1737.085181 \n", "A1CF 6.483706 15.54629 4.621959 10.410410 4.920152 \n", "A2BP1 12.878769 29.79084 9.201703 19.218434 9.708699 \n", "A2LD1 743.762600 511.14170 299.508100 622.202700 394.375000 \n", "A2M 49.509160 95.17065 26.399070 89.052390 32.440310 \n", "\n", "[5 rows x 50 columns]\n", "Preview of gene expression data after normalization:\n", "Number of genes after normalization: 17901\n", " GSM1194062 GSM1194063 GSM1194064 GSM1194065 GSM1194066 \\\n", "Gene \n", "A1BG 1346.496358 1630.091552 2081.789469 1796.719663 2008.200069 \n", "A1CF 4.538759 5.038548 3.803502 8.955622 3.817977 \n", "A2M 42.052910 38.886210 23.065940 43.597190 26.161890 \n", "A2ML1 125.865200 203.504000 139.937500 181.789300 134.115600 \n", "A3GALT2 4.721398 5.191688 4.019145 4.739811 4.043736 \n", "\n", " GSM1194067 GSM1194068 GSM1194069 GSM1194070 GSM1194071 ... \\\n", "Gene ... \n", "A1BG 1522.559963 1009.084895 1341.158950 2027.324354 2003.861906 ... \n", "A1CF 5.237851 3.216614 3.457880 4.237291 5.366957 ... \n", "A2M 30.920590 28.413580 15.422110 57.794280 43.735720 ... \n", "A2ML1 166.589100 163.001800 140.692600 333.713600 226.403700 ... \n", "A3GALT2 5.098981 3.256807 3.651523 4.297328 5.081932 ... \n", "\n", " GSM1194102 GSM1194103 GSM1194104 GSM1194105 GSM1194106 \\\n", "Gene \n", "A1BG 1749.987044 1385.016852 2304.43018 2092.178360 1663.14074 \n", "A1CF 3.578176 6.867698 10.41257 8.163887 12.59161 \n", "A2M 23.917930 43.075670 55.74748 67.217300 60.45679 \n", "A2ML1 154.066500 432.067100 360.51350 453.911000 628.54790 \n", "A3GALT2 3.901351 14.812840 12.03404 7.739103 28.92620 \n", "\n", " GSM1194107 GSM1194108 GSM1194109 GSM1194110 GSM1194111 \n", "Gene \n", "A1BG 1721.694577 1592.98306 1607.190855 2017.009250 1737.085181 \n", "A1CF 6.483706 15.54629 4.621959 10.410410 4.920152 \n", "A2M 49.509160 95.17065 26.399070 89.052390 32.440310 \n", "A2ML1 598.126800 420.07030 138.735700 464.638000 202.998200 \n", "A3GALT2 13.079970 27.06521 6.184034 9.633035 4.929014 \n", "\n", "[5 rows x 50 columns]\n" ] } ], "source": [ "# 1. Analyze the gene expression data indices and gene annotation columns to determine mapping\n", "# From the gene annotation preview, we can see that 'ID' could be the gene identifier and 'GENE_SYMBOL' looks like the column for gene symbols\n", "\n", "# Get a more comprehensive view of the gene annotation data to confirm our column choices\n", "print(\"First few rows of gene annotation with non-null gene symbols:\")\n", "non_null_gene_symbols = gene_annotation.dropna(subset=['GENE_SYMBOL']).head(5)\n", "print(non_null_gene_symbols[['ID', 'GENE_SYMBOL']])\n", "\n", "# 2. Extract the mapping between gene identifiers and gene symbols\n", "# The 'ID' column in gene_annotation seems to match the index in gene_data\n", "mapping_data = get_gene_mapping(gene_annotation, 'ID', 'GENE_SYMBOL')\n", "\n", "print(\"Preview of mapping data:\")\n", "print(mapping_data.head())\n", "print(f\"Number of mappings: {len(mapping_data)}\")\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", "\n", "print(\"Preview of gene expression data after mapping:\")\n", "print(f\"Number of genes after mapping: {len(gene_data)}\")\n", "print(gene_data.head())\n", "\n", "# Normalize gene symbols if needed\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "\n", "print(\"Preview of gene expression data after normalization:\")\n", "print(f\"Number of genes after normalization: {len(gene_data)}\")\n", "print(gene_data.head())\n" ] }, { "cell_type": "markdown", "id": "11d65a1d", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "5ed7125f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:08:38.518202Z", "iopub.status.busy": "2025-03-25T06:08:38.518076Z", "iopub.status.idle": "2025-03-25T06:08:47.231341Z", "shell.execute_reply": "2025-03-25T06:08:47.230938Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data shape: (17901, 50)\n", "First 5 gene symbols:\n", "Index(['A1BG', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2'], dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Parkinsons_Disease/gene_data/GSE49126.csv\n", "Original clinical data columns (should contain sample IDs):\n", "Index(['!Sample_geo_accession', 'GSM1194062', 'GSM1194063', 'GSM1194064',\n", " 'GSM1194065'],\n", " dtype='object')\n", "Genetic data columns (sample IDs):\n", "Index(['GSM1194062', 'GSM1194063', 'GSM1194064', 'GSM1194065', 'GSM1194066'], dtype='object')\n", "Selected clinical data shape: (1, 50)\n", "Selected clinical data preview (transposed):\n", " Parkinsons_Disease\n", "GSM1194062 0.0\n", "GSM1194063 0.0\n", "GSM1194064 0.0\n", "GSM1194065 0.0\n", "GSM1194066 0.0\n", "Clinical data saved to ../../output/preprocess/Parkinsons_Disease/clinical_data/GSE49126.csv\n", "Number of clinical samples: 50\n", "Number of genetic samples: 50\n", "Number of common samples: 50\n", "Linked data shape: (50, 17902)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (50, 17902)\n", "For the feature 'Parkinsons_Disease', the least common label is '0.0' with 20 occurrences. This represents 40.00% of the dataset.\n", "The distribution of the feature 'Parkinsons_Disease' in this dataset is fine.\n", "\n", "Data shape after removing biased features: (50, 17902)\n", "Is the trait biased: False\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Parkinsons_Disease/GSE49126.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols from the already mapped gene expression data from Step 6\n", "# Gene data was already normalized in Step 6\n", "print(f\"Gene expression data shape: {gene_data.shape}\")\n", "print(\"First 5 gene symbols:\")\n", "print(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", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# 2. Re-extract clinical data correctly to ensure it matches with genetic data\n", "# Re-obtain the original data\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "background_info, clinical_df = get_background_and_clinical_data(matrix_file)\n", "\n", "# Print sample identifiers from original clinical data to debug\n", "print(\"Original clinical data columns (should contain sample IDs):\")\n", "print(clinical_df.columns[:5]) # Show first 5 sample IDs\n", "\n", "# Print sample identifiers from genetic data to debug\n", "print(\"Genetic data columns (sample IDs):\")\n", "print(gene_data.columns[:5]) # Show first 5 sample IDs\n", "\n", "# Extract clinical features directly from the original clinical_df\n", "# The trait information is in row 0 (disease state)\n", "def convert_trait(value):\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to binary\n", " if \"parkinson\" in value.lower():\n", " return 1\n", " elif \"control\" in value.lower():\n", " return 0\n", " else:\n", " return None\n", "\n", "# Create clinical data with the trait information\n", "trait_row = 0 # The disease state row\n", "selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_df,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=None,\n", " convert_age=None,\n", " gender_row=None,\n", " convert_gender=None\n", ")\n", "\n", "print(\"Selected clinical data shape:\", selected_clinical_df.shape)\n", "print(\"Selected clinical data preview (transposed):\")\n", "# Transpose to show samples as rows to make structure clearer\n", "print(selected_clinical_df.T.head())\n", "\n", "# Save the processed 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", "# 3. Link clinical and genetic data\n", "# Both datasets should have samples as columns initially\n", "# Check for matching sample IDs\n", "clinical_samples = set(selected_clinical_df.columns)\n", "genetic_samples = set(gene_data.columns)\n", "common_samples = clinical_samples.intersection(genetic_samples)\n", "\n", "print(f\"Number of clinical samples: {len(clinical_samples)}\")\n", "print(f\"Number of genetic samples: {len(genetic_samples)}\")\n", "print(f\"Number of common samples: {len(common_samples)}\")\n", "\n", "if len(common_samples) > 0:\n", " # Filter both datasets to include only common samples\n", " clinical_data_filtered = selected_clinical_df[list(common_samples)]\n", " gene_data_filtered = gene_data[list(common_samples)]\n", " \n", " # Now link them using geo_link_clinical_genetic_data function\n", " linked_data = geo_link_clinical_genetic_data(clinical_data_filtered, gene_data_filtered)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " \n", " # 4. 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", " # 5. 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", " print(f\"Is the trait biased: {is_biased}\")\n", " \n", " # 6. 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=True,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=\"Dataset contains gene expression data from blood samples of PD patients and controls.\"\n", " )\n", " \n", " # 7. 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. Linked data was not saved.\")\n", "else:\n", " print(\"No common samples found between clinical and genetic data. Cannot link the datasets.\")\n", " # Record that the dataset is not usable\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=False, # No common samples means trait data isn't available for gene samples\n", " is_biased=True, # Mark as biased since we can't use it\n", " df=pd.DataFrame(), # Empty dataframe\n", " note=\"No common samples between clinical and genetic data.\"\n", " )\n", " print(\"Dataset deemed not usable. Linked data was not saved.\")" ] } ], "metadata": { "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.16" } }, "nbformat": 4, "nbformat_minor": 5 }