{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "ede1815f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:10:18.577165Z", "iopub.status.busy": "2025-03-25T06:10:18.577062Z", "iopub.status.idle": "2025-03-25T06:10:18.739915Z", "shell.execute_reply": "2025-03-25T06:10:18.739583Z" } }, "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 = \"Peptic_ulcer_disease\"\n", "cohort = \"GSE60427\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Peptic_ulcer_disease\"\n", "in_cohort_dir = \"../../input/GEO/Peptic_ulcer_disease/GSE60427\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Peptic_ulcer_disease/GSE60427.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Peptic_ulcer_disease/gene_data/GSE60427.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Peptic_ulcer_disease/clinical_data/GSE60427.csv\"\n", "json_path = \"../../output/preprocess/Peptic_ulcer_disease/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "e04c5b31", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "ba0217fb", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:10:18.741304Z", "iopub.status.busy": "2025-03-25T06:10:18.741166Z", "iopub.status.idle": "2025-03-25T06:10:18.874561Z", "shell.execute_reply": "2025-03-25T06:10:18.874225Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Toll-like receptor 10 in Helicobacter pylori infection\"\n", "!Series_summary\t\"Helicobacter pylori is a highly successful and important human pathogen that causes chronic gastritis, peptic ulcer diseases and gastric cancer. Innate immunity plays an important role of the primary defense against pathogens and epidemiological studies have suggested a role of toll-like receptor 1 (TLR1) in the risk of H. pylori acquisition. We performed microarray analysis of gastric mucosal biopsy specimens from H. pylori-positive and uninfected subjects; infection was associated with an ~15-fold up-regulation of TLR10 (p <0.001). Quantitative RT-PCR confirmed TLR10 mRNA levels were increased 3-fold in H. pylori-infection (p <0.001) and immunohistochemistory using anti-TLR10 polyclonal antibodies showed increased TLR10 expression in gastric epithelial cells of infected individuals. In vitro experiments where H. pylori was co-cultured with NCI-N87 gastric cells showed significant H. pylori-specific up-regulation of TLR10 mRNA levels and a correlation with TLR2 mRNA levels (R = 0.87, P <0.001). We compared combinations of TLRs for their ability to mediate NF-_B activation. NF-_B activation was increased following exposure to heat killed H. pylori or H. pylori-LPS only with the TLR2/TLR10 heterodimer. These findings suggest TLR10 is a functional receptor involved in the innate immune response to H. pylori infection and that TLR2/TLR10 heterodimer possibly functions in the recognition of H. pylori-LPS.\"\n", "!Series_overall_design\t\"We have employed whole genome microarray expression profiling of gastric epithelium in H.pylori infection. We compare 1) Hp positive and negative group. 2) by gastritis grade 3) by countries.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: gastric epithelium'], 1: ['gender: F', 'gender: M'], 2: ['age: 50', 'age: 25', 'age: 66', 'age: 33', 'age: 27', 'age: 47', 'age: 38', 'age: 30', 'age: 28', 'age: 51', 'age: 40', 'age: 24', 'age: 53', 'age: 65', 'age: 34', 'age: 18', 'age: 61', 'age: 41', 'age: 64', 'age: 49', 'age: 42', 'age: 82', 'age: 73', 'age: 57', 'age: 46'], 3: ['country: Bhutan', 'country: Dominican Republic'], 4: ['gastritis grade: normal', 'gastritis grade: mild', 'gastritis grade: severe', 'gastritis grade: IM']}\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": "90739dbb", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "686eb82d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:10:18.875936Z", "iopub.status.busy": "2025-03-25T06:10:18.875830Z", "iopub.status.idle": "2025-03-25T06:10:18.886905Z", "shell.execute_reply": "2025-03-25T06:10:18.886618Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{0: [0.0, 50.0, 0.0], 1: [1.0, 25.0, 1.0], 2: [1.0, 66.0, nan], 3: [1.0, 33.0, nan], 4: [nan, 27.0, nan], 5: [nan, 47.0, nan], 6: [nan, 38.0, nan], 7: [nan, 30.0, nan], 8: [nan, 28.0, nan], 9: [nan, 51.0, nan], 10: [nan, 40.0, nan], 11: [nan, 24.0, nan], 12: [nan, 53.0, nan], 13: [nan, 65.0, nan], 14: [nan, 34.0, nan], 15: [nan, 18.0, nan], 16: [nan, 61.0, nan], 17: [nan, 41.0, nan], 18: [nan, 64.0, nan], 19: [nan, 49.0, nan], 20: [nan, 42.0, nan], 21: [nan, 82.0, nan], 22: [nan, 73.0, nan], 23: [nan, 57.0, nan], 24: [nan, 46.0, nan]}\n", "Clinical data saved to ../../output/preprocess/Peptic_ulcer_disease/clinical_data/GSE60427.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import numpy as np\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "# 1. Gene Expression Data Availability\n", "is_gene_available = True # Based on the background information, this is a microarray study of gene expression\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# From sample characteristics, we identify the following:\n", "age_row = 2 # Age information is available\n", "gender_row = 1 # Gender information is available\n", "\n", "# Looking deeper at the background information:\n", "# The study mentions \"Helicobacter pylori... causes chronic gastritis, peptic ulcer diseases and gastric cancer\"\n", "# And there's a characteristic for \"gastritis grade\" which could potentially indicate peptic ulcer disease\n", "# Let's use the gastritis grade as a proxy for peptic ulcer disease presence\n", "trait_row = 4 # 'gastritis grade: normal', 'gastritis grade: mild', 'gastritis grade: severe', 'gastritis grade: IM'\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert gastritis grade to binary trait (0 = normal/no disease, 1 = has disease).\"\"\"\n", " if pd.isna(value) or not isinstance(value, str):\n", " return None\n", " \n", " value = value.lower().strip()\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if value == 'normal':\n", " return 0 # No disease\n", " elif value in ['mild', 'severe', 'im']: # IM = intestinal metaplasia, a pathological condition\n", " return 1 # Has disease\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age string to integer value.\"\"\"\n", " if pd.isna(value) or not isinstance(value, str):\n", " return None\n", " \n", " value = value.strip()\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " try:\n", " return int(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender string to binary (0 = female, 1 = male).\"\"\"\n", " if pd.isna(value) or not isinstance(value, str):\n", " return None\n", " \n", " value = value.lower().strip()\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if value == 'f':\n", " return 0\n", " elif value == 'm':\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\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 a DataFrame from the sample characteristics dictionary\n", " # This mimics the structure expected by geo_select_clinical_features\n", " sample_characteristics = {\n", " 0: ['tissue: gastric epithelium'], \n", " 1: ['gender: F', 'gender: M'], \n", " 2: ['age: 50', 'age: 25', 'age: 66', 'age: 33', 'age: 27', 'age: 47', 'age: 38', 'age: 30', 'age: 28', \n", " 'age: 51', 'age: 40', 'age: 24', 'age: 53', 'age: 65', 'age: 34', 'age: 18', 'age: 61', 'age: 41', \n", " 'age: 64', 'age: 49', 'age: 42', 'age: 82', 'age: 73', 'age: 57', 'age: 46'], \n", " 3: ['country: Bhutan', 'country: Dominican Republic'], \n", " 4: ['gastritis grade: normal', 'gastritis grade: mild', 'gastritis grade: severe', 'gastritis grade: IM']\n", " }\n", " \n", " # Convert dictionary to DataFrame (ensuring it's in the format expected by geo_select_clinical_features)\n", " clinical_data = pd.DataFrame.from_dict(sample_characteristics, orient='index')\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 extracted features\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Ensure directory exists before saving\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save to CSV\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "b83a184b", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "fdbff680", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:10:18.888089Z", "iopub.status.busy": "2025-03-25T06:10:18.887976Z", "iopub.status.idle": "2025-03-25T06:10:19.076686Z", "shell.execute_reply": "2025-03-25T06:10:19.076279Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Index(['A_19_P00315452', 'A_19_P00315459', 'A_19_P00315482', 'A_19_P00315492',\n", " 'A_19_P00315493', 'A_19_P00315502', 'A_19_P00315506', 'A_19_P00315518',\n", " 'A_19_P00315519', 'A_19_P00315524', 'A_19_P00315528', 'A_19_P00315529',\n", " 'A_19_P00315538', 'A_19_P00315541', 'A_19_P00315543', 'A_19_P00315550',\n", " 'A_19_P00315551', 'A_19_P00315554', 'A_19_P00315581', 'A_19_P00315583'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.\n", "print(gene_data.index[:20])\n" ] }, { "cell_type": "markdown", "id": "7ff4f517", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "30427abf", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:10:19.078159Z", "iopub.status.busy": "2025-03-25T06:10:19.078046Z", "iopub.status.idle": "2025-03-25T06:10:19.080138Z", "shell.execute_reply": "2025-03-25T06:10:19.079729Z" } }, "outputs": [], "source": [ "# These identifiers appear to be Agilent microarray probe IDs (A_19_P format)\n", "# These are not standard human gene symbols and would need to be mapped to gene symbols\n", "# They follow the Agilent probe format (A_19_P followed by a number)\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "c73779f3", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "719503d4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:10:19.081618Z", "iopub.status.busy": "2025-03-25T06:10:19.081508Z", "iopub.status.idle": "2025-03-25T06:10:21.677206Z", "shell.execute_reply": "2025-03-25T06:10:21.676828Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['GE_BrightCorner', 'DarkCorner', 'A_23_P117082', 'A_33_P3246448', 'A_33_P3318220'], 'SPOT_ID': ['CONTROL', 'CONTROL', 'A_23_P117082', 'A_33_P3246448', 'A_33_P3318220'], 'CONTROL_TYPE': ['pos', 'pos', 'FALSE', 'FALSE', 'FALSE'], 'REFSEQ': [nan, nan, 'NM_015987', 'NM_080671', 'NM_178466'], 'GB_ACC': [nan, nan, 'NM_015987', 'NM_080671', 'NM_178466'], 'LOCUSLINK_ID': [nan, nan, 50865.0, 23704.0, 128861.0], 'GENE_SYMBOL': [nan, nan, 'HEBP1', 'KCNE4', 'BPIFA3'], 'GENE_NAME': [nan, nan, 'heme binding protein 1', 'potassium voltage-gated channel, Isk-related family, member 4', 'BPI fold containing family A, member 3'], 'UNIGENE_ID': [nan, nan, 'Hs.642618', 'Hs.348522', 'Hs.360989'], 'ENSEMBL_ID': [nan, nan, 'ENST00000014930', 'ENST00000281830', 'ENST00000375454'], 'ACCESSION_STRING': [nan, nan, 'ref|NM_015987|ens|ENST00000014930|gb|AF117615|gb|BC016277', 'ref|NM_080671|ens|ENST00000281830|tc|THC2655788', 'ref|NM_178466|ens|ENST00000375454|ens|ENST00000471233|tc|THC2478474'], 'CHROMOSOMAL_LOCATION': [nan, nan, 'chr12:13127906-13127847', 'chr2:223920197-223920256', 'chr20:31812208-31812267'], 'CYTOBAND': [nan, nan, 'hs|12p13.1', 'hs|2q36.1', 'hs|20q11.21'], 'DESCRIPTION': [nan, nan, 'Homo sapiens heme binding protein 1 (HEBP1), mRNA [NM_015987]', 'Homo sapiens potassium voltage-gated channel, Isk-related family, member 4 (KCNE4), mRNA [NM_080671]', 'Homo sapiens BPI fold containing family A, member 3 (BPIFA3), transcript variant 1, mRNA [NM_178466]'], 'GO_ID': [nan, nan, 'GO:0005488(binding)|GO:0005576(extracellular region)|GO:0005737(cytoplasm)|GO:0005739(mitochondrion)|GO:0005829(cytosol)|GO:0007623(circadian rhythm)|GO:0020037(heme binding)', 'GO:0005244(voltage-gated ion channel activity)|GO:0005249(voltage-gated potassium channel activity)|GO:0006811(ion transport)|GO:0006813(potassium ion transport)|GO:0016020(membrane)|GO:0016021(integral to membrane)|GO:0016324(apical plasma membrane)', 'GO:0005576(extracellular region)|GO:0008289(lipid binding)'], 'SEQUENCE': [nan, nan, 'AAGGGGGAAAATGTGATTTGTGCCTGATCTTTCATCTGTGATTCTTATAAGAGCTTTGTC', 'GCAAGTCTCTCTGCACCTATTAAAAAGTGATGTATATACTTCCTTCTTATTCTGTTGAGT', 'CATTCCATAAGGAGTGGTTCTCGGCAAATATCTCACTTGAATTTGACCTTGAATTGAGAC']}\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", "# 2. 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": "b294a726", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "577eb6f7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:10:21.679088Z", "iopub.status.busy": "2025-03-25T06:10:21.678950Z", "iopub.status.idle": "2025-03-25T06:10:22.319460Z", "shell.execute_reply": "2025-03-25T06:10:22.319095Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping preview:\n", "{'ID': ['A_23_P117082', 'A_33_P3246448', 'A_33_P3318220', 'A_33_P3236322', 'A_33_P3319925'], 'Gene': ['HEBP1', 'KCNE4', 'BPIFA3', 'LOC100129869', 'IRG1']}\n", "\n", "Gene expression data preview (first few gene symbols):\n", "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M', 'A2ML1', 'A2MP1', 'A4GALT',\n", " 'A4GNT', 'AA06'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Shape of the gene expression data: (19847, 32)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Peptic_ulcer_disease/gene_data/GSE60427.csv\n" ] } ], "source": [ "# 1. Determine which columns to use for mapping\n", "# From the gene annotation preview, we see:\n", "# - 'ID' contains probe identifiers like 'A_23_P117082' which match the format in gene_data\n", "# - 'GENE_SYMBOL' contains the human gene symbols we need like 'HEBP1'\n", "\n", "# 2. Get a gene mapping dataframe by extracting the ID and GENE_SYMBOL columns\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')\n", "\n", "# Preview the mapping\n", "print(\"Gene mapping preview:\")\n", "print(preview_df(gene_mapping))\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "# Preview the result to verify the gene symbols\n", "print(\"\\nGene expression data preview (first few gene symbols):\")\n", "print(gene_data.index[:10])\n", "\n", "# Normalize gene symbols to handle synonyms and consolidate redundant entries\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "\n", "# Print the shape of the resulting gene data\n", "print(f\"\\nShape of the gene expression data: {gene_data.shape}\")\n", "\n", "# Save the 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": "d5c570fd", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "d80adf0f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:10:22.321343Z", "iopub.status.busy": "2025-03-25T06:10:22.321226Z", "iopub.status.idle": "2025-03-25T06:10:22.391302Z", "shell.execute_reply": "2025-03-25T06:10:22.390956Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Loaded normalized gene data with shape: (19847, 32)\n", "Loaded clinical data with shape: (3, 25)\n", "Clinical data after transposition: (25, 3)\n", "Gene samples: 32, Clinical samples: 3, Common: 0\n", "No common samples between clinical and gene expression data.\n", "Abnormality detected in the cohort: GSE60427. Preprocessing failed.\n", "Data quality check failed. The dataset is not suitable for association studies.\n" ] } ], "source": [ "# 1. Load the previously normalized gene data and saved clinical data\n", "normalized_gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n", "clinical_data = pd.read_csv(out_clinical_data_file, index_col=0)\n", "\n", "print(f\"Loaded normalized gene data with shape: {normalized_gene_data.shape}\")\n", "print(f\"Loaded clinical data with shape: {clinical_data.shape}\")\n", "\n", "# Transpose clinical data to have samples as columns (matching gene data)\n", "clinical_data_T = clinical_data.T\n", "print(f\"Clinical data after transposition: {clinical_data_T.shape}\")\n", "\n", "# Check which samples are in both datasets\n", "gene_samples = set(normalized_gene_data.columns)\n", "clinical_samples = set(clinical_data_T.columns)\n", "common_samples = gene_samples.intersection(clinical_samples)\n", "print(f\"Gene samples: {len(gene_samples)}, Clinical samples: {len(clinical_samples)}, Common: {len(common_samples)}\")\n", "\n", "# Filter to keep only common samples\n", "if len(common_samples) > 0:\n", " clinical_data_filtered = clinical_data_T[list(common_samples)]\n", " normalized_gene_data_filtered = normalized_gene_data[list(common_samples)]\n", " \n", " # 2. Link the clinical and genetic data using geo_link_clinical_genetic_data\n", " linked_data = geo_link_clinical_genetic_data(clinical_data_filtered, normalized_gene_data_filtered)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " \n", " # The trait column is the first row from clinical data (Peptic_ulcer_disease)\n", " trait_col = linked_data.columns[0]\n", " print(f\"Using trait column: {trait_col}\")\n", " \n", " # Print counts of each trait value to help with debugging\n", " if trait_col in linked_data.columns:\n", " print(f\"Trait values count: {linked_data[trait_col].value_counts().to_dict()}\")\n", " \n", " # 3. Handle missing values in the linked data\n", " linked_data = handle_missing_values(linked_data, trait_col)\n", " print(f\"Shape after handling missing values: {linked_data.shape}\")\n", " \n", " # 4. Determine whether the trait and demographic features are severely biased\n", " is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait_col)\n", " \n", " # 5. Conduct quality check and save the cohort information\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_trait_biased, \n", " df=unbiased_linked_data,\n", " note=\"Dataset contains gastritis grade information as a proxy for peptic ulcer disease.\"\n", " )\n", " \n", " # 6. If the data is usable, save it\n", " if is_usable:\n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " # Save the data\n", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", " else:\n", " print(\"Data quality check failed. The dataset is not suitable for association studies.\")\n", "else:\n", " print(\"No common samples between clinical and gene expression data.\")\n", " # Create a record indicating the dataset is not usable\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=True,\n", " is_biased=True, \n", " df=pd.DataFrame(),\n", " note=\"No common samples between clinical and gene expression data.\"\n", " )\n", " print(\"Data quality check failed. The dataset is not suitable for association 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 }